Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
The onLoad and onUnload Events
Collapse the table of content
Expand the table of content

The onLoad and onUnload Events

We’ll often want to perform some action immediately after a page is loaded, or before someone viewing our page jumps to another link. The Window object provides the onLoad and onUnload events to tell our code when these things happen. Fire up NotePad again and enter the following few lines of HTML and code:

<HTML>
<HEAD>
<TITLE> Window Events </TITLE>
</HEAD>
<BODY>
<CENTER>
<H1> Events of Window </H1>
Go to the <A HREF="file:c:\">root directory</A> of the C: drive.
<SCRIPT LANGUAGE="VBScript">
Sub Window_onLoad
  Alert "onLoad fired"
End Sub
Sub Window_onUnload
  Alert "onUnload fired"
End Sub
</SCRIPT>
</CENTER>
</BODY>
</HTML>

Now load this file into Internet Explorer. As soon as the page has loaded and is displayed, we hear a beep and see a message box displayed. This action is caused by the code we’ve connected to the Window’s onLoad event.

Now dismiss the message box and click on the single link on the page. Before we see the contents of the root directory of our C: drive, we get another message box, this time from the onUnload event.

Placing message boxes in the onLoad and onUnload events isn’t very useful— there aren’t many cases where we’d want to do this in real life. However, our example shows how simple it is to execute code when our page is loaded or unloaded.

Note that any action that causes the page to be unloaded, not just clicking to another link, will fire the onUnload event. If the current page has a code in an onUnload handler and we refresh it, or even shut down the browser, the code will be executed.

© 1997 by Wrox Press. All rights reserved.

Show:
© 2015 Microsoft