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!

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

This answer sometimes generates invalid 5-digit color strings.
I used it but always generates valid one, If something you know better, welcome for edit,
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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.