Search code examples
jqueryanimationqueuedelay

JQuery problem with stop() and delay() within animation


As you can see on http://jsfiddle.net/FrelCee/5zcv3/4/ , i want to animate those 3 divs when the container is hovered.

Problem is this ugly queue that appears when you fast hover more than once. I also tried using .stop() function, but then the delay() isn't working.

Here is an example with stop() function and delay() problem : http://jsfiddle.net/FrelCee/FHC99/22/

Does anyone know any better way to this?

Thanks in advance!


Solution

  • You just need to supply at least the first parameter to .stop(true, true) to clear the current queue and you can decide if you also want to supply the second parameter to jump to the end of the animation when the next one starts (that's up to you as it gives a slightly different effect). You also need to place the .stop() calls before the .delay() so you aren't clearing the .delay(). See the jQuery doc for .stop() to understand the two parameters for .stop(). When I do that here: http://jsfiddle.net/jfriend00/pYgQr/, it seems to handle fast hover in/out just fine.

    // On hover function
    var hover = $('#container');
    hover.hover(function(){
    
        $(this).find('#first').stop(true, true).animate({left:10}, 600);
        $(this).find('#second').stop(true, true).delay(100).animate({left:10}, 600);
         $(this).find('#third').stop(true, true).delay(250).animate({left:10}, 600);
    
    }, function() {
    
        $(this).find('#first').stop(true, true).animate({left:-100}, 600);
        $(this).find('#second').stop(true, true).delay(100).animate({left:-100}, 600);
        $(this).find('#third').stop(true, true).delay(250).animate({left:-100}, 600);
    
    }); // on mouse out hide divs
    

    Also, I don't know why you're doing this at the beginning:

    var hover = $('#container');
    $(hover).hover(function(){
    

    You can either do this:

    var container = $('#container');
    container.hover(function(){
    

    or this:

    $('#container').hover(function(){
    

    In addition, there is no reason to do:

    $(this).find('#first')
    

    These are ids which must be unique in the page so it's better to use:

    $('#first')
    

    This will be faster in jQuery because it will be able to just use document.getElementById('first') internally.