Search code examples
jquerycssdelay

Remove or add css style on click after a few seconds


How can I remove or add .css() but with delay? In my example I add a border color when I click .s_edit and remove it when I click .s_done. The problem is that I don't want to remove the border color instantly, but after 2seconds. looks like .delay() does not work and I have no idea how to use setTimeout or something similar.

JSFiddle: http://jsfiddle.net/5Bc3K/1/

HTML:

<div class="main">
    <a href="#" class="s_edit">Edit</a>    
    <a href="#" class="s_done">Done</a>
</div>

JQUERY:

$('.s_edit').click(function(e){
    e.preventDefault();

    var parent = $(this).parents('.main');    
    parent.css('border-color', 'red');
    $(this).hide();
    $('.s_done', parent).show();

});

$('.s_done').click(function(e){
    e.preventDefault();

    var parent = $(this).parents('.main');    
    parent.delay(2000).css('border-color', '');
    $(this).hide();
    $('.s_edit', parent).show();

});

Solution

  • Try this:

    $('.s_done').click(function(e){
        e.preventDefault();
        var parent = $(this).parents('.main');
        setTimeout(function() {
            parent.css('border-color', '');
        }, 2000);
        $(this).hide();
        $('.s_edit', parent).show();
    });