Generating a random color with JavaScript.

In this tutorial, we 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.

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

<div id="color"></div>

As you can see, it’s nothing special. It’s just a simple DIV element.

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

var r = Math.floor(Math.random() * (255 - 0 + 1) + 0);
var g = Math.floor(Math.random() * (255 - 0 + 1) + 0);
var b = Math.floor(Math.random() * (255 - 0 + 1) + 0);

var rgbString = r + ", " + g + ", " + b;
document.getElementById('color').innerHTML = "RGB: " + rgbString;
document.getElementById('color').style.backgroundColor = 'rgb(' + rgbString + ')';

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 this code 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:

setInterval(function(){
    var r = Math.floor(Math.random() * (255 - 0 + 1) + 0);
    var g = Math.floor(Math.random() * (255 - 0 + 1) + 0);
    var b = Math.floor(Math.random() * (255 - 0 + 1) + 0);
    var rgbString = r + ", " + g + ", " + b;
    document.getElementById('color').innerHTML = "RGB: " + rgbString;
    document.getElementById('color').style.backgroundColor = 'rgb(' + rgbString + ')';
}, 1000);

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

Related: