Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Blinking a div with background-color in jquery using setInterval

the code :

<div id="divtoBlink" ></div>

css:

#divtoBlink{
 width:100px;
 height:20px;
 background-color:#627BAE;
}

javascript:

setInterval(function(){
  $("#divtoBlink").css("background-color","red");
  },100)

but nothing is happening can anyone tell me what i am doing wrong ?

fiddle Here

like image 665
Sora Avatar asked Sep 27 '13 11:09

Sora


2 Answers

I suggest you don't change the color with javascript. It's better practice to do this via CSS. Changing styles should be done in a stylesheet, not in JS (in case if you want other/more properties changed).

You toggle a class, that class has a background definition (in this example, if you want you can add more properties). A fiddle as DEMO

<div id="divtoBlink" ></div>

.blinker{
    background: red;
}

let $div2blink = $("#divtoBlink"); // Save reference for better performance
let backgroundInterval = setInterval(function(){
    $div2blink.toggleClass("blinker");
 },100)

If you feel like a wild mood, you can add some css3 animation to it

#div2blink{
    transition: backgroundColor 0.05s ease-in-out;
}

Made a demo for the animation: DEMO (I slowed it down in the example!)

like image 117
Martijn Avatar answered Oct 07 '22 05:10

Martijn


DEMO

setInterval(function () {
    $("#divtoBlink").css("background-color", function () {
        this.switch = !this.switch
        return this.switch ? "red" : ""
    });
}, 100)
like image 21
A. Wolff Avatar answered Oct 07 '22 04:10

A. Wolff