Generating random hex color in JavaScript



The Hex (Hexadecimal) code is a six-digit code and a three-byte hexadecimal number that is used to represent the colors. These three bytes represent RGB which means the amount of red, green, and blue in a particular shade of a color. Each byte will represent a number in the range 00 to FF (Hexadecimal notation) or 0 to 255 in decimal notation. This indicates the intensity of each of the color components from 0 to 255.

The following are the functions to be used for generating random hex codes −

Math.random() is used to get the number randomly in the range 0 to less than 1 including the decimal.

function random_num(maximum) { return Math.floor(Math.random() * maximum); } document.write(random_num(5)); // output: 0, 1 or 2

In the above snippet, we gave input as 5 as maximum value. Whenever we try to execute the program, it will print the output in between 0 to 4.

document.write(random_num()); // output: 0 to <1

In this case, as we didn’t have any input value as the maximum value, it prints a random number between 0 to <1 whenever we run the program. So, this is how the Math.random() function works.

Math.floor() is a function that will round the number downwards to the nearest integer.

document.write(Math.floor(1.95)); // output: 1

Here, we can see the output is printed as 5. So, the value is rounded downwards to the nearest integer.

document.write(Math.floor(1)); // output: 1

If the value passed is a perfect integer without any floating (decimal) points, it will be rounded.

Now, let’s combine these functions to generate the random hex numbers.

We use math.random() to generate a random number and multiply it with 16777215 as this number is the decimal representation of fffff (Highest in the hex code).

Math.random()*16777215

This will return a random number like 12421420.464841081 with decimals, Now we use math.floor() to remove the decimals and return a whole number.

Math.floor(Math.random()*16777215)

Now, we include toString() method to convert the number into a string. We have passed 16 as a parameter because Base 16 is hexadecimal. The value of 16 will return hexcode (with numbers and letters).

Math.floor(Math.random()*16777215).toString(16);

Example 1

Following is the example, which returns the random hex codes of color −

<!DOCTYPE html> <html> <title>Generating random Hex color</title> <head> <h3> <div id="demo">Mouse-over on this box to get new random color</div> <p id="color"></p> </h3> <style> body { height: 100vh; padding: 1rem; display: grid; place-items: center; font-family: verdana; } h3 { background: white; padding: 1rem 1rem; text-align: center; border-radius: 5px 20px 5px; } p { display: block; padding: 1px; font-size: 20px; font-weight: lighter; font-family: verdana; } </style> </head> <body> <script> function hex() { const RanHexColor = Math.floor(Math.random()*16777215).toString(16); document.body.style.backgroundColor = "#" + RanHexColor; color.innerHTML = "#" + RanHexColor; } demo.addEventListener("mouseover", hex); hex(); </script> </body> </html>

In the output, whenever you mouse over the box which is in middle it will generate the random hex colors on the background.

Example 2

In this example, we have achieved the task of getting random hex colors.

The slice() method will extract a part of a string. This method accepts 2 parameters (start, end). The start could be the first character in the string(0) and the end is the position.

const mobile = 'oneplus'; document.write(mobile.slice(2)); // output: "eplus"

In the above snippet, as we passed only the start parameter it sliced the string from index 2 to the end of the string.

const mobile = 'oneplus'; document.write(mobile.slice(0,3)); // output: "one"

In this snippet, we have passed both the start and end parameters. So, it sliced the string from 0 to 3 and printed "one".

const mobile = 'oneplus'; document.write(mobile.slice()); // output: "oneplus"

Here, we have passed nothing into the parameter, and therefore by default, it will take the entire string length.

Instead of Math.floor() we have used slice() method to eliminate the decimal after the numbers.

Below is the example, which returns the random hex codes of color −

<!DOCTYPE html> <html> <title>Generating random Hex color</title> <head> <div> <h3 id="demo">Mousemove here to get new random color</h3> <p id="color"></p> </div> <style> body { height: 100vh; padding: 1rem; display: grid; place-items: center; font-family: verdana; } div { background: white; padding: 1rem 1rem; text-align: center; } p { display: block; padding: 1px; font-size: 20px; font-weight: lighter; font-family: verdana; } </style> </head> <body> <script> function hex() { let RanHexCol = (Math.random()*16777215).toString(16); document.body.style.backgroundColor = '#' + RanHexCol.slice(0, 6); color.innerHTML = "#" + RanHexCol.slice(0, 6); } demo.addEventListener("mousemove", hex); hex(); </script> </body> </html>

Whenever you hover the mouse on the h3 element in the output, we can see the hex colors are randomly changing in the background.

Example 3

In the following example below, we have stored all the letters and numbers which will be a part of the hex color code in a variable. The loop will iterate 6 times as a hex color code consisting of 6 letters or digits and adds the value to '#'. Now, the random hex color code is generated.

<!DOCTYPE html> <html> <head> <style> body { height: 100vh; padding: 1rem; display: grid; place-items: center; font-family: verdana; } p { display: block; padding: 1px; font-size: 20px; font-weight: lighter; font-family: verdana; } </style> </head> <body> <p id = "demo"> </p> <script> // storing all letter and digit combinations // for html color code var codes = "0123456789ABCDEF"; // html color code starts with # var color = '#'; // generating 6 times as HTML color code consist // of 6 letter or digits let i = 0; for (i; i < 6; i++) document.body.style.backgroundColor = color += codes[(Math.floor(Math.random() * 16))]; document.getElementById("demo").innerHTML = color; </script> </body> </html>

In the output, the hex colors will be randomly changed in the background every time we execute the program.


Advertisements