Arif YILMAZ
Arif YILMAZ

Reputation: 5866

jquery change div's background color to blink

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

Answers (2)

Fabrício Matté
Fabrício Matté

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

Fiddle

Upvotes: 4

adeneo
adeneo

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

FIDDLE

Upvotes: 1

Related Questions