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
See a Live Demo
Tweet
No comments:
Post a Comment