4

I have two independent web elements, if I scroll the content of one element, I also want the 2nd element scroll at same time. Here is an example: https://stackedit.io

I did the following code, but it is not working:

element.find('.fullscreen-mk-content-textarea').on('scroll', function(e){
    // first element will trigger this event, then manully trigger the 
    // the scroll of the 2nd element. It's my plan. 
    console.log(e); // works
    element.find('.right-side').trigger('scroll'); // doesn't work...
});

What shall I do?

Adrian Forsius
  • 1,437
  • 2
  • 19
  • 29
Nicolas S.Xu
  • 13,794
  • 31
  • 84
  • 129
  • Romeo's answer actually works, just don't forget that ID selector uses hash (#) instead of full stop (.) Hope this helped some beginner like me, who tries to find out how to trigger event on scroll. – Norwak Jun 30 '19 at 14:59

3 Answers3

17

Vanilla Javascript

var el = document.querySelector(".right-side");

el.dispatchEvent(new Event('scroll'));
Firanolfind
  • 1,559
  • 2
  • 17
  • 36
4

Try this jsFiddle.

$('.e1').scroll(function(e){
    $('.e2').scrollTop(parseInt($('.e1').scrollTop()));
});
Romeo
  • 521
  • 5
  • 20
  • Be wary using `parseInt(...)` here, because there could be floating point values when the user zoomed his/her browser in/out. – Tim Visser Aug 22 '22 at 12:52
3

You can just set the scrollTop value of the other to match. That will cause it to scroll a desired amount. That's how you scroll something. It won't cause it to scroll by trying to trigger a scroll event. A scroll event is an indicator of some scroll motion, not something that causes scroll motion.

If using jQuery, you can use .scrollTop() to retrieve the current value of the scroll or .scrollTop(val) to set the amount of scroll.

jfriend00
  • 683,504
  • 96
  • 985
  • 979