Sams Teach Yourself JavaScript in 24 Hours Free Open Book

Sams Teach Yourself JavaScript in 24 Hours

Previous Page
Next Page

Using the onLoad and onUnload Events

Another event you'll use frequently is onLoad. This event occurs when the current page (including all of its images) finishes loading from the server.

The onLoad event is related to the window object, and to define it you use an event handler in the <body> tag. For example, the following is a <body> tag that uses a simple event handler to display an alert when the page finishes loading:

<body onLoad="alert('Loading complete.');">

Watch Out!

Because the onLoad event occurs after the HTML document has finished loading and displaying, you cannot use the document.write or document.open statements within an onLoad event handler. This would overwrite the current document.


In JavaScript 1.1 and later, images can also have an onLoad event handler. When you define an onLoad event handler for an <img> tag, it is triggered as soon as the specified image has completely loaded.

To set an onLoad event using JavaScript, you assign a function to the onload property of the window object:

window.onload = MyFunction;

You can also specify an onUnload event for the <body> tag. This event will be triggered whenever the browser unloads the current documentthis occurs when another page is loaded or when the browser window is closed.

Try It Yourself

Adding Link Descriptions to a Web Page

One of the most common uses for an event handler is to display descriptions of links when the user moves the mouse over them. For example, moving the mouse over the Order Form link might display a message such as "Order a product or check an order's status".

Link descriptions like these are typically displayed with the onMouseOver event handler. You will now create a script that displays messages in this manner and clears the message using the onMouseOut event handler. You'll use functions to simplify the process.

By the Way

This example uses the innerHTML property to display the descriptions within a heading on the page. See Hour 13 for a complete description of this property.


This will also be an example of defining event handlers entirely with JavaScript. The HTML document, shown in Listing 9.4, does not include any <script> tags or event handlersthe only thing it requires is some id attributes on the objects we will be using in the script.

Listing 9.4. The HTML Document for the Descriptive Links Example

<html>
<head>
<title>Descriptive Links</title>
</head>
<body>
<h1>Descriptive Links</h1>
<p>Move the mouse pointer over one of
these links to view a description:</p>
<ul>
<li><a href="order.html" id="order">Order Form</a>
<li><a href="email.html" id="email">Email</a>
<li><a href="complain.html" id="complain">Complaint Department</a>
</ul>
<h2 id="description"></h2>
<script language="JavaScript" type="text/javascript"
 src="linkdesc.js">
</script>
</body>
</html>

This document defines three links in a bulleted list. Each <a> tag is defined with an id attribute for the script to use to attach an event handler. The <h2> tag with the id value description, currently blank, will be used to display a description of each link.

By the Way

Notice that the <script> tag is below the content of the HTML document. It would not work at the top of the document because the objects the script uses are not yet defined. You can also deal with this issue by using an onLoad event handler instead of a simple script to set up the event handlers.


The script will begin with a function to serve as the onMouseOver event handler for the links:

function hover(e) {
    if (!e) var e = window.event;
    // which link was the mouse over?
    whichlink = (e.target) ? e.target.id : e.srcElement.id;
    // choose the appropriate description
    if (whichlink=="order") desc = "Order a product";
    else if (whichlink=="email") desc = "Send us a message";
    else if (whichlink=="complain") desc = "Insult us, our
 products, or our
families";
    // display the description in the H2
    d = document.getElementById("description");
    d.innerHTML = desc;
}

The hover function uses the target or srcElement properties to find the target object for the link, and then finds its id attribute. Three if statements evaluate the id and choose an appropriate description. Finally, the script uses the getElementById() method to find the <h2> tag that will display the descriptions, and displays the description using the innerHTML property.

Did you Know?

The conditional statement on the third line of the hover function checks whether the target property exists, and if not, it uses the srcElement property. This is called feature sensingdetecting whether the browser supports a featureand is explained further in Hour 15, "Unobtrusive Scripting."


One more function will be required. The cleardesc() function will serve as the onMouseOut event handler and clear the description when the mouse is no longer over one of the links.

function cleardesc() {
     d = document.getElementById("description");
     d.innerHTML = "";
}

Now that the functions are defined, you need to set them as the event handlers for the links. Each link requires the following three lines of code:

orderlink = document.getElementById("order");
orderlink.onmouseover=hover;
orderlink.onmouseout=cleardesc;

