I'm trying to set random background colors using a forEach loop, but all the divs are getting the same background color with the same timer.
Here's the link to the codepen. https://codepen.io/McKern/pen/gvoZRp
var bgColors = [
"#260CE8",
"#7D1AFF",
"#A90CE0",
"#385EFF",
"#0F0559",
"#FF37EB"
];
$('.box').each(function(){
timer = setInterval( function() {
randomBgColor = bgColors[Math.floor(Math.random() * bgColors.length)];
randomNum = Math.floor(Math.random() * ((25-10)+1) + 10);
box = $('.box');
$('.box').css('backgroundColor', randomBgColor)
}, 1000);
});
1 Answer 1
You can also use the value from the jQuery.each()
and change the first and 3 from last line in your pen.
$('.box').each(function(i, l){
timer = setInterval( function() {
randomBgColor = bgColors[Math.floor(Math.random() *
bgColors.length)];
randomNum = Math.floor(Math.random() * ((25-10)+1) + 10);
box = $('.box');
$(l).css('backgroundColor', randomBgColor)
}, 1000);
});
answered Feb 18, 2018 at 6:30
DaveStSomeWhere
2,5402 gold badges25 silver badges20 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-js
$('.box').css('backgroundColor', randomBgColor)for$(this).css('backgroundColor', randomBgColor)$('.box')selects all the box elements, so$('.box').csschanges the colour on all of them. NewToJs is right, usingthisinstead will select the current item in the each loop