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;
Top comments (0)