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 ?
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 ?
Share Improve this question edited Aug 6, 2015 at 13:48 Shafizadeh asked Aug 6, 2015 at 8:59 ShafizadehShafizadeh 10.4k15 gold badges58 silver badges92 bronze badges4 Answers
Reset to default 3I 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
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);
});
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.
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);
});