I started learning jQuery today and I’m facing an issue, I was under the impression that the order you write code in jQuery is the order it executes it, apparently I’m wrong. for example I’d like to tell it to put my text blue but then change it to red. I can’t get that to work because it seems to fight for the element (my guess is it runs at the sametime all functions), even if I put in a delay. Any ideas on this?
here’s my code: http://jsfiddle.net/jZUzP/
$(document).ready(function(){
$(".post").css({"color":"#0000FF"})
.delay(800)
.css({"color":"##FF0000"});
});
In a general sense jQuery code is executed in the order it appears, the same as for any other JavaScript code. However, functions that make use of
setTimeout()or Ajax may execute something after a delay.In the case of the code from your question, you are using the
.delay()method, which adds a delay only to jQuery animation effects, and the.css()method does not participate in animation. So as indicated in Felix’s comment, the two css changes happen immediately after each other, too fast to see the first colour.More specifically, your first
.css()call happens, then the.delay()call happens but what it does is add a delay to the animation queue and then return immediately, and then your second.css()call happens. If you then queued up other animation effects they would happen after the delay. Browsers run JavaScript in a single thread, so you won’t ever have two blocks of code running at the same time – and note that that single thread is also the one the browser uses to render (which is why long-running loops make the browser unresponsive).So, you might naturally ask, isn’t there a way to change css settings in a way that does participate in jQuery’s animation process? Well yes, you can use the
.animate()method – except that it doesn’t work on colours. At least, not by default. But if you include the jQuery UI extension to jQuery then you can use.animate()to change colours as follows:Demo: http://jsfiddle.net/jZUzP/1/
Note that the above called
.animate()with a duration of 0 so that the colour change would be instantaneous.Further reading:
.animate()doco.animate()docoIf you don’t want to include jQuery UI as well as jQuery just for something simple like this you can of course use the (non-jQuery, standard JS)
setTimeout()function to queue up your second css change:(jQuery animation effects use
setTimeout()internally.)