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.
- <!DOCTYPE html>
- <html>
- <body onload="changeColor()">
- <h1>Changing Color for each load</h1>
- <script>
- function changeColor() {
- /* randomize generation of numbers from 1 to 255*/
- var red = Math.ceil(Math.random() * 255);
- var green = Math.ceil(Math.random() * 255);
- var blue = Math.ceil(Math.random() * 255);
- var dColor = "rgb(" + red + ","+green+","+blue+")";
- console.log(dColor);
- document.body.style.backgroundColor = dColor;
- }
- </script>
- </body>
- </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.