1

Possible Duplicate:
How to loop a css background image with Jquery every few seconds?

I'm wondering how to achieve a simple "animation" effect of colors changing every second and if there is a way to animate the animation it can be even better.

I have just tried something like:

$('.box').delay(1000).css("background","red");

And it doesn't work at all (the delay function isn't working).. anyways i need like two of them:

$('.box').delay(1000).css("background","red");
$('.box').delay(1000).css("background","green");

So that it becomes red -> wait a second and becomes green -> becomes red again..

Is it possible? thanks!

3

4 Answers 4

10
$(document).ready(function() {
    setInterval(function() {
        $('body').animate( { backgroundColor: 'red' }, 300)
            .animate( { backgroundColor: 'green' }, 300);
    }, 1000);
});

http://jsfiddle.net/theSifter/yR6jc/

Sign up to request clarification or add additional context in comments.

Comments

3
setInterval(function() {
    var box = $('.box');
    if (box.css('background-color') == 'red') {
        box.css({'background-color':'green'});
    }
    else {
        box.css({'background-color':'red'});
    }
}, 1000);

2 Comments

Is there any way to loop the color changing? Now it works but it changes once and that's it.
You could loop, but there is no way to tell the javascript engine to relax and update the user display without setTimeout or setInterval. A loop without setTimeout or setInterval will just crash the browser (eventually).
2
<h1 id="ho">Ho ho ho!</h1>
<h2 id="mc">Merry Christmas!</h2>

<script>
    var flag = false;
    setInterval(function() {
        flag = !flag;
        $("#ho").css("background", flag ? "red" : "green");
        $("#mc").css("background", flag ? "green" : "red");
    }, 1000);
</script>

Comments

1

I think you have to use the javascript setInterval method :

See here: http://www.w3schools.com/jsref/met_win_setinterval.asp

so:

setInterval(function() {
// Code to execute every second
}, 1000);

2 Comments

w3fools.com maybe?? ;)
Maybe somethings could be wrong there, but the example i saw wasn't..

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.