Osman Osman - 14 days ago 7
jQuery Question

How to change the background colour twice with a delay in between? jQuery

I am currently using the code below to change the colour of an Input field twice when clicked on.

The expected outcome is that the background colour changes to black and then waits before changing to white (and staying at white until the user clicks on the field again).

However, the colour switches straight to white ignoring the first Black colour. How do I fix this?

$('input:text').focus(function () {
$(this).css('background','#000').delay(5000).css('background','#fff');
});

Answer

If you want to use css() then you will need to use a setTimeout. css() does not animate so there is no internal animation queue for delay() to work with, such as with animate().

$('input:text').on('focus', function () {
    $(this).css('background','#000');

    setTimeout(function(){
        $(this).css('background','#fff');
    }, 5000);
});