0

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);
 });
asked Feb 18, 2018 at 6:11
5
  • Swap $('.box').css('backgroundColor', randomBgColor) for $(this).css('backgroundColor', randomBgColor) Commented Feb 18, 2018 at 6:13
  • $('.box') selects all the box elements, so $('.box').css changes the colour on all of them. NewToJs is right, using this instead will select the current item in the each loop Commented Feb 18, 2018 at 6:16
  • Here is a JsFiddle Demo I have also moved the interval outside of the loop. Commented Feb 18, 2018 at 6:19
  • Instead of all the background colors changing in unison, they don't change at all Commented Feb 18, 2018 at 6:25
  • That works. thanks! Commented Feb 18, 2018 at 6:27

1 Answer 1

0

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

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.