Generate Random Colors using JavaScript

In this post, we will see how to generate random colors using JavaScript. We will generate a random color and change the color of the div contents, at regular intervals.

<html xmlns="http://www.w3.org/1999/xhtml" >
<
head>
<
title>Generate Random Colors using JavaScript</title>
<
script type="text/javascript">
// after every second timer
setInterval(randomRgb, 1000);

function randomRgb() {
// create the rgb string
var col = "rgb("
+ randomColor(255) + ","
+ randomColor(255) + ","
+ randomColor(255) + ")";

//change the text color with the new random color
document.getElementById("divone").style.color = col;
}


function randomColor(num) {
return Math.floor(Math.random() * num);
}
</script>
</
head>
<
body>
<
div id="divone" style="font:bold 24px verdana">DevCurry.com</div>
</
body>
</
html>

As you can see, we are using Math.random() to generate a random rgb value between 0 and 255. The onesecond timer is set using setInterval() which makes a function call to randomRgb() and changes the color of text kept inside ‘divone’. If you are new to the setInterval() function, read my post Execute a Function at Regular Intervals using JavaScript

Note: This code should work on most of the modern browsers. For old browsers, you need to look at hexadecimal value instead of RGB. Check my post Convert RGB to Hexadecimal using JavaScript

OUTPUT

image

See a Live Demo






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

No comments: