Reputation:
so i have something like so (below), everything works in turn (it's hidden at the start, then you see it slide down, waits 2 seconds, and slides back up) but the .css action takes place immediately, even though it's after the 2 second delay. Just wondering why this is.
$('p:first')
.hide()
.slideDown('slow')
.delay(2000)
.css({"background-color":"#ff4"})
.slideUp('slow')
});
EDIT NEW CODE: I have changed my code to this: which doesn't seem to slideUp anymore.. (as I want it to change to yellow right before sliding up)
$('p:first')
.hide()
.slideDown('slow')
.delay(2000, function(){
$(this).css({"background-color": "#ff4"})
})
.slideUp('slow')
});
Upvotes: 5
Views: 2456
Reputation: 262929
That's because delay() only affects the animation queue. Method chaining occurs as soon as the previous call returns, so css() (which is not an animation) ends up being called too soon.
You can pass a callback function to slideUp(), and it will be called when the animation is complete:
$("p:first").hide()
.slideDown("slow")
.delay(2000)
.slideUp("slow", function() {
$(this).css("background-color", "#ff4");
});
EDIT: You're trying to pass a callback to delay()
in your second code snippet, but that method does not officially support such an argument (it still gets called, though, which is interesting). However, doing that breaks the animation callback chain, as you can see, since slideUp()
is never called.
In this situation, you can inject your own function in the animation queue, using the aptly-named queue() and dequeue() methods:
$("p:first").hide()
.slideDown("slow")
.delay(2000)
.queue(function() {
$(this).css("background-color", "#ff4")
.dequeue();
}).slideUp("slow");
Upvotes: 5
Reputation: 413720
The ".css()" call is a synchronous operation, but all the others are animations. The animation functions all return immediately after queueing up the operation for later.
There's a way to queue up your own code in the animation queue, I think, but I won't type in a guess; I'll make a quick check of the documentation.
edit — ok what you'd do is this:
$('p:first')
.hide()
.slideDown('slow')
.delay(2000)
.queue(function(next)
$(this).css({"background-color":"#ff4"});
next();
})
.slideUp('slow')
});
Seems like using the callbacks as others suggested should work too.
Upvotes: 3
Reputation: 78520
Change the css in the callback
$('p:first')
.hide()
.slideDown('slow')
.delay(2000)
.slideUp('slow',function(){
$(this).css({backgroundColor:"#ff4"})
})
Upvotes: 2