Generating random colors with JavaScript can be a bit intimidating, especially to new developers. in this post, I will walk you through how you can generate random colors with JavaScript.
- create an index.html file
create an index.html file, and copy and paste the code snippet below into the index.html file.
lang="en">
charset="UTF-8">
http-equiv="X-UA-Compatible" content="IE=edge">
name="viewport" content="width=device-width, initial-scale=1.0">
Generate random color
const button = document.getElementById("button");
button.addEventListener("click", () => {
const generateRandomColor = `#${Math.floor(Math.random() * 0xffffff).toString(16)}`;
document.body.style = `background-color: ${generateRandomColor}`;
})
Code ExplanationCode Explanation
- the HTML code below will create a button element on the HTML document.
- I added a little styling to it to place the button element in the center of the HTML document
body {
display: grid;
place-items: center;
height: 100vh;
}
#button {
height: 50px;
width: 100px;
}
Here is the
-
JavaScript code that does the magic.
-
firstly, I search through the Dom tree to retrieve a button element with an id of “button”, then I stored it in a variable called button.
-
then, I added an event listener to the button, and I listen to a click event.
-
then the code generates a random color each time the button is clicked.
-
then I assigned the color to the background.
const button = document.getElementById("button");
button.addEventListener("click", () => {
const generateRandomColor = `#${Math.floor(Math.random() * 0xffffff).toString(16)}`;
document.body.style = `background-color: ${generateRandomColor}`;
})
thank you for reading. please leave a comment below and share the post with your friends who are also learning JavaScript. don’t forget to follow me for more useful content.