Calling Your
JavaScript Code after the Page Has Loaded
Sometimes
you will want to execute JavaScript code only when the user tries
to leave your page. You might want to do this because you
want to bid the
user farewell or remind the user he or she is leaving
your site.
Doing this requires two steps:
• Place the code you want to execute after the page has
completed
loading into a function.
• Use the onUnload attribute of the body tag to call the function.
This results in code like the following:
<script language="JavaScript">
function functionName() {
Code to execute when the page finishes loading
}
</script>
</head>
<body onUnload="functionName();">
Body of the page
</body>
</head>
<body>
The following task creates a function that displays a
goodbye message in a dialog
box and then only invokes that function when the user
leaves the page:
1. Open a new HTML document in your preferred HTML or text
editor.
2. Create the header of the document with opening and
closing head tags.
3. Insert a script block in the header of the document.
4. Create a function named bye that takes no arguments:
function bye()
{
}
5. In the function, use the window.alert method to display an alert
dialog box:
window.alert(“Farewell”);
6. Create the body of the document with opening and closing body
tags.
7. In the body tag, use the onUnload attribute to call the bye function:
<body
onUnload=”bye();”>
8. In the body of the page, place any HTML or text that you
want in
the page so that the final page looks like Listing below
code
<head>
<head>
<script language="JavaScript">
<!--
function bye() {
window.alert(“Farewell”);
}
// -->
</script>
</head>
<body onUnload="bye();">
The page’s content.
</body>
Using onUnload to call a function after the user leaves a page.
9. Save the file.
10. Open the file in a browser, and you should see the page’s
content.
Navigate to another site and you should see the farewell
dialog box.
No comments:
Post a Comment