Andrew Crane
Andrew Crane

Reputation: 15

True random color for div on demand

I'm trying to use a random color for a <div> whenever the page loads, or on demand on refresh but it does not work. My code:

<head>
    <script type='text/javascript'>//<![CDATA[ 
        document.onload=function(){
            var red = Math.floor((Math.random()*256)+0);
            var blue = Math.floor((Math.random()*256)+0);
            var green = Math.floor((Math.random()*256)+0);
            var coloredDiv =  document.createElement("div");

            document.getElementById("coloredDiv");
            coloredDiv.style["background-color"] = 'rgb('+red+','+green+','+blue+')';
        }//]]>  
    </script>
</head>

<body>
    <div id="coloredDiv">A div that changes color randomly??!?!?!?!</div>
    <a href="javascript:void(0);" onClick="javascript: location.reload(true);">Go again!</a>
</body>

Upvotes: 1

Views: 623

Answers (1)

Harry
Harry

Reputation: 89750

You can set the background-color using either of the below options:

Option 1:

window.onload=function(){
    var red = Math.floor((Math.random()*256)+0);
    var blue = Math.floor((Math.random()*256)+0);
    var green = Math.floor((Math.random()*256)+0);
    var coloredDiv =document.getElementById("coloredDiv");
    coloredDiv.style.backgroundColor = 'rgb('+red+','+green+','+blue+')';
}

Option 2:

coloredDiv.style["backgroundColor"] = 'rgb('+red+','+green+','+blue+')';

The key thing to note is that whenever we set value using JS for a CSS property which haa hyphen in it (like background-color), the hyphen(s) should be removed and the first letter of the second and subsequent words should be capitalized.

Upvotes: 2

Related Questions