Search code examples
jquerycssdelay

delaying jquery css changes


I have written a code which makes a border of a div orange then after a second or two changes it to black, however what is actually happening is that it goes straight to black, any help please? thanks!

Code:

$('#newMessage1').css('border','2px solid #ffa800').delay(100).css('border','2px solid #000000');

Solution

  • The jQuery delay function only works on functions added to the fx queue (functions like fadeIn or slideDown). css is not one of these functions (try to delay any other non-fx-queue aware function and it won't work either).

    From the docs:

    Added to jQuery in version 1.4, the .delay() method allows us to delay the execution of functions that follow it in the queue. It can be used with the standard effects queue or with a custom queue. Only subsequent events in a queue are delayed; for example this will not delay the no-arguments forms of .show() or .hide() which do not use the effects queue.

    jQuery delay is not a substitute for the native JS setTimeout, which in this case would probably be the way to go. You could, for example, do something like this (working example here):

    $('#newMessage1').css('border','2px solid #ffa800');
    
    setTimeout(function() { 
        $("#newMessage1").css('border','2px solid #000000'); 
    }, 1000);