Reputation: 16017
this is my first question here so excuse me if I did anything wrong. I'm doing the layout of a website and I want the header to change colors randomly when the user refresh the page. I already did some research and got these javascript codes:
<script type="text/javascript">
var randnum = Math.random();
var inum = 2;
var rand1 = Math.round(randnum * (inum-1)) + 1;
var colors = new Array;
colors[1] = "#385c78";
colors[2] ="#9d302f";
var color = colors[rand1]
document.getElementById('navbar').style.backgroundColor = image;
</script>
This one goes inside the head tag. It picks a random hexadecimal code between the two ones I want and store it on the var color.
The second one I'm using goes on the body.
<script type="text/javascript">
//writes "<div id="header" style="background-color:#something">"
document.write('<div id="header" style="background-color:' + color + '">')
</script>
<!-- continuation of div id="navbar" -->
*Header code here*
</div>
The problem is that this way of doing it is giving me some troubles, since the div id="header" is written inside javascript. I can't wrap other divs properly and Google Chrome's inspect element tells me that the body size is 1333px x 80px (as it can be seen here http://puu.sh/2yjKi), exactly and only the header size, and it doesn't wraps the rest of the website content. So my question is: Is there any way to improve that code? Make the background color of that div change via javascript or something like that?
I thank you all in advance for reading and appreciate your help.
Upvotes: 3
Views: 11424
Reputation: 6615
Though the post is little old but my answer may help others who would land here just like me!!
DEMO
HTML:
<div style="height:150px">
<div>
<h1><center>That's how i change color!!</center></h1>
</div>
<br><br>
<div class="bordered" id="fancy">
<center>I behave like a chameleon!!</center>
</div>
</div>
JS:
setInterval(function () {
document.getElementById("fancy").style.background= '#'+Math.floor(Math.random()*16777215).toString(16);
document.body.style.background= '#'+Math.floor(Math.random()*16777215).toString(16);
}, 1000);
Hope this would help someone!!
Upvotes: 4
Reputation: 45
function changecolor() {
var colors = ["#B40404", "#0000FF", "#FE2E9A", "#FF0080", "#2EFE2E", ];
var rand = Math.floor(Math.random() * colors.length);
$('#controls-wrapper').css("background-color", colors[rand]);
setTimeout('changecolor()', 1000);
}
Upvotes: 0
Reputation: 2011
Output your header as normal HTML, and then use JavaScript to update the color onDomReady. Something about like this:
$(document).ready(function() {
var colors = ["#385c78", "#9d302f"],
selectedColor = colors[Math.floor(Math.random()*colors.length)]
header = $("div#header");
header.css("background-color", selectedColor);
});
http://jsfiddle.net/ryanbrill/GD3qB/
Upvotes: 1