The following code shows how to Change the Background Color of a Web Page Randomly. Basically, in this example, we use the onload event handler. This is because we want to call a function each time the page is refreshed. Further, the onload event handler calls the change() function where, we take three variables. These variables are assigned a random number, that we multiply with 255 to get a number between 0 and 255. In order to create a random color, we use the rgb() method and use these variables as parameters and set the background property.

<html>
 <head>
   <title>Randomly Change Background Color</title>
    <script>
	function change(){
          var body=document.getElementById("b");
          var x=Math.random();
          var y=Math.random();
          var z=Math.random(); 
          body.style.background='rgb('+x*255+','+y*255+','+z*255+')';        
        }
   </script>
   <style>
     body{
        color: #992288;
        background: #ffddff;
	font-size: 20px;
     }
   </style>
 </head>
 <body onload="change();" id="b">
   <div>The background color will randomly change each time the page is loaded.</div>
 </body>
</html>

Output

Changing the background color when page is loaded
Changing the background color when page is loaded