1

How can i use jQuery to change the CSS attributes of a HTML element with delay.

Imagine this scenario. I have a div with bg color blue. I want it to fade out and when it fades back in i want the bg color to be red.

I tried this.

$("div").fadeOut().delay(500).css("background-color","red").fadeIn();

While fading out the div already changes the color to red before it fades in. It does not follow the sequence of chained events. How can I make this happen in one single line.

2 Answers 2

4

You can have any function participate in the animation queue using the queue function:

$("div")
    .fadeOut()
    .delay(500)
    .queue(function() {
        $(this).css("background-color","red").dequeue();
    })
    .fadeIn();

Note the dequeue call within the callback, which is what tells jQuery to continue with the next thing in the queue.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes. This is what i wanted. Thanks for the explanation too
2
$("div").fadeOut(500, function() {
    $("div").css("background-color","red").fadeIn()
});

2 Comments

The setTimeout version was fine. This version won't delay the way the OP's code seems to want.
+1 for a good solution. However you took out my delay option. The 500ms seems to applied on the fadout now. and there is no delay :(

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.