Event Handlers

2. HTML Events

2.2. onload


          onload event handler triggers a process when an HTML object or element is loaded. Normally the onload event handler is used inside the <body> tag.  When used inside the body tag, it could trigger for example a test on the type of browser or if a cookie is enabled on a browser.

          A simple code example below is when a web page is loaded and reloaded will display a different background color each time.  The code will be using a native function or method called Math.random().  This function or method will be discussed in more detail in another learning guide.


  1. <!DOCTYPE html>
  2. <html>
  3. <body onload="changeColor()">

  4.       <h1>Changing Color for each load</h1>

  5.       <script>
  6.               function changeColor() {
  7.                   /* randomize generation of numbers from 1 to 255*/
  8.                   var red = Math.ceil(Math.random() * 255);
  9.                   var green = Math.ceil(Math.random() * 255);
  10.                   var blue = Math.ceil(Math.random() * 255);

  11.                   var dColor = "rgb(" + red + ","+green+","+blue+")"; 
  12.    console.log(dColor);
  13.                   document.body.style.backgroundColor = dColor;
  14.               }
  15.        </script>
  16. </body>
  17. </html>

          In the example code above, the function changeColor is called when a browser loads the webpage or when the web page is refreshed.  Inside the changeColor function a random number from 1 to 255 will be generated for red, green and blue variables.  These color values will be concatenated together using the + sign and place inside dColor variable to form the CSS value for color rgb(red,green,blue).

          The dColor will then be assign to the body background color using the statement:

 document.body.style.backgroundColor = dColor; 

          This statement is using the attribute style of the body tag and the CSS property background-color but translated to backgroundColor in JavaScript.