2

I want to set a CSS attribute for a element (div) just for 2 sec. here is my try:

html:

<div class="div">foo</div>
<input class="btn" type="button" value="click" />

jquery:

$(".btn").click(function(e) {
   $(".div").css({"border": "1px solid #ccc"});
});

But the above code will be applied for ever, how can I limit it for a specific period ?

Shafizadeh
  • 9,960
  • 12
  • 52
  • 89

4 Answers4

3

I think you could use something like this :

$(".btn").click(function(e) {
    $(".div").css({"border": "1px solid #ccc"});
    setTimeout(function(){
        $(".div").css({/* Your initial css */});
    }, 2000);
});
Mteuahasan
  • 491
  • 2
  • 10
3

I think using css class maybe the best solution just because i don't know the prev border style or the others css rules applied to the element:

css

.borderStyle{
    border: 1px solid #ccc!important;
}

js

$('.btn').click(function(){
    $('.div').addClass("borderStyle");
    setTimeout(function(){ $('.div').removeClass("borderStyle"); }, 2000);
});

toggle class version

$('.btn').click(function(){
    $('.div').toggleClass("borderStyle");
    setTimeout(function(){ $('.div').toggleClass("borderStyle"); }, 2000);
});

fiddle

don't know why the toggleclass don't work for you but lets keep it shown in my answer for future reviews

Vanojx1
  • 5,574
  • 2
  • 23
  • 37
2

Pretty simple, add a setTimeout() and let that run after 2 seconds and let it remove the border.

$(".btn").on("click", function() {
    $('.foo').css('border', '1px solid #ccc');
    setTimeout( function() { 
        $('.foo').css('border', 'none');
    }, 2000);
});

Working JSFIDDLE

As you can see, I have replaced your .click() with .on(). Read here why it's better to use .on() and here how you use it.

Community
  • 1
  • 1
Rvervuurt
  • 8,589
  • 8
  • 39
  • 62
1

After two seconds to remove css atribute:

$(".btn").click(function(e) {
   $(".div").css({"border": "1px solid #ccc"});
   setTimeout(function() { 
       $(".div").css({
           'border' : 'none',
           'width' : '30px',
           'top' : '10px',
           'left' : '30px',
           'bottom' : '10px',
           'right' : '30px'
       });
   }, 2000);
});
Akul Von Itram
  • 1,428
  • 2
  • 20
  • 31