Nino
Nino

Reputation: 15

Event order jQuery

I've a HTML aside element on my page and I've appended the element some effects (animating). I'm almost done, but I cannot figured it out why the animations for some reason executes disordered...please concentrate on the second function if it is possible because I don't want to mess up a code that works perfectly

$(document).ready(function(){
$("aside, #top").hover(function(){
    $("aside").animate({width:100}, 700);
    $("#top").animate({width:100}, 700);
    $("#navigation").show();
});

$("aside, #top").mouseleave(function(){
    $("aside").animate({width:10}, 700);
    $("#top").animate({width:10}, 700);
    $("#navigation").hide();
});

The last one

$("#navigation").hide();

Is executed before the other two in the same function. Why?

Upvotes: 0

Views: 69

Answers (2)

Fresheyeball
Fresheyeball

Reputation: 30015

The reason hide is executed 'first' is that all three are being executed at the same time. To order animations you need to use callbacks or chaining. http://api.jquery.com/animate/

The callback will run after the animation has finished. It only appears to run first because .hide takes no time at all, but the animations take 700ms to run.

You could also use a timeout if you want the .hide to occur at a specific point in the animation cycle.

$("aside, #top").mouseleave(function(){
    $("aside").animate({width:10}, 700);
    $("#top").animate({width:10}, 700, function(){
         $("#navigation").hide();
    });        
});

or

$("aside, #top").mouseleave(function(){
    $("aside").animate({width:10}, 700);
    $("#top").animate({width:10}, 700);
    setTimeout(function(){
         $("#navigation").hide();
    }, 700);        
});

(psst. "Append" means something closer to concatenate, you don't append effects to elements, you attach them. And animation operations are not events, so its not an event order problem, its an execution order problem. Cheers.)

Upvotes: 2

gdoron
gdoron

Reputation: 150253

Use a callback:

$("#top").animate({width:10}, 700, function(){
    $("#navigation").hide();
});

Regarding to why, An easy explanation: it's because the first two lines takes time to finish while the last runs and finish right away, before those two finished.

Upvotes: 2

Related Questions