Change three colors every time every update

I have three classes with three different colors. How can I randomly change background-colorson every page visit?

Fiddle

.projects{background:#99c6c3;}  
.other-things{background:#d3d3d3;}
.about {background:#eedd8d;}    

I tried using this js:

var bgcolorlist=new Array("#99c6c3", "#d3d3d3", "#eedd8d")
$(".projects").css("background-color",bgcolorlist[Math.floor(Math.random()*bgcolorlist.length)]);

But I do not want the two colors to be the same.

+4
source share
1 answer

Updated fiddle

You can select a random color from bgcolorlistand then delete it with splice()so that it is not selected the next time:

var bgcolorlist=new Array("#99c6c3", "#d3d3d3", "#eedd8d");
var elements=new Array(".projects", ".about", ".other-things");

for(var i=0;i<elements.length;i++){
  var random = Math.floor(Math.random()*bgcolorlist.length);
  $(elements[i]).css("background-color",bgcolorlist[random]);

  bgcolorlist.splice(random, 1); //remove selected color from array
}
body {font-size:21px; font-family:arial;}
.projects{text-align:center; line-height:100vh;background:#99c6c3;	overflow-x: hidden;width: 33%;float:left; height: 100vh;}	
.other-things{text-align:center; line-height:100vh;background:#d3d3d3;overflow-x: hidden;width: 33%;float:left; height: 100vh;}
.about {text-align:center; line-height:100vh;background: #eedd8d;	overflow-x: hidden;width: 33%;float:left; height: 100vh;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="projects">ONE</div>
<div class="other-things">TWO</div>
<div class="about">THREE</div>
Run codeHide result
+1
source

All Articles