Main Page

resize event

Can you still assign an event handler to
document.body.onload
? Yes, you can. The problem is that
document.body
doesn’t exist until the page has loaded the
<body/>
tag. This means that if you try to
assign the event handler in the
<head/>
element, where it should be done, you get an error. Try it for
yourself:
<html>
<head>
<title>Onload Example</title>
<script type=”text/javascript”>
document.body.onload = function () {
alert(“loaded”);
}
</script>
<body>
</body>
</html>
If you run this code, you get an error saying that
document.body
isn’t defined. So, it is always best to
assign the
onload
event handler to the
window
object.
The
unload
event can be handled the same way, either by assigning the event handler to the
window
object or by assigning it in the
<body/>
element. The unload event fires when you navigate from one
page to another (by clicking a link or using the Back/Forward buttons) or when you close the browser
window:
<html>
<head>
<title>OnUnload Example</title>
</head>
<body onunload=”alert(‘Goodbye’)”>
</body>
</html>
The resize event
At times your Web page may change depending on the size of the browser window. For this case, you
can use the
resize
event to determine when to change these dynamic elements.
Similar to the load and unload events, the event handler for the resize event must be assigned either to
the
window
object using JavaScript code or to the
<body/>
element in HTML:
<html>
<head>
<title>OnResize Example</title>
You have very short amount of time in which to execute the event handler code
before the window is closed or the next page takes control, so it’s usually best to
avoid using an
onunload
event handler. The best reason to use onunload is to deref-
erence objects that were used on the page; any functionality more complicated than
this should be avoided.
288
Chapter 9
12_579088 ch09.qxd 3/28/05 11:39 AM Page 288


JavaScript EditorFree JavaScript Editor     Ajax Editor


©