August 19, 2010

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



'Like' us on our FaceBook page if you find this blog useful. Thanks!


Did you like this post?
kick it on DotNetKicks.com Save on Delicious
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP 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 has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

0 Responses to "Generate Random Colors using JavaScript"
 

Copyright © 2009-2012 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions