jessica
jessica

Reputation: 1687

Changing div to a different color, wait 3 seconds, before changing color back using jQuery

I have a jQuery code that is suppose to make a div blue, and then wait 3 seconds, before making it back to black. But it's just staying at its original color, black, and not changing to blue at all, before changing back to black. What am I doing wrong?

<div id = "div" style="width:250px;height:250px; background-color:black;"></div>

$(function(){

$("#div").css({"background-color" : "blue"})
         .delay(3000)
         .css({"background-color" : "black"});

}) //end of $(function())

Here's a fiddle: http://fiddle.jshell.net/5wjy9aqu/1/

Upvotes: 0

Views: 2424

Answers (3)

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167172

Please use animate() and also include jQueryUI for animating colours.

$(function () {
    $("#div").animate({
        "background-color": "blue"
    }, 1000)
    .delay(3000)
    .animate({
        "background-color": "black"
    }, 1000);
});

Fiddle: http://fiddle.jshell.net/zydLvbuf/

Well, if you don't wanna add the whole jQueryUI, you can also add a custom plugin for just animating the colours.

$("#block").animate({
  backgroundColor: $.Color({ saturation: 0 })
}, 1500 );

Upvotes: 1

DRD
DRD

Reputation: 5813

In a modern browser you can also use the following CSS-only solution: http://fiddle.jshell.net/otzm74xk/.

CSS:

#div {
    width: 250px;
    height: 250px;
    background-color: blue;
    animation: blacken 0s linear 3s 1 forwards;
}

@keyframes blacken {
    100% {
        background-color: black;    
    }
}

Upvotes: 0

MinusFour
MinusFour

Reputation: 14423

It's because delay doesn't work like that.

You can always do it like this:

$('#div').css("background-color", "blue");
setTimeout(function(){
    $('#div').css("background-color", "black");
}, 3000);

You can also use, queue if you really insisit on delay.

$('div').css('background-color', 'blue').delay(3000).queue(function(){
     $(this).css('background-color', 'black');
     $(this).dequeue();
});

Which if you ask me, is not really a good option.

Upvotes: 5

Related Questions