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



Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

No comments: