1

Is there a way to fire an actual mouse scroll event while auto scrolling?

I am using the following piece of code to emulate auto scrolling

setInterval(function scroll() {
  for (var i = 0; i < 4000; i += 800) {
    $("html, body").animate({
      scrollTop: i
    }, 500).delay(500);
  }

I somehow want to call a mouse wheel scroll event each time an auto scroll occurs

$(window).on('wheel', function(event){

});

2 Answers 2

1

There is a scroll event in jQuery, you can use it to bind a handler (docs.https://api.jquery.com/scroll/), something like so:

$("html, body").on('scroll', function(){ alert('Scrolled'); });

By the way the scroll event would fire multiple times while scrolling, so it's really not a good idea to fire your handler all the time, you should take a look at the debounce function for a way to tackle that problem (https://davidwalsh.name/javascript-debounce-function)

Sign up to request clarification or add additional context in comments.

4 Comments

As you can see, I am trying to emulate an actual mouse scroll to the bottom of the page. During a real mouse scroll, does the scroll event fire multiple times?
Yes, it fires multiple times during an 'actual' scroll, and during the execution of the animate('scrollTop'...) function as well. What are you trying to achieve, in your post the handler is empty, and you say that you want to call a 'wheel' event, when you are trying to handle it in your code, while you are successfully calling the animate scrollTop event?
No I am not sure of what I am doing, that's why I posted it here. I want to emulate an actual scroll (you know with pauses). Does my original code suffice? If no, can you post the code as per your understanding?
Yes your original code should suffice for the scrolling, have you tried it yet? You can remove the 'on.('wheel'...' function, you don't need it to scroll the page, rather to take another action on each scroll (automatic or not), so just remove it and you should be okay
0

You can simply add your event handler inside the setInterval.

setInterval(function scroll() {
  for (var i = 0; i < 4000; i += 800) {
    $("html, body").animate({
      scrollTop: i
    }, 500).delay(500);

    // do also something else (event handler)
  }

1 Comment

Yeah I want to trigger the 'wheel' event for each scroll. As you can see, I am attempting to emulate it as close as possible to a real mouse scroll. I can't seem to get my head around how to trigger a 'wheel' event.

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.