Felipe Alarcon Felipe Alarcon - 4 years ago 361
Javascript Question

How to change a div background colour every X seconds in jQuery without effect?

I have a list with some rgb colours like this:

var ls = ['rgb(255,0,0)','rgb(0,255,0)', 'rgb(0,0,255)'];


And I would like to update a div background colour every 2 seconds using the colours from the list. To achieve it, I have written the following code:

(function($){
var $box = $('#box');
var temp;

var ls = ['rgb(255,0,0)','rgb(0,255,0)', 'rgb(0,0,255)'];

$.each(ls, function(i, x){
temp = setInterval(change(x), 2000);
});

function change(color) {
$box.css('background-color', color);
}

})(jQuery);


My goal is to display every colour in the list for 2 seconds before moving on to the next colour but this code waits 2 seconds and executes the loop so I can only see the last colour which is blue (rgb(0,0,255)).

My HTML looks like this:

<html>
<head>
<title>bin</title>
<style>
#box{
width: 200px;
height: 200px;
background-color: rgb(0,0,0);
}
</style>
</head>

<body>

<div id="box"></div>
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<script src="main.js"></script>
</body>
</html>


Thanks everyone.

Answer Source

I have found a nicer way using keyframesto achieve this color transition using plain css although this technique is not supported by IE9 and lower but I thought it'd be worth adding it here in case someone is reading.

<!DOCTYPE html>
<html>
<head>
<style> 
div {
    width: 100px;
    height: 100px;
    background-color: red;
    -webkit-animation-name: example; /* Chrome, Safari, Opera */
    -webkit-animation-duration: 4s; /* Chrome, Safari, Opera */
    animation-name: example;
    animation-duration: 4s;
}

/* Chrome, Safari, Opera */
@-webkit-keyframes example {
    0%   {background-color: red;}
    25%  {background-color: yellow;}
    50%  {background-color: blue;}
    100% {background-color: green;}
}

/* Standard syntax */
@keyframes example {
    0%   {background-color: red;}
    25%  {background-color: yellow;}
    50%  {background-color: blue;}
    100% {background-color: green;}
}
</style>
</head>
<body>

<p><b>Note:</b> This example does not work in Internet Explorer 9 and earlier versions.</p>

<div></div>

</body>
</html>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download