Gus Gus - 3 months ago 9x
CSS Question

How to make a div's background color randomly change when the page refreshes

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;

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 + '">')
<!-- continuation of div id="navbar" -->
*Header code here*

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, 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.


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);