Generating a random color with JavaScript.

In this tutorial, I will show you how to generate a random RGB color using JavaScript. As you probably already know, the RGB color model consists of three numbers ranging from 0 to 255. Therefore, we can easily generate a random color by generating three random numbers between 0 and 255.

Let’s say for example that we have a HTML DIV element with the ID “color”:

Nothing special here, it’s just a simple DIV element.

Now, let’s give this element a random background color.

In the JavaScript example above, we generated three random numbers ranging from 0 to 255. We then concatenated these three numbers into the typical RGB format, with the numbers separated by commas.

For example, when I first executed the code above, my first result was: 103, 139, 167. The second time I ran it, I got: 109, 115, 218.

After we generated the RGB string, we modified the DIV’s content so that the random color is displayed inside it as a piece of text. Finally, we set the background color of the DIV to the random color by modifying its style.backgroundColor attribute.

A screenshot showing one of the random colors that the code above produced:

random color javascript

Note that if you want it to change color every second, you can stick this code inside the setInterval() method like so:

If you run the code above, you should see that our DIV element changes to a new random color every 1000 ms.

Related:

Facebook Comments