Generate random hex CSS color code in JavaScript

We can set the color of text or background color of any element by set the hex color through CSS. Now in this post, we are going to generate the random CSS hex color code using JavaScript.

In this example, first we will generate the random hex color using our JavaScript code and then wi will use the randomly generated color as the background color of the body tag of our web page so that the color will be set as the background color.

Below is our JavaScript code:

 function generateRandomColor() {
    max = 1 << 24;
    // Return the randomly generated hex color
    return '#'+(Math.floor(max*Math.random()) + max).toString(16).slice(-6);

 // Set the randomly generated color as the background color of body tag = generateRandomColor();

You may also like to read,

How To Change Background Color Every Seconds in JavaScript

If we run the above JavaScript code on our web page then we will see a background color on our web page body tag. Every tie we refresh or reload the web page, we will see a random background color for our web page.

How to delay in loading JavaScript code?

Our JavaScript function that we have created generate and return a randomly generated color. After that, we are applying the color as the background color of our HTML body tag using the HTML DOM style backgroundColor property.

In the end, we are able to see random color every time we reload our page.


Delay in loading external JavaScript file

Close current tab in browser window using JavaScript

Leave a Reply

Your email address will not be published. Required fields are marked *