1

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!

Anubhav
  • 7,138
  • 5
  • 21
  • 33
Runcible
  • 13
  • 3

3 Answers3

2

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

Community
  • 1
  • 1
Anubhav
  • 7,138
  • 5
  • 21
  • 33
1

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.

Community
  • 1
  • 1
Xenyal
  • 2,136
  • 2
  • 24
  • 51
0

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/

Michael Benin
  • 4,317
  • 2
  • 23
  • 15