0

Pretty new to code. Having some trouble implementing some code to randomize the background color of part of my website to change based on an array. Found this code:

$(document).ready(function(){
  var colors = ["#4ECDC4","#FF6B6B","#313638","#FFE66D"];                
  var rand = Math.floor(Math.random()*colors.length);           
  $(‘#u97’, ‘#u379’).css("background-color", colors[rand]);
});

The "#u97, #u379" are the divs that I want to change the background color of. I insert the code in the header with a "script" tag but nothing happens. There is also a master CSS file that the divs get the color from, could that be interfering with something?

2 Answers2

0

try this:

$(document).ready(function(){
  var colors = ["#4ECDC4","#FF6B6B","#313638","#FFE66D"];                
  var rand = Math.floor(Math.random()*colors.length);           
  $('#u97').css("background-color", colors[rand]);
  $('#u379').css("background-color", colors[rand]);
});
Bartłomiej Gładys
  • 4,525
  • 1
  • 14
  • 24
  • Thanks, but it didn't seem to function. It's supposed to choose a different color on each reload but it's not. – Efren Martinez Sep 11 '16 at 21:54
  • I think your rand is not seeded with something that is different every time. Your code would probably repeat the same sequence every time you load the page unless you seed it with something like a datetime for instance. – nocturns2 Sep 11 '16 at 22:06
  • My mistake. please see this post: http://stackoverflow.com/questions/521295/javascript-random-seeds – nocturns2 Sep 11 '16 at 22:09
0

$(document).ready(function(){
  var colors = ["#4ECDC4","#FF6B6B","#313638","#FFE66D"];                
  var rand = function () {
    return Math.floor(Math.random()*colors.length);        
  };
  
  $("#u97, #u379").each(function () {
    $(this).css("background-color", colors[rand()]);
  });
});
div {height: 50px; width: 50px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="u97"></div><div id="u379"></div>
rafaelcastrocouto
  • 11,781
  • 3
  • 38
  • 63