singlesyntax.comSingle Syntax

How to Generate Random HEX Color in JavaScript? [Easy Guide]

How to Generate Random HEX Color in JavaScript? [Easy Guide]

Advertisement

In this article, I will guide you through creating a JavaScript function that generates a random hex color code composed of a mix of numbers and alphabets.

This function generates a random hex color each time it is executed:

main.js

function getRandomHexColor() {
    // Generate a random number between 0 and 16777215 (0xFFFFFF in decimal)
    const randomNumber = Math.floor(Math.random() * 16777215);
    // Convert the random number to a hexadecimal string and pad with leading zeros if necessary
    const randomHexColor = `#${randomNumber.toString(16).padStart(6, '0')}`;
    return randomHexColor;
}

// Example usage:
console.log(getRandomHexColor()); // e.g., #3e2f1b

1. Generating Random Numbers

In the first step we need to generate random numbers and we can easily do that using the JavaScript Math Object and Math random() Method.

If you create a normal random method then it will give you random decimal numbers see the example below:

main.js

const randomValue = Math.random();
console.log(randomValue); // e.g., 0.123456789

But we need to generate a random number between 0 and 16777215, you might be thinking why do I need 16777215 instead of "999999" or any six-digit number well we need to use this eight-digit number because the number 16,777,215 is the highest value you can have with a six-digit hex color code.

Hex color codes use six digits, where each digit can be from 0 to 9 or A to F, giving 16 possible choices for each digit.

This means you can create a total of 16,777,216 different colors with six digits. The largest hex color code is #FFFFFF, which corresponds to 16,777,215 in decimal.

So, by using a number up to 16,777,215, you can cover all possible colors represented by a six-digit hex code, including those that contain alphabetic characters. This ensures that every possible color, whether it uses digits or letters, is included.

Don’t forget to wrap the Math.random() method inside Math.floor() to ensure you get whole numbers and avoid decimal values.

main.js

const randomNumber = Math.floor(Math.random() * 16777215);
console.log(randomNumber); // e.g., 45326764

2. Converting Number to hexadecimal String

main.js

function getRandomHexColor() {
    const randomNumber = Math.floor(Math.random() * 16777215);
    const randomHexColor = randomNumber.toString(16) //use the `toString(16)` method
 
}

Now we need to convert the number into a hexadecimal string, which can be easily done using the toString(16) method.

Simply use the toString(16) method on the random number and pass 16 it as the argument to convert it to a hexadecimal string.

This method ensures that the resulting code includes only digits and letters from 0 to F, without any characters beyond F.

3. Add padStart Method

Our function is almost ready. However, there's a potential issue: sometimes the generated hex color code might be only 5 characters long instead of 6.

If the function returns a 5-character hex color code, it won't be valid. To fix this and ensure that we always get a 6-character hex color code, we need to add the padStart method to the code.

The padStart(6, '0') method will ensure that the color code is always a 6-digit code by adding leading zeros if necessary.

For example, if the hex code is A9A9A and contains only five characters, the padStart(6, '0') method will add a leading 0 to make it a six-digit color code, resulting in 0A9A9A. This ensures that the function always returns a properly formatted hex color code with exactly six characters.

4. Return the Generated Hex Code

The final step is to return the generated random hex color code so that it can be easily used wherever needed.

I want to use a template string to wrap the color code and add `#` at the beginning, so I don’t have to add `#` manually every time I use this function.

main.js

function getRandomHexColor() {
    
    const randomNumber = Math.floor(Math.random() * 16777215);
 
    const randomHexColor = `#${randomNumber.toString(16).padStart(6, '0')}`;
    return randomHexColor; //return the code
}

// Example usage:
console.log(getRandomHexColor()); // e.g., #3e2f1b

Conclusion

When I first created a random hex color generator in JavaScript, it only produced dark or dull colors because it didn't include any alphabetic characters.

After making some changes to the code, I finally achieved the desired result. I also hope this post has saved you time in creating a similar function.

Share this post with your friends who are looking for a new project or want to build something using JavaScript!

Related Posts:

Advertisement

Leave a comment 💬

All Comments

Yasmin

Amazing Article!