Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scrolling 2 different elements in same time

Tags:

javascript

dom

If i have a textarea element and a div element how can i scroll them both in one time? ( when i scroll textarea i want the div to do the same )

I want to use pure javascript, as simple code as it is possible.

Ty.

like image 294
John Avatar asked Aug 18 '11 13:08

John


2 Answers

As answered here: synchronize two scrolling bars in multiple selection box

var s1 = document.getElementById('Select1');
var s2 = document.getElementById('Select2');

function select_scroll_1(e) { s2.scrollTop = s1.scrollTop; }
function select_scroll_2(e) { s1.scrollTop = s2.scrollTop; }

s1.addEventListener('scroll', select_scroll_1, false);
s2.addEventListener('scroll', select_scroll_2, false);
like image 110
red Avatar answered Nov 08 '22 19:11

red


While the question asked about doing it in pure JavaScript, if you want to do this with jQuery, all you need to do is tie the scrollTop property of one element to the scrollTop of the other, using a function tied to the scroll event.

Something along the lines of:

$('.linked').scroll(function(){
    $('.linked').scrollTop($(this).scrollTop());    
})

With that function, all elements with a class of linked will scroll whenever you use the scrollbars of one of them. (I assumed vertical scrolling, if you wanted horizontal, do the same but with scrollLeft.)

See http://jsfiddle.net/g8Krz/ for a working example of the above.

like image 25
K6t Avatar answered Nov 08 '22 19:11

K6t