Wil Prim Wil Prim - 5 months ago 15
CSS Question

.delay() not working when changing background-color of <div>

I am just learning JQUERY and I have been playing around with delay() I wrote a fiddle to show you... What I am trying to do is when a button is clicked, change the background-color of the div and then after a few moments switch the background color again. But when I try it, it just switches to the second color and skips the first.

HTML:

<div class = "animation">


</div>

<button id = "change"> Click </button>


Here is the Jquery code:

$(document).ready(function(){
$("#change").click(function(){

$(".animation").css("background", "blue").delay(700).css("background", "red");


});
});


Here is the link:

JSFiddle

Answer

delay only works for items in the queue (such as animations).

For anything else, use a regular old timer:

$("#change").click(function() {
    var $el = $(".animation");

    $el.css("background", "blue");

    setTimeout(function () {
        $el.css("background", "red");
    }, 700);
});
Comments