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

2

3 Answers 3

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);
});​
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

That's great worked fine, but used .toggleClass as suggested.
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;
}​

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.