Runcible
Runcible

Reputation: 13

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!

Upvotes: 1

Views: 436

Answers (3)

Xenyal
Xenyal

Reputation: 2223

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.

Upvotes: 1

Michael Benin
Michael Benin

Reputation: 4332

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/

Upvotes: 0

Anubhav
Anubhav

Reputation: 7208

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

Upvotes: 2

Related Questions