How to generate random background color in JS
ahmadullah
Posted on January 31, 2021
In this article, you're going to learn how to generate random colors in JS.
First of all, we need to add a button into our HTML file then add some css code after that make our hands dirty with JS.
<!--html part*!-->
<button>Generate Random color</button>
<h2>color code goes here</h2>
/*css part*/
button{
padding:10px;
background-color:cyan;
color:#fff;
}
And now it turns to JS if you are familiar JS math function then you should know how to generate random numbers in JS.
Math.random()
generates a random number between 0 and 1. here we use the string method to get a portion of generated number and text.
we can also generate random alphanumeric text using Math.random().
then we convert that into text and get 6 characters of it.
Here is the code.
const btn = document.querySelector('button');
const colorCode = document.querySelector('h2');
btn.addEventListener('click', function () {
const random = Math.random().toString(16).substring(2, 8);
let randomColor = `#${random}`;
colorCode.textContent = randomColor;
document.querySelector('body').style.backgroundColor = randomColor;
})
I used
const random = Math.random().toString(16).substring(2, 8);
in my code this code generates alphanumeric characters in HEXA Decimal format which is between 'a' up to 'f' and number from 0 up to 9;
Posted on January 31, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 30, 2024