The onload event fires whenever an element finishes loading successfully (i.e., all its children are loaded). Frequently, this event is used in the body element to initiate a script after the page loads in the client’s browser. Figure 13.2 uses the onload event for this purpose. The script called by the onload event updates a timer that indicates how many seconds have elapsed since the document was loaded.
<?xml version = "1.0" encoding = "utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
<!-- Fig. 13.2: onload.html -->
<!-- Demonstrating the onload event. -->
<html xmlns = "http://www.w3.org/1999/xhtml">
var seconds = 0;
// called when the page loads to begin the timer
// 1000 milliseconds = 1 second
window.setInterval( "updateTime()", 1000 );
} // end function startTimer
// called every 1000 ms to update the timer
document.getElementById( "soFar" ).innerHTML = seconds;
} // end function updateTime
<body onload = "startTimer()">
<p>Seconds you have spent viewing this page so far:
<strong id = "soFar">0</strong></p>
Fig. 13.2 | Demonstrating the onload event.
Our use of the onload event occurs in line 30. After the body section loads, the browser triggers the onload event. This calls function startTimer (lines 15–19), which in turn uses method window.setInterval to specify that function updateTime (lines 22–26) should be called every 1000 milliseconds. The updateTime function increments variable seconds and updates the counter on the page.
Note that we could not have created this program without the onload event, because elements in the XHTML page cannot be accessed until the page has loaded. If a script in the head attempts to get a DOM node for an XHTML element in the body, getElement-ById returns null because the body has not yet loaded. Other uses of the onload event include opening a pop-up window once a page has loaded and triggering a script when an image or Java applet loads.
Copyright © 2018-2020 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.