user1551817
user1551817

Reputation: 7451

Generate random hexadecimal to change color in html

I have a web page that has a div element with a colored background.

I want the color to change each time someone loads the page.

I found this snippet of code online which apparently generates a random hexadecimal number:

'#'+Math.floor(Math.random()*16777215).toString(16);

I'm new to JavaScript and so I'm trying to piece together how I implement this.

I assume that I assign a variable to the randomly generated hexadecimal:

bandColor = '#'+Math.floor(Math.random()*16777215).toString(16);

Now I'm not sure whether I use this variabile (bandColor) in my stylesheet or my html.

If it's the html, I'm guessing I do something like this in the JavaScript:

$("#band").html(bandColor);

And then in the html:

<div id="band">

Would appreciate anyone who can point out what I have right / wrong!

Upvotes: 0

Views: 142

Answers (3)

Joe
Joe

Reputation: 26

JavaScript in external or embed style-sheet for CSS.

<!doctype html>
<html>
<head>
<style>
#band{
  width: 100%;
  height: 500px;
  background-color: #123456;
}
</style>
</head>
<body>
<div id="band"><div>
<script>
var bandColour = document.getElementById('band');
bandColour.style.backgroundColor = '#'+Math.floor(Math.random()*16777215).toString(16);
</script>
</body>
</html>

Upvotes: 1

HarisH Sharma
HarisH Sharma

Reputation: 1257

Pure javascript solution can be:

document.getElementById("band").style.background = "blue";

And with random color:

document.getElementById("band").style.background = '#'+(Math.random()*0xFFFFFF<<0).toString(16);

Upvotes: 1

APerson
APerson

Reputation: 8422

Try the style attribute of the element, so:

$("#band").css("background-color", bandColour);

Side note: sometimes your code will generate a five-digit or fewer hex string, like #9eb8d. You can fix this by left-padding with zeroes:

bandColour = ("000000" + bandColour).slice(-6);

which you would put before the statement where you set the background color.

Upvotes: 2

Related Questions