0

I'm trying to make a css background flash between two colours. The best solution seemed to be using a recursive function shown on a similar question:

(function pulse(){
        $('#my_div').delay(100).css("background-color","blue").delay(100).css("background-color","red").delay(100).fadeIn('slow',pulse);
})();​

http://jsfiddle.net/bSWMC/223/

I can't seem to get the background switching colours. There may be a really obvious answer here, I'm new to jQuery!

Many thanks for your help, jeremy

Ram
  • 143,282
  • 16
  • 168
  • 197
Jeremy Affolter
  • 133
  • 1
  • 1
  • 8

3 Answers3

0

I would just create two css classes one for each color, and than use the jquery function toggleClass and give the two css classes name i.e.

$(div).toggleClass('class1 class2')

One more thing you probably will need to use setInterval to set the timing on it to run the toggleClass. something like this (http://jsfiddle.net/Eyq5x/31/)

<div id="me" class='yellow'></div>

div
{
    height:50px;
    width:50px;
}
.yellow
{
    background-color:yellow;

}

.red
{
    background-color:red;
}
​
$(document).ready(function(){
    setInterval(
        function(){
            $('#me').toggleClass('yellow red');
        },1000);
});​
Nir
  • 356
  • 1
  • 5
0

Another potential way to do it using seTimeout Like @DhirajBodicherla above pointed out .delay doesn't work with .css. Since jQuery returns the rgb for the colors though .toggleClass is probably the better route to take.

function pulse(){
    var div = $('#my_div');
    if(div.css("background-color")=="rgb(255, 0, 0)"){
        div.css("background-color","blue");
    }else{
         div.css("background-color","red");
    }
      setTimeout(pulse,100);
}

pulse();

Live Demo

Loktar
  • 34,764
  • 7
  • 90
  • 104
0

Here's how I did it -> http://jsfiddle.net/joplomacedo/bSWMC/229/

I'll paste in the code below:

js/jquery:

(function pulse() {
   $('#my_div').css('background-color', 'red');

   setTimeout(function() {
       $('#my_div').css('background-color', 'green');
   }, 2000);

   setTimeout(function() {
       $('#my_div').css('background-color', 'blue');
   }, 4000);

   setTimeout(pulse, 6000);
})();

css:

#my_div {
    height:60px;
    width:60px;
    background-color:red;
    -webkit-transition: 0.5s;
    transition: 0.5s;
}​
João Paulo Macedo
  • 15,297
  • 4
  • 31
  • 41