Reputation: 5866
I want to change the color of div and change it back to the original colur after a second. but I want to do it 2-3 times in a row to get the attention of the user.
here is the jquery code which changes the color to red and changes back to the original ONLY ONCE.
$('.b').on('click', function() {
var $el = $(".a"),
x = 500,
originalColor = $el.css("background");
$el.css("background", "red");
setTimeout(function(){
$el.css("background", originalColor);
}, x);
});
How can I change the color and change it back 3 times?
Upvotes: 1
Views: 4104
Reputation: 70149
Using a recursive setTimeout
:
$('.b').on('click', function () {
var $el = $(".a"),
x = 500,
originalColor = $el.css("background"),
i = 3; //counter
(function loop() { //recurisve IIFE
$el.css("background", "red");
setTimeout(function () {
$el.css("background", originalColor);
if (--i) setTimeout(loop, x); //restart loop
}, x);
}());
});
Upvotes: 4
Reputation: 318182
$('.b').on('click', function() {
var i = 0,
orgCl = $('.a').css("background"),
timer = setInterval(function() {
$('.a').css('background', 'red').delay(500).show(1, function() {
$('.a').css('background', orgCl).delay(500).show(1, function() {
if (i++ > 2) clearInterval(timer);
});
});
},1000);
});
Upvotes: 1