Приглашаем посетить
Салтыков-Щедрин (saltykov-schedrin.lit-info.ru)

Window Events

Window Events

The window object exposes events that allow control over the current state of the window. These events are useful for determining whether the document is loaded and for responding when it receives or loses the focus or when an error occurs.

Document State Events

Events are available for tracking the loading and unloading of a document. Handlers for these events should always be written in the document's head to ensure that they are hooked up as early as possible in the document's loading process. If the events are written in the middle of the document's contents, the code might never run if, for example, the user leaves the document before the unloading code is even parsed.

Load Events

The two events related to the loading of the document are onload and onreadystatechange. Both events help you determine when the entire document has been parsed and all elements have been loaded. The onreadystatechange event is a new event that occurs on the document, not on the window; onreadystatechange is discussed in detail in Chapter 6, "The HTML Document."

The onload event fires when the entire document is parsed but does not necessarily signal that all objects on the document are completely downloaded. This event is also supported by the Netscape Navigator 3.0 and Microsoft Internet Explorer 3.0 object models.

Unload Events

Two events relate to the unloading of the document: onbeforeunload and onunload. The onbeforeunload event is fired immediately before the onunload event. The onbeforeunload event gives the Web author a chance to verify that the user really wants to exit the document. This confirmation is useful when exiting the document would cause information to be lost because the user failed to submit data to the server. For example, in a data-binding scenario in which the user batches many changes on the client, exiting the document without submitting the data would cause the changes to be unintentionally lost. (Data binding is covered in detail in Chapter 15, "Data Binding with HTML.")

The onbeforeunload event can display a predefined dialog box that presents the developer's text and asks whether the user wants to exit the document. To display this query, set the returnValue property to a string, as shown in the following code. If you don't set the returnValue property using a string value, the window simply unloads the document without displaying a dialog box.

<SCRIPT LANGUAGE="JavaScript" EVENT="onbeforeunload()" FOR="window">
   event.returnValue = "Your input will be lost if you leave.";
</SCRIPT>

Figure 4-3 shows this custom message displayed by Internet Explorer 4.0 in response to the onbeforeunload event.

Window Events

Figure 4-3. Custom message displayed in a special dialog box by the onbeforeunload event.

For security reasons, a document cannot prevent the window from unloading it without the user's intervention. This restriction prevents a document from locking the system and requiring the user to either end the browser application or reboot.

Immediately before the document is unloaded, the onunload event fires. At this point, there is no way to stop the process or ask the user not to leave the document. Rather, this is where any cleanup code for the document should be written—it is the last opportunity for scripts to access the document and its contents.

Focus Events

The term focus refers to the window or element that is active and receives user notifications such as keyboard and mouse events. To allow you to determine when the window receives and loses the focus, the window exposes the onblur and onfocus events. In general, the onblur event fires when the window loses the focus to an element within the window or to another window, and the onfocus event fires when the window receives the focus.

The document that is loaded by the browser initially has the focus but does not fire an onfocus event. When the window has the focus, every user interaction with the window will cause the onblur and onfocus event sequence to occur. For example, clicking on the focusable window's document fires the onblur event on the window, followed by the onfocus event, even if the window already has the focus.

If the initial document is a frameset, the frameset itself has the initial focus. As with traditional HTML documents, loading the frameset does not fire an initial onfocus event. However, once the user clicks on or navigates to an instance of a frame in the frameset, an onblur event fires on the frameset and an onfocus event fires on the corresponding frame. This leads to the first rule of focus events:

This one item can be a window object, a frameset, or an element within the document such as an input control or embedded object. Whenever the focus changes, an onblur event fires on a window or an element and an onfocus event fires on some other element.

A document may contain any number of focusable elements, including the input controls that take part in a form, embedded controls, and applets. Whenever one of these elements receives the focus, an onblur event fires on the prior window or element and an onfocus event fires on the focusable element. This leads to the second rule of focus events:

The focus and blur Methods

