Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I differentiate a manual scroll (via mousewheel/scrollbar) from a Javascript/jQuery scroll?

UPDATE:

Here is a jsbin example demonstrating the problem.

UPDATE 2:
And here is the fixed version thanks to fudgey.


Basically, I have the following javascript which scrolls the window to an anchor on the page:

 // get anchors with href's that start with "#"  $("a[href^=#]").live("click", function(){      var target = $($(this).attr("href"));      // if the target exists: scroll to it...      if(target[0]){          // If the page isn't long enough to scroll to the target's position          // we want to scroll as much as we can. This part prevents a sudden           // stop when window.scrollTop reaches its maximum.          var y = Math.min(target.offset().top, $(document).height() - $(window).height());          // also, don't try to scroll to a negative value...          y=Math.max(y,0);          // OK, you can scroll now...          $("html,body").stop().animate({ "scrollTop": y }, 1000);      }      return false;  }); 

It works perfectly......until I manually try to scroll the window. When the scrollbar or mousewheel is scrolled I need to stop the current scroll animation...but I'm not sure how to do this.

This is probably my starting point...

$(window).scroll(e){     if(IsManuallyScrolled(e)){         $("html,body").stop();     } }  

...but I'm not sure how to code the IsManuallyScrolled function. I've checked out e (the event object) in Google Chrome's console and AFAIK there is not way to differentiate between a manual scroll and jQuery's animate() scroll.

How can I differentiate between a manual scroll and one called via jQuery's $.fn.animate function?

like image 976
David Murdoch Avatar asked May 14 '10 13:05

David Murdoch


People also ask

What is the difference between scroll to and scroll bar?

A scroll bar's orientation determines the direction in which scrolling occurs when the user operates the scroll bar. A horizontal scroll bar enables the user to scroll the content of a window to the left or right. A vertical scroll bar enables the user to scroll the content up or down.

What is scroll in Javascript?

Definition and UsageThe scroll event occurs when the user scrolls in the specified element. The scroll event works for all scrollable elements and the window object (browser window). The scroll() method triggers the scroll event, or attaches a function to run when a scroll event occurs.


1 Answers

Try this function:

$('body,html').bind('scroll mousedown wheel DOMMouseScroll mousewheel keyup', function(e){  if ( e.which > 0 || e.type == "mousedown" || e.type == "mousewheel"){   $("html,body").stop();  } }) 

Also, did you see this tutorial?

Update: Modern browsers now use "wheel" as the event, so I've included it in the code above.

like image 155
Mottie Avatar answered Oct 14 '22 09:10

Mottie