You missed an s
in getElementsByClassName
, and since it returns multiple DOM elements, you need to select the first one with [0]
, or, as suggested by @ScottMarcus, simply use querySelector
which will return the first element matching the selector you pass to it.
And when using setInterval
inside a loop with the same delay, they're all going to trigger at the same time. Here is another approach using setTimeout
:
var bg = document.querySelector('.bg');
var colours = ["#CCCDFF", "#BAC7E8", "#D9EEFF", "#BADFE8"];
chainColours(colours);
function chainColours(colours) {
if (colours.length) {
setColour(colours[0]);
setTimeout(function() {
chainColours(colours.slice(1)); // Repeat with all colours except the first one
}, 200);
}
}
function setColour(colour) {
bg.style.background = colour;
}
.bg {
width: 100px;
height: 100px;
}
<div class="bg"></div>
Here, we're using a recursive function (a function which calls itself).
The first time we call it, we pass it the entire array of colours. The if
condition will pass, because colours.length
will be truthy (different than 0
).
We set the bg colour to the first colour in that Array, using the setColour()
function.
And then, using setTimeout
, we wait 200ms to call the function again, but passing the Array without the first element, using slice
.
It will go on until there are no elements left in that passed Array. Then, the if
condition will not pass, and it will stop.