4

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

Fiddle

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

I tried to use this js :

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

But I don't want two colors to be the same.

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
Federico
  • 1,392
  • 1
  • 17
  • 40

1 Answers1

1

Updated fiddle

You could choose random color from bgcolorlist then remove it using splice() so it'll not be selected 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>
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101