29

I want to make it so that a webpage automatically scrolls to a certain element, however I don't want the scrolling to fight user input-- If it begins to scroll and then the user scrolls, I want the automated scrolling to stop and let the user have full control.

So I originally thought I could do something like this:

var animatable = $('body, html');
animatable.animate({scrollTop: $('#foo').offset()}, 1000);

$(window).scroll(function() { animatable.stop(); });

however, the problem is-- the animation of the scrollTop triggers the scroll event handler for window! So, the animation begins and then stops immediately.

I am looking for a way that I can make my window scroll event handler only stop if it's triggered by user input... Is this possible?

patrick
  • 8,078
  • 8
  • 53
  • 98

1 Answers1

56

Diode's solution didn't work for me - scroll() didn't differentiate between the animation and the user, meaning the animation stopped immediately. From a different post, the following works for me (modified for this purpose):

// Assign the HTML, Body as a variable...
var $viewport = $('html, body');

// Some event to trigger the scroll animation (with a nice ease - requires easing plugin )...
$('#element').click(function() {
    $viewport.animate({ 
        scrollTop: scrollTarget // set scrollTarget to your desired position
    }, 1700, "easeOutQuint");
});

// Stop the animation if the user scrolls. Defaults on .stop() should be fine
$viewport.bind("scroll mousedown DOMMouseScroll mousewheel keyup", function(e){
    if ( e.which > 0 || e.type === "mousedown" || e.type === "mousewheel"){
         $viewport.stop().unbind('scroll mousedown DOMMouseScroll mousewheel keyup'); // This identifies the scroll as a user action, stops the animation, then unbinds the event straight after (optional)
    }
});                 
Community
  • 1
  • 1
Tom Bates
  • 3,132
  • 2
  • 18
  • 13
  • 2
    That worked like a charm. Thanks for answering this question. – ghayes Oct 06 '12 at 07:56
  • 10
    For touch screen devices you will need to add `touchstart` to your list of events, and check for it in the event itself `... || e.type == 'touchstart'` – Ben Fleming Aug 27 '14 at 02:26
  • @Benjammin' - good tip, small nitpick - use `===` rather than `==` – Ohad Schneider Apr 07 '15 at 14:05
  • 1
    @OhadSchneider Yeah implicit conversion can bite you in the ass, but I don't think this situation has really any risk of a false positive. But yeah, go ahead and use the triple equals, probably better that way. – Ben Fleming Apr 07 '15 at 23:56