ptg
13.3 Handling a Window or Frame Event 465
13.3 Handling a Window or Frame Event
A window is the main Web page, unless it is divided up into frames. There are a number
of events that will affect windows and frames; these are described in Table 13.3. The fol-
lowing examples illustrate some of the events that affect windows and frames.
13.3.1 The onLoad and onUnLoad Events
The onLoad event handler is invoked on the occurrence of a Load event; that is, when a
document, its frameset, or images have completely finished loading. This includes the
point at which all functions have been defined and scripts have been executed, and all
been called here such as: <a href=“#” onClick=“validateForm(this)”> and the sub-
mit() method used within the function if the form is OK. (See the section “Form Valida-
tion with Regular Expressions” on page 765 in Chapter 17.)
7 A deactivated link is assigned an onClick event handler. When the user clicks the
link, the JavaScript code is executed. The pseudo JavaScript: protocol is followed
by a reference to the form and a reset() method, which clears the form fields. See
Figure 13.4.
Figure 13.4 The focus is in the first box and the field is selected (highlighted).
Table 13.3 Window and Frame Events
Event Handler When It Is Triggered
onBlur When the mouse moves away from the window or frame and it loses focus.
onFocus When the mouse is clicked or moved in a window or frame and it gets focus.
onLoad When a document or image has finished loading.
onMove When a window is moved.
onUnLoad When a page is exited or reset.
EXPLANATION ( CONTINUED)
From the Library of WoweBook.Com
ptg
466 Chapter 13 • Handling Events
forms are available. This event can be helpful in synchronizing the loading of a set of
frames, particularly when there might be large images that need to be loaded or all of the
frame data hasn’t arrived from the server.
The onUnLoad event handler is invoked when the page is exited or reset.
EXAMPLE 13.5
<html>
<head><title>load and unload Events</title>
1 <script type="text/javascript">
2 var sec=0;
3 function now(){
var newdate= new Date();
var hour=newdate.getHours();
var minutes=newdate.getMinutes();
var seconds=newdate.getSeconds();
var timestr=hour+":"+minutes+":"+seconds;
4 window.setInterval("trackTime()", 1000);
5 alert("Your document has finished loading\n"+
"The time: "+timestr);
}
6 function trackTime(){
7 sec++;
}
8 function howLong(){
alert("You have been browsing here for "+ sec+" seconds");
}
</script>
</head>
9 <body background="blue hills.jpg" onLoad="now();"
10 onUnLoad="howLong();">
<font face="arial,helvetica" size=5>
When you leave or reload this page, <br />an alert dialog box
will appear.
</font>
</body>
</html>
EXPLANATION
1 The JavaScript program starts here.
2 A global variable called sec is declared.
3 The user-defined function now() contains several of the Date object’s methods to
calculate the time. This function is used to keep track of how long the user brows-
es from the time the page is loaded until it is exited.
4 The window object’s setInterval() method is set to call the function trackTime() ev-
ery 1,000 milliseconds (1 second) starting when the document is loaded until it
is unloaded.
From the Library of WoweBook.Com
ptg
13.3 Handling a Window or Frame Event 467
5 The alert dialog box pops up when the page finishes loading.
6 This is a user-defined function that keeps track of the number of seconds that
have elapsed since the page was loaded.
7 The variable called sec is increased by one each time trackTime() is called.
8 This function is called when the page is exited or reloaded. It is the event that is
triggered by the onUnLoad handler on line 10.
9 When the document has finished loading, the onLoad event handler is triggered.
The onLoad event handler is an attribute of the <body> tag. The event handler is
assigned a function called now() that sets up a timer that will go off every second
while the page is opened. After a second passes another function called track-
Time() will keep updating a variable that stores the number of seconds that have
elapsed. The background attribute of the HTML <body> tag is set to an image of
blue hills.
10 The onUnLoad event handler is triggered when the user either leaves or reloads
the page. See Figure 13.5.
Figure 13.5 If you exit or click the reload button, this alert box appears.
EXPLANATION ( CONTINUED)
From the Library of WoweBook.Com
ptg
468 Chapter 13 • Handling Events
13.3.2 The onFocus and onBlur Event Handlers
When an object has the focus, it is waiting for the user to do something, such as click a
button, click a link, or start or stop an animation. If you are moving between frames, the
frame where the mouse is pointing has the focus, and when the cursor moves out of the
frame, it loses focus or is “blurred.” The onFocus event handler is triggered by the user
clicking on the current window, frame, or form element, or by using the Tab key to cycle
through different elements on the screen. The onFocus event handler allows you to ini-
tiate a window or frame type function when the mouse is moved into a window, and the
onBlur event handler is triggered when you leave a window or frame. This can be caused
by the user clicking outside of the current window, frame, or form element. It’s exactly
the opposite of onFocus.
When a window has focus, it becomes the top window in a stack of windows. Exam-
ple 13.6 changes the background color of the left frame to pink when it goes into focus
and to yellow when it goes out of focus. The status bar at the bottom of the window
reflects what frame has the focus.
EXAMPLE 13.6
<html>
<head><title>Frame Me!</title></head>
1 <frameset cols="25%,75%">
2 <frame src="leftfocus.html" name="left">
3 <frame src="rightfocus.html" name="right" >
</frameset>
</html>
<! The right frame file >
<html>
4 <head><title>Right Frame</title></head>
5 <body bgColor="lightblue">
<font face="arial" size=4> right frame<br />
</body>
</html>
<html>
<head><title>Left Frame</title>
6 <script type="text/javascript">
7 function focus_on_me(){
document.bgColor="pink"; // Current doc is the left frame
8 window.status="focus leftframe";
}
9 function defocus_me(){
parent.left.document.bgColor="yellow"; // Another way to
// reference
10 window.status="focus rightframe"; // See the status bar
}
</script>
From the Library of WoweBook.Com
ptg
13.3 Handling a Window or Frame Event 469
</head>
11 <body onFocus="focus_on_me()" // Event handlers
12 onBlur="defocus_me()"
bgColor="lightgreen">
<image src="signs.jpg">
</body>
</html>
EXPLANATION
1 In this example, there are three files involved with frames. This is the HTML file
that defines the frameset. It consists of a main window divided into two frames, a
left frame consisting of 25 percent of the window, and right frame consisting of 75
percent of the window.
2 The left frame’s source code is in a file called leftfocus.html.
3 The right frame’s source code is in a file called rightfocus.html.
4 This HTML document is the content for the right frame.
5 The background color of the right frame is lightblue.
6 This is the start of the JavaScript program found in the file called leftfocus.html.
7 This user-defined function, called focus_on_me(), is called when the onFocus
event handler is triggered; that is, when the user’s cursor has focus in that window.
It assigns a pink background color to the left frame by going down the JavaScript
hierarchy: parent.left.document.bgcolor.
8 The status bar in the window is assigned the string “focus leftframe”. Look in the
status bar.
9 This user-defined function, called defocus_me, is called when the onBlur event
handler is triggered; that is, when the user’s cursor loses focus in that window. It
assigns a yellow background color to the right frame by going down the JavaScript
hierarchy: parent.right.document.bgcolor.
10 The status bar in the window is assigned the string “focus rightframe”. Look in the sta-
tus bar. (If the status bar doesn’t show anything, it could be that the “Hide the status
bar” feature has been enabled for your browser. For Firefox, see Tools→Options→
Enable JavaScript→Advanced JavaScript Settings).
11 An onFocus event handler is assigned to the <body> tag for the file called leftfo-
cus.html. As soon as focus goes into this window (frame), the handler’s function
called focus_on_me() is called.
12 An onBlur event handler is assigned to the <body> tag for leftfocus.html. When fo-
cus leaves this frame (i.e., the user clicks the mouse in another window), the func-
tion called defocus_me() is called. The output is shown in Figure 13.6.
EXAMPLE 13.6 (CONTINUED)
From the Library of WoweBook.Com
ptg
470 Chapter 13 • Handling Events
The focus() and blur() Methods. The focus() and blur() methods behave exactly
the same as their like-named events. These methods are applied to an object, such as a
window or form object, and are called from the JavaScript program. When the focus()
method is applied to an object, it will cause that object to be in focus and when the blur()
method is applied to an object, it will lose its input focus.
Figure 13.6 When focus is on the left frame, it turns pink. When focus leaves the left
frame, it turns yellow. Notice the mouse pointer is in the right frame. That’s where
the focus is. Check the status bar.
EXAMPLE 13.7
<html>
<head><title>The focus and blur methods</title>
<script type="text/javascript">
1 function newWindow(){
2 winObj=window.open("summertime.jpg",
"summer","width=650,height=200,resizable=yes,
scrollbars=yes,location=yes");
3 winObj.moveTo(0,0); // Move to left corner of screen
4 winObj.focus(); // New window gets the focus
//windObj.blur();
}
5 function closeWindow(){
6 winObj.close(); // Close the new window
}
</script>
</head>
<body bgColor="lightgreen">
<h2>Summer Scene from the Old Country</h2>
<form>
<input type=button
value="Open Window"
7 onClick="JavaScript:newWindow();" />
<input type=button
value="Close Window"
8 onClick="JavaScript:closeWindow();" />
From the Library of WoweBook.Com
ptg
13.3 Handling a Window or Frame Event 471
</form>
</body>
</html>
EXPLANATION
1 A user-defined function, called newWindow(), will create a new window object
with the window object’s open() method, specified with a number of options to
further define the window.
2 The new window object contains an image called summertime.jpg.
3 The new window is moved to the left corner of the screen, pixel position (0,0).
4 The new window gets focus. It will be on top of all the other windows.
5 This user-defined function is responsible for closing the new window.
6 The close() method of the window object causes the new window to be closed.
7 When the user clicks this button, the onClick event handler is triggered, and a new
window will be opened.
8 When the user clicks this button, the onClick event handler is triggered, and the
new window will be closed. The output is shown in Figures 13.7 and 13.8.
Figure 13.7 The parent window.
Figure 13.8 The new window is in focus and will appear on top of its parent window.
EXAMPLE 13.7 (CONTINUED)
From the Library of WoweBook.Com
ptg
472 Chapter 13 • Handling Events
13.3.3 The onResize Event Handler
The onResize event handler fires when the size of an object has changed.
2
In Firefox,
Opera, and Safari, the onResize event handler is fired only when the size of the browser
window changes and can be an attribute or property of the body, frameset, document,
and window objects. In Internet Explorer, the onResize event handler is fired when the
size of the browser window or the size of a body element is changed (although Internet
Explorer can be quirky and lock up at times; new problems with this handler were
reported with Internet Explorer 8).
<body onResize="JavaScript:resizeTo(400,400);">
This event handler can be used as an attribute of the window object but is not a valid
attribute for the XHTML body tag. When the size of the document or window changes,
the onResize event is fired on the body element in Internet Explorer. In Firefox, Opera,
and Safari, an onResize event handler is fired on the body element when the browser win-
dow is resized.
2. This event does not fire for files with embedded controls.
EXAMPLE 13.8
<html>
<head><title>Test window.onresize</title>
<script type="text/javascript">
1 function shrinkScreen() {
2 var newWidth=screen.availWidth/2;
var newHeight=screen.availHeight/2;
3 window.resizeTo(newWidth,newHeight);
4 alert("The screen's width is: " +
newWidth+ " and the height is: "+ newHeight);
}
5 function getDimensions() {
6 if (window.outerWidth){ // Firefox
alert("OnResize event: the original screen dimensions
are: " +
screen.availWidth+" x "+ screen.availHeight+
"new dimensions are: \n" + window.outerWidth +""+
window.outerHeight);
}
else{ // Internet Explorer
7 alert("OnResize event: the original screen dimensions
are: "+
screen.availWidth+" x "+ screen.availHeight+
"\nnew dimensions are: " + document.body.clientWidth +
""+ document.body.clientHeight);
}
}
From the Library of WoweBook.Com
ptg
13.3 Handling a Window or Frame Event 473
</script>
</head>
8 <body onResize="getDimensions();">
<form>
<input type="button" value="Click to change window size"
9 onClick="JavaScript:shrinkScreen()" />
</form>
</body>
</html>
EXPLANATION
1 The function shrinkScreen() will cause the screen to be made half its size, if it is
within the lower limit of 100 pixels.
2 The available screen width, screen.availWidth, and the available screen height,
screen.availHeight, specify the current width or height of the screen, in pixels, minus
features such as the taskbar in Windows. The variables newWidth and newHeight
will get the available screen width and height divided by two.
3 The window will be resized to the new dimensions created on the previous two
lines.
4 The alert box displays the dimensions of the screen in pixels after it has been re-
sized.
5 The function, getDimensions(), is called whenever the window is resized.
6 If the outerWidth property exists, the browser is not Internet Explorer. The origi-
nal screen dimensions and the new window dimensions will be displayed in the
alert box. The outerWidth property determines the width of the window (includ-
ing taskbars, etc.); using the innerWidth property determines the width excluding
the text decoration.
7 Internet Explorer uses the clientWidth property of the document object to get the
width of the window.
8 The onResize handler is associated with the body of the document. When the win-
dow changes in size, this handler is triggered.
9 When the onClick event handler is triggered, the shrinkScreen() function will
be called and the screen will be resized to half its size. The output is shown in
Figure 13.9.
EXAMPLE 13.8 (CONTINUED)
From the Library of WoweBook.Com
ptg
474 Chapter 13 • Handling Events
13.4 Handling Mouse Events
In many previous examples, we’ve seen uses of the onClick event handler to initiate an
action when a user clicks the mouse in a button or on a link. There are a number of other
events that can be fired due some action of the mouse. When the user moves the mouse
pointer over a link, image, or other object, the onMouseOver event handler is triggered, and
when he or she moves the mouse pointer away from an object, the onMouseOut event is trig-
gered. Table 13.4 lists events that are triggered when mouse movement is detected.
Figure 13.9 Window was resized manually by the user. The onResize event handler
was triggered.
Table 13.4 Mouse Events
Event Handler When It Is Triggered
onClick When the mouse is clicked on a link and on form objects like button,
submit.
onDblClick When the mouse is double-clicked on a link, document, form object,
image.
onMouseDown When the mouse is pressed on a link, document.
onMouseMove When the mouse is moved when it is over a link, form object, or most
elements.
onMouseOut When a mouse is moved out of a link, imagemap.
onMouseOver When a mouse is moved over or enters a link, imagemap, or most
elements.
onMouseUp When the mouse is released from a link, document.
From the Library of WoweBook.Com