Advertisement
  1. Code
  2. Coding Fundamentals

How to Code a Random Color Generator in JavaScript

Scroll to top
4 min read
17

Colors are a crucial part of design, both online and offline. Almost all elements on a webpage have some color applied to them. There are entire websites built around creating gradients and color palettes either randomly or from a source color.

In this tutorial, I'll show you how to generate a random color in JavaScript. Maybe you will find the random color generator useful when developing a website that lets users create stylish posters or form elements!

Understanding the Basic Concept

Colors can be represented in a lot of formats like RGB, Hexadecimal, or HSL notation. We will generate a random color in these three notations. Generating a random color is simply a matter of generating random numbers.

Luckily, JavaScript does have a Math.random() function that we can use to generate those random numbers. It will give you a random floating-point pseudo-random number that will be greater than or equal to 0 and less than 1. The distribution is pretty much uniform. This is good enough for our use case.

We will be generating random numbers between specific ranges like 0 to 100 or 0 to 255. Basically, the minimum value we want to get from our random number generator is 0, and the maximum value can be whatever we want, like 100 or 255.

Multiplying any number by 0 will give us 0, and multiplying it by 1 will give us the same number back. So multiplying our desired maximum value—for example 255—by anything between 0 and 1 will give us a number between 0 and 255. However, since Math.random() never gives us 1 exactly, we will have to use some other trick to get 255. This can be done by internally increasing the maximum limit by 1.

Here is the implementation of this logic as a function in JavaScript.

1
function randomInteger(max) {
2
    return Math.floor(Math.random()*(max + 1));
3
}
4
5
// Outputs a number between 0 and 255 inclusive

6
console.log(randomInteger(255));

Multiplying a number by some random fraction doesn't always result in integer values. Therefore, we use the Math.floor() function to get rid of the decimal part from our numbers.

Generating Random Colors

We will now write the code to create random colors in RGB, hex, and HSL notation.

Generating an RGB Color Value

This requires us to create three random integers between 0 and 255. These values will represent the red, green, and blue components of our colors. After that, we simply need to do some basic string concatenation. Here is our function for generating random RGB color values in JavaScript:

1
function randomRgbColor() {
2
    let r = randomInteger(255);
3
    let g = randomInteger(255);
4
    let b = randomInteger(255);
5
    return [r,g,b];
6
}
7
8
for(i = 0; i < 5; i++) {
9
    console.log(randomRGBColor());
10
}
11
12
/* Example output:
13
[191, 99, 247]
14
[162, 94, 201]
15
[236, 241, 172]
16
[168, 89, 2]
17
[161, 42, 113]
18
*/

Generating a Hex Color Value

Just like the previous example, we will begin by generating a random number between 0 and 255. After that, we will convert those numbers to the corresponding hexadecimal values. A simple string concatenation in the end will give us our random color in hex format.

1
function randomHexColor() {
2
    let [r,g,b] =randomRgbColor();
3
4
    let hr = r.toString(16).padStart(2, '0');
5
    let hg = g.toString(16).padStart(2, '0');
6
    let hb = b.toString(16).padStart(2, '0');
7
8
    return "#" + hr + hg + hb;
9
}
10
11
for(i = 0; i < 5; i++) {
12
    console.log(randomHEXColor());
13
}
14
/*
15
#51c18a
16
#81f582
17
#8a8446
18
#0554e1
19
#a21b18
20
*/

You might have noticed that we are also using the padStart() function. This is because the random number that we generate will sometimes be represented by a single digit when converted to hexadecimal notation. However, a valid color in this format needs to have 3 or 6 characters. Padding with a 0 at the beginning will give us a total character sequence length of 6.

Generating an HSL Color Value

Color in HSL notation also consists of three numbers. The first one is an angular degree that determines the hue of the color, the second value is a percentage that determines the saturation of the color, and the third value is used to specify the lightness of the color as a percentage. Hue can range from 0 to 360, while the percentages will vary from 0 to 100.

1
function randomHslColor() {
2
    let h = positiveInteger(360);
3
    let s = positiveInteger(100);
4
    let l = positiveInteger(100);
5
6
    return [h,s,l];
7
}
8
9
for(i = 0; i < 5; i++) {
10
    console.log(randomHslColor());
11
}
12
13
/*
14
[346, 83, 88]
15
[178, 43, 7]
16
[93, 87, 75]
17
[291, 29, 85]
18
[43, 53, 78]
19
*/

Random Color Generator

Here's a CodePen example of the random color generating functions in action!

Final Thoughts

This quick tip showed you how to generate random colors in JavaScript in three common formats: RGB, hex, and HSL. If you want to have transparent colors, you can use the same technique to randomize the opacity of your colors.

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.