Andrei Surdu
Andrei Surdu

Reputation: 2341

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();

});

Upvotes: 0

Views: 4743

Answers (2)

Romain
Romain

Reputation: 1948

If you want to use JQuery, swap your function setTimeout with the animate function. The animate function is more powerful and customizable .

However, you don't really need to customise your script. You can simply add some CSS effects like this:

CSS

#box{
 position : relative;
 width : 100px;
 height : 100px;
 background-color : gray;
 border : 5px solid black;    
 -webkit-transition : border 500ms ease-out; 
 -moz-transition : border 500ms ease-out;
 -o-transition : border 500ms ease-out;
}

Here is a working link: Border nicely fading

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337560

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();
});

Upvotes: 2

Related Questions