You can force a window or an element to receive or lose the focus by calling its focus or blur method. Calling one of these methods causes the associated event handler to be executed only if a change of state is required. For example, a window that already has the focus will not fire the onfocus event if its focus method is called. However, if the window does not have the focus and then receives the focus through the focus method, the onfocus event will be fired. This distinction is important to recognize because you cannot rely on code being executed in response to all focus or blur method calls.

Error Handling

The window object exposes an onerror event that is fired whenever a scripting error occurs on the page. When errors occur in a script, the user is usually presented with a cryptic message and the page fails to execute. Using an onerror event handler, the page can override the built-in dialog box and display a more explanatory message.

The onerror event also makes it possible to override the built-in dialog box and fail silently, as shown in the following code. While this is easy to accomplish, it is probably not advisable. If a scripting error occurs on the page, the page might enter an unpredictable state, causing the document to no longer function.

<SCRIPT LANGUAGE="JavaScript">
   function stopAllErrors() {
      // No scripting errors will ever display a message.
      return true;  // A value of true prevents the dialog box 
                    // from appearing.
   }

   window.onerror = stopAllErrors;  // Hook up onerror event handler.
   thisBadCode.WillNot.GenerateAnError(); // Syntax error
</SCRIPT>

Unlike most events in the Dynamic HTML object model, returning true to the onerror event forces the dialog box to not appear. For all other events, returning false prevents the event from performing its default action. This difference is necessary in order to maintain compatibility with the onerror event in Netscape Navigator 3.0.

You can use the onerror event to gracefully handle errors in user input. In the following example, the user types a color name that is applied to the document's text box. If the user types an invalid color name, a custom dialog box warns the user that the color name is invalid.

<SCRIPT LANGUAGE="JavaScript">
   function doError() {
      if (arguments[0] == "runtime error 380") {
         alert("Invalid Color Name");
         return true;
      }
   }
   window.onerror = doError;
</SCRIPT>
Color:
<INPUT TYPE=TEXT ONCHANGE="this.style.color = this.value;"
   VALUE="Black">

The onerror event passes the event handler three arguments: an error description, the name of the file in which the error occurred, and the line number of the error. Error handlers should not use the line number parameter because if the source is edited, the line numbers will be updated and the error handlers will no longer work.

User Events

User events are events that fire when the user interacts with the window—for example, when the user resizes or scrolls the window. These events fire after the actions have been completed, so event handlers can't cancel the actions. Chapter 5, "Window and Frame Management," introduces methods that scripts can use to resize or scroll the window.

Using CSS (Cascading Style Sheets), you can create containers within the document that support scrolling and resizing. These actions fire the same events on the containers as they do on the window.

The onresize Event

Every time the user resizes a window, an onresize event fires on the window. This event lets you write code that rearranges the contents or even other windows in relation to the current size of the document.

The onscroll Event

The onscroll event is fired each time the document is scrolled, either by the user manually moving the scrollbar or by an action that results in the document being scrolled—for example, navigating to a bookmark or using the arrow keys. The properties for determining the current scrollbar's position are exposed through the body object on the document itself. Interacting with these properties is demonstrated in Chapter 5; a complete discussion of these properties is presented in Chapter 9, "Scripting Individual Elements."

Specifying Window Events

All the window events—including onblur, onfocus, onload, onunload, and onbeforeunload—can be specified as attributes of the <BODY> tag in an HTML page, which allows you to bind these events to a handler using attributes rather than scripts, as shown in the following code:

<HTML>
   <HEAD>
      <TITLE>Hooking Up Event Handlers</TITLE>

      <SCRIPT LANGUAGE="JavaScript">
         function doLoad() {
            // Do something when document is loaded.
         }

         function doUnload() {
            // Do something when document is about to be unloaded.
         }
         window.onload = doLoad;  // Hook up event handler in script.
      </SCRIPT>
   </HEAD>
   <!— Hook up event handler using a Body element attribute. -->
   <BODY ONUNLOAD="doUnload();">
   </BODY>
</HTML>

[Содержание]