Thursday, April 4, 2013

Generate Random Colors using JavaScript

Hi, 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, they 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’. 

Note: This code should work on most of the modern browsers. For old browsers, you need to look at hexadecimal value instead of RGB. 


Output:






 
Design by Frits Hendrico Tarihoran | Bloggerized by fritshendrico - Premium Blogger Themes | Revivalist, History Maker