Making two textareas horizontally scroll in sync

Viewed 418

I have two textarea boxes and I want both of them to horizontally scroll simultaneously, based on the scroll bar at the bottom. The Following program I have written works fine as long as both textarea boxes have the same amount of texts/width. As you can see, my first text box has more text than the second; therefore, when I scroll using the scroll bar at the bottom text box, I will not see the full text on the first box. Please run the code to see the issue. Is there a way I can increase the scrolling area of the bottom text box area to match the scrolling requirement of the first box?

  //Java Script Code
  var headbox = document.getElementById('head_text_area');
  var bodybox = document.getElementById('main_text_area');
  bodybox.addEventListener('scroll', select_scroll, false);

  function select_scroll(e) {
    headbox.scrollLeft  = bodybox.scrollLeft;        
  }
/*CSS style*/
#main_text_area, #head_text_area{
  resize: none;  
  white-space: nowrap; /*All the text user types without pressing an enter should be in one line*/
  width: 100%;
}

#head_text_area::-webkit-scrollbar {
    display: none;/*First text box should not show a scroll bar*/
}
<textarea rows="6" id="head_text_area" width="100%" disabled>
This line is longer than the line in the second text area. At the start of the website, I won't be able to scroll to the right to see all the text in this area. Unless I put more texts on the bottom text area box. 
More text might be here. The horizontal scroll bar of this section is hidden.   
   </textarea><br><br>

  <textarea id="main_text_area" rows="6" width="100%"> 
This box isn't as long as the other text area. Therefore, scroll bar in this is short. This limits the viewable area of first box. 
  </textarea>

1 Answers

To make a simple scrolling motion which will be equal on both scroll bars depending on the lower one. You will have to convert the values of the scroll bars to percentage values. For this to work there has to be some scrollable content in the lower text area.

Here is an update to the function which implements percentage values

function select_scroll(e) {
    let percent = bodybox.scrollLeft / (bodybox.scrollWidth - bodybox.clientWidth);
    headbox.scrollLeft =  (headbox.scrollWidth - headbox.clientWidth)* percent;
}
Related