After using getElementById() to find the object with the id attribute "order", this sets up the hover() and cleardesc() functions as its onMouseOver and onMouseOut event handlers. This will need to be repeated for the other two links. Putting all of this together, the complete JavaScript file for this example is shown in Listing 9.5.

Listing 9.5. The JavaScript File for the Link Descriptions Example

function cleardesc() {
     d = document.getElementById("description");
     d.innerHTML = "";
}
function hover(e) {
    if (!e) var e = window.event;
    // which link was the mouse over?
    whichlink = (e.target) ? e.target.id : e.srcElement.id;
    // choose the appropriate description
    if (whichlink=="order") desc = "Order a product";
    else if (whichlink=="email") desc = "Send us a message";
    else if (whichlink=="complain") desc = "Insult us, our
 products, or our
families";
    // display the description in the H2
    d = document.getElementById("description");
    d.innerHTML = desc;
}
// Set up the event handlers
orderlink = document.getElementById("order");
orderlink.onmouseover=hover;
orderlink.onmouseout=cleardesc;
emaillink = document.getElementById("email");
emaillink.onmouseover=hover;
emaillink.onmouseout=cleardesc;
complainlink = document.getElementById("complain");
complainlink.onmouseover=hover;
complainlink.onmouseout=cleardesc;

To test the script, store it as linkdesc.js in the same folder as the HTML document, and load the HTML file into a browser; this script should work on any JavaScript-capable browser. Internet Explorer's display of the example is shown in Figure 9.3.

Figure 9.3. Internet Explorer displays the descriptive links example.


Did you Know?

As usual, you can download the listings for this hour from this book's website.



Previous Page
Next Page
Index: [SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R][S][T][U][V][W][X][Y]


     Main Menu
Sams Teach Yourself JavaScript in 24 Hours
Table of Contents
Copyright
About the Author
Acknowledgments
Part I: Introducing the Concept of Web scripting and the JavaScript Language
Part II: Learning JavaScript Basics
Part III: Learning More About the DOM
Hour 9. Responding to Events
Understanding Event Handlers
Using Mouse Events
Using Keyboard Events
Using the onLoad and onUnload Events
Summary
Q&A
Quiz Questions
Quiz Answers
Exercises
Hour 10. Using Windows and Frames
Hour 11. Getting Data with Forms
Hour 12. Working with Style Sheets
Hour 13. Using the W3C DOM
Hour 14. Using Advanced DOM Features
Part IV: Working with Advanced JavaScript Features
Part V: Building Multimedia Applications with JavaScript
Part VI: Creating Complex Scripts
Part VII: Appendixes
Index


More Books
PHP Hacks
Processing Xml With Java - A Guide To Sax, Dom, Jdom, Jaxp, And Trax
The Koran (Holy Qur'an)
Macromedia Flash 8 Bible
Search Engine Optimization for Dummies
YouTube Traffic
PHP 5 for Dummies
Harry Potter and The Chamber of Secrets
Harry Potter and the Sorcerer's Stone
The Pilgrim's Progress
Wireless Hacks
Flash Hacks. 100 Industrial-Strength Tips & Tools
PayPal Hacks. 100 Industrial-Strength Tips and Tools
Amazon Hacks
Pdf Hacks
The Da Vinci Code
Google Hacks
The Holy Bible
Windows XP For Dummies
Harry Potter and the Half-Blood Prince
Seo Book
Upgrading and Repairing Networks
Macromedia Dreamweaver 8 UNLEASHED
Windows XP Annoyances
Windows XP Hacks
Microsoft Windows XP Power Toolkit
Teach Yourself MS Office In 24Hours
iPod & iTunes Missing Manual
PC Hacks 100 Industrial-Strength Tips and Tools
PC Overclocking, Optimization, and Tuning - 2th Edition
PC Hardware In A Nutshell 3rd Edition
PC Hardware in a Nutshell, 2nd Edition
Upgrading and Repairing PCs
Google for Dummies
MySQL Cookbook
Teach Yourself Macromedia Flash 8 In 24 Hours
PHP CookBook
Sams Teach Yourself JavaScript in 24 Hours
PHP5 Manual
Free Games Paper Airplanes
500 Juegos Gratis 500 Giochi Gratis 500 Jeux Gratuits 500 Jogos Gratis 500 Kostenlose Spiele