Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
189
rated 0 times [  192] [ 3]  / answers: 1 / hits: 17629  / 13 Years ago, sat, january 14, 2012, 12:00:00

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?


More From » jquery

 Answers
45

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)
}
});

[#88028] Thursday, January 12, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
aubriechantalr

Total Points: 380
Total Questions: 95
Total Answers: 86

Location: Guadeloupe
Member since Sat, Aug 22, 2020
4 Years ago
;