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.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Generate random color</title>
<style ="text/css">
body {
display: grid;
place-items: center;
height: 100vh;
}
#button {
height: 50px;
width: 100px;
}
</style>
</head>
<body>
<button id=" button">Click me</button>
<script>
const button = document.getElementById("button");
button.addEventListener("click", () => {
const generateRandomColor = `#${Math.floor(Math.random() * 0xffffff).toString(16)}`;
document.body.style = `background-color: ${generateRandomColor}`;
})
</script>
</body>
</html>
Code ExplanationCode Explanation
- the HTML code below will create a button element on the HTML document.
<button id="button">Click me</button>
- 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.
Top comments (8)
There are at least 3 problems with your code generating the random colour:
#ffffff
asMath.floor(Math.random() * x)
will only ever get you as high asx-1
0
s. For example -#ddd
will be interpreted as the colour#dddddd
rather than#000ddd
- which is an entirely different colourabc8
will be interpreted as shorthand#rgba
(The long version being#rrggbbaa
) - so some colours you are returning will also have random alpha valuesDear Randy!
Thank you for taking the time to read my articleπ and sharing your valuable insights through your corrective comment. I appreciate your attention to detail and the effort you've put into providing feedbackπ. However, I intentionally focused on a more traditional approach in this article to showcase core concepts. ππ
It's always good to stay open to new ideas, though ππ
Maybe this approach would be better?
πHey Karlen!
Thank you for reading my article and for sharing your suggestion on an alternative way to write the code. I appreciate your input and the opportunity to consider different approaches to solving the problem. I will definitely take this into consideration for future posts. In the meantime, If you have any further suggestions, ideas, or questions, please don't hesitate to reach out. Your input is highly valued, and I am eager to foster meaningful discussions around code development.
Thanks! This is a well-written and easy-to-follow tutorial π
Dear Bryan,
Thank you for taking the time to read my article and leaving a comment expressing your gratitude. I appreciate your kind words and I'm glad that you found the article helpful.
It's always rewarding to receive positive feedback and know that the content I create has made a positive impact. As a developer and writer, my goal is to share knowledge and provide valuable resources to the community, so knowing that it has been beneficial to you is truly fulfilling.
If you have any further questions, feedback, or topics you'd like me to cover in future articles, please feel free to let me know. I'm here to assist and provide information that meets the needs and interests of readers like you.
Thank you
π Hey TIM!
Thank you so much for the kind words! I'm glad you enjoyed the article and I hope it was helpful in some way. If you have any questions or feedback, feel free to let me know!.