0

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!

NightOwl888
  • 55,572
  • 24
  • 139
  • 212
user1551817
  • 6,693
  • 22
  • 72
  • 109

3 Answers3

2

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.

APerson
  • 8,140
  • 8
  • 35
  • 49
1

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

HarisH Sharma
  • 1,101
  • 1
  • 11
  • 38
1

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>
mustachioed
  • 533
  • 3
  • 18
Joe
  • 26
  • 1