Reputation: 1582
I'm looking to change to background color of a div class every time the window reloads.
I've used this code to change the background color of the body on refresh:
<script type="text/javascript">
<!-- //Enter list of bgcolors:
var bgcolorlist=new Array("silver", "#BAF3C3", "#c3baf3")
document.body.style.background=bgcolorlist[Math.floor(Math.random()*bgcolorlist.length)]
// -->
</script>
But I'm looking to change the background color of '.three' so every div with the class 'three' will have a different background color every time the window reloads (choosing from an array of colors).
Can't seem to figure out how to do this, is it at all possible?
Upvotes: 0
Views: 6630
Reputation: 76395
If the bg-colour has to be changed, you could use localStorage
to check what the bg was prior to the page being reloaded:
var colours = ['#F00','#0F0'];//my eyes!
var currentColour = +(localStorage.previousBGColour || -1)+1;
currentColour = currentColour >= colours.length ? 0 : currentColour;//if index is not set reset to colour at index 0
document.getElementById('theDiv').style.backgroundColor = colours[currentColour];
localStorage.previousBGColour = currentColour;//store colour that's currently in use
Note that not all browsers support localStorage
: some people are still using old, crummy IE8, for example.
jQuery
$(document).ready(function()
{
(function()
{//this IIFE is optional, but is just a lot tidier (no vars cluttering the rest of the script)
var colours = ['#F00','#0F0'],
currentColour = +(localStorage.previousBGColour || -1) + 1;
$('#theDiv').css({backgroundColor:colours[currentColour]});
localStorage.previousBGColour = currentColour;
}());
}
Upvotes: 1
Reputation: 12683
By using pure JS:
window.onload = function(){
var arr = document.querySelectorAll(".three");
for(var i=0;i<arr.length;i++){
arr[i].style.background = bgcolorlist[Math.floor(Math.random()*bgcolorlist.length)]
}
}
This will give all divs with class three random colors. If you want all to be same, just cache the math.random to a variable
Upvotes: 0
Reputation: 3474
var bgcolorlist = ['silver', '#BAF3C3', '#C3BAF3'];
$(function() {
$('.three').css({
background: bgcolorlist[Math.floor(Math.random()*bgcolorlist.length)]
});
});
Every time the page loads, this picks a random colour from the list and sets it on the body's css.
Upvotes: 0
Reputation: 1879
Using JQuery you can do
$(document).ready(function(){
$('.three').css('background-color',bgcolorlist[Math.floor(Math.random()*bgcolorlist.length));
});
Upvotes: 0
Reputation: 57322
Use this
var bgcolorlist=new Array("silver", "#BAF3C3", "#c3baf3")
$(".three").css("background-color",bgcolorlist[Math.floor(Math.random()*bgcolorlist.length)]);
Upvotes: 1