5

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?

1
  • 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. Commented Jun 30, 2019 at 14:59

3 Answers 3

19

Vanilla Javascript

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

el.dispatchEvent(new Event('scroll'));
Sign up to request clarification or add additional context in comments.

2 Comments

Is there a jQuery code to do exactly the same thing?
If .trigger('scroll') is not working, then $(document).get(0).dispatchEvent(new Event('scroll'));
5

Try this jsFiddle.

$('.e1').scroll(function(e){
    $('.e2').scrollTop(parseInt($('.e1').scrollTop()));
});

1 Comment

Be wary using parseInt(...) here, because there could be floating point values when the user zoomed his/her browser in/out.
4

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.