﻿ kirupa.com - Random Colors in JavaScript

# Random Colors in JavaScript

written by kirupa   |   22 January 2011

Every now and then, I run into into some technique that is so full of win, that I have to share it with all of you. Generating a random color is one of those techniques.

In following gray box, click on the Change Color button:

 #F3F3F3

[ go ahead, click on the button. I dare you to click only once ]

Each time you click the button, both the value and the color of the text changes to a random color.

By the end of this tutorial, you will learn how to generate a random color in JavaScript. If that doesn't entice you to read further, indirectly you may learn some other nifty tricks about colors and numbers that you may be able to apply to more common problems.

Let's get started.

## Looking at the Hex Color Value

First, let's understand what exactly it is that we are going to be doing. Our goal is to generate random color values, and these color values are known as hexadecimal values (or hex values if want to sound cool).

The Counting in Hexadecimal tutorial can help you learn more about them, but just remember that a hex value is nothing more than a different way of representing numbers than the one that you are probably accustomed to:

 What you see... What your computer sees... 1492 5D4 1,000,000 F4240 12 C 666 29A 2012 7DC 45,220,592 2B202F0

The numbers you see in the above table are just arbitrarily picked decimals with their hex equivalents showing. In many cases, you can get away with just specifying a decimal value and letting your computer handle the conversion internally.

With colors, it doesn't work the same way. In order to work with colors, you need to specify the hex value yourself. And the tricky part is, what makes hex values unique when it comes to colors is that the number shouldn't be looked at in aggregate.

Instead, a hex value is divided into three parts where each part corresponds to Red, Green, and Blue (a RGB value!).

The first two characters correspond to red, the second two correspond to green, and the third two correspond to blue. When you expand these values back into decimal form, you will get a number between 0 and 255.

To put it differently, our RGB color value is nothing more than three indiidual numbers between 0 and 255, converted to hex, and then joined together to make a single value. As long as we can generate a random number between 0 and 255 for each of the colors, we can do some simple conversion from that random to hex to get our random color into a form our computer can understand.

I'm glossing over some details, but that is basically the big picture of what we want to do. Let's put this into code.

## Code for Generating a Random Color Value

As you will soon see, the hard part of all this is trying to come up with an approach for generating the random colors. The code directly translates the approach from English into code that your browser can do magical things with.

Without further delay, the code for generating a random color looks as follows:

function getRandomColor() {
// creating a random number between 0 and 255
var r = Math.floor(Math.random() * 256);
var g = Math.floor(Math.random() * 256);
var b = Math.floor(Math.random() * 256);

// going from decimal to hex
var hexR = r.toString(16);
var hexG = g.toString(16);
var hexB = b.toString(16);

// making sure single character values are prepended with a "0"
if (hexR.length == 1) {
hexR = "0" + hexR;
}

if (hexG.length == 1) {
hexG = "0" + hexG;
}

if (hexB.length == 1) {
hexB = "0" + hexB;
}

// creating the hex value by concatenatening the string values
var hexColor = "#" + hexR + hexG + hexB;

return hexColor.toUpperCase();
}

This function, when called, returns a random color in the form a string. To use it, all you have to do is just call it:

var myRandomColor = getRandomColor();

That's it. Pretty simple, right?

## Looking at the Code

Ok, now that you have the code and very basic instructions on how to use it inside your projects, let's look at why the code works the way it does. Our dissection will start at the very top.

The first three lines generate a random value between 0 and 255 for the red, green, and blue components of our color:

var r = Math.floor(Math.random()*256);
var g = Math.floor(Math.random()*256);
var b = Math.floor(Math.random()*256);

The only tricky part here is the combination of Math.floor and Math.random for generating the random number. You can learn more about why both of those math functions are used in the Random Numbers in JavaScript tutorial.

After these three lines have run, the r, g, and b variables will each store a number between 0 and 255. Right now, these numbers are in decimal form. What we need to do is convert them into hex, and that is easily done by using the toString function with an argument of 16:

var hexR = r.toString(16);
var hexG = g.toString(16);
var hexB = b.toString(16);

In these three lines, I create three new variables called hexR, hexG, and hexB to store the hex equivalents of the decimal values the r, g, and b variables store.

The next thing we do is a little bit of housecleaning. Like I mentioend earlier, a hex color value is made up of six characters with the red, blue, and green components each using two characters. You absolutely must use two characters to represent the color value. If you do not, the color is going to be flagged as invalid.

If any of your red, green, or blue values hold a decimal value less than 15, then you will end up with a hex value that is only a single character. That can't be allowed for our purposes, so what I do is prepend a zero (0) character to the single character hex value to ensure that the length of the color is still two characters:

if (hexR.length == 1) {
hexR = "0" + hexR;
}

if (hexG.length == 1) {
hexG = "0" + hexG;
}

if (hexB.length == 1) {
hexB = "0" + hexB;
}

The above code with the three if statements does the heavy lifting to make sure our individual colors are two characters long. I first check to see if the length of the hex value is 1 character. If it is, then I add a 0 to the beginning to make sure the hex value's length becomes 2 characters.

One of the last things we do is construct our hex color value:

var hexColor = "#" + hexR + hexG + hexB;

There is nothing fancy going on here, for I am simply generating the hex color by doing simple string manipulation and assigning it to our hexColor variable. I start by adding the # character to the two-character hex values stored by the hexR, hexG, and hexB variables.

The last thing I do is return the hexColor value back to whatever called this function initially:

return hexColor.toUpperCase();

For purely aesthetic reasons, I call toUpperCase() on the hexColor variable to make sure that the returned colors look more presentable. For example, I prefer seeing #A1A1A1 instead of #a1a1a1. This is just a personal preference, so you can remove the function call to toUpperCase and gain back a small amount of performance if you want. Your browser will know what to do with the color value independent of whether the letters are capitalized or not, so you don't have to worry about your applications behaving differently.

## Conclusion

Well, this wraps up this tutorial where you learned how to generate random color values. If you want to see this technique put to use (note that I didn't say "good use"), check out my really awesome seizure generator if you haven't done so already. If you found another use for this technique, do share for everyone to see by posting here!

If you have a question about this or any other topic, the easiest thing is to drop by our forums where a bunch of the friendliest people you'll ever run into will be happy to help you out!

#### THE KIRUPA NEWSLETTER

Get cool tips, tricks, selfies, and more...personally hand-delivered to your inbox!

( View past issues for an idea of what you've been missing out on all this time! )