简体   繁体   中英

Javascript stop animation when scrolling stops

I'm trying to have an animation play whilst the user is scrolling and stop when they stop.
I know very little javascript, but from hunting around and adapting I've got as far as making it start on scrolling, but then it keeps going and I can't figure out how to make it stop as soon as the scrolling ends.

Here's what I have so far:

$(window).scroll(function() {
    $('#square').animate({
        top: '70px',
        queue: true,
    }, 900).animate({
        top: '5px',
        queue: true
    }, 1000);
});

Fiddle

Any help greatly appreciated!

You could use a timer as follows:

var timer;

$(window).scroll(function() {

    clearTimeout(timer);
    timer = setTimeout( refresh , 150 );

    $('#square').animate({
        top: '70px',
        queue: true,
    }, 900).animate({
        top: '5px',
        queue: true
    }, 1000);

});

var refresh = function () { 
// do stuff
    $('#square').stop().clearQueue();
};

FIDDLE

Reference: Event when user stops scrolling

Updated your JSFiddle using reference from another Stack Overflow question .

This will display to you when there is a scroll event occurring and when the scroll event stops.

The core of what you want is $('#square').stop().clearQueue(); though.

I've accomplished this with underscore's debounce and jquery:

https://github.com/michaelBenin/node-startup/blob/master/client/js/core/scroll_manager.js

To stop the animation see: http://api.jquery.com/stop/

Also see this library for animations: http://julian.com/research/velocity/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM