Download as pdf or txt
Download as pdf or txt
You are on page 1of 16

Internet Systems

Chapter 14. Dynamic HTML: Event Model


DHTMLs event model lets scripts respond to user actions.

Event onclick
The onclick event fires when the user clicks the mouse. The following causes the enclosed script to be executed when the element with id element_ID is clicked. <script type = text/javascript for = element_ID event = onclick> </script> We get inline scripting by including onclick = script in the opening tag of an element e.g.,
<p onclick = "alert( 'second' )">p2</p>

212

Internet Systems

Example:
<html> <head> <title>onclick Example</title> <script type = "text/javascript" for = "p1" event = "onclick"> alert( "first" ); </script> </head> <body> <p id = "p1">p1</p> <p onclick = "alert( 'second' )">p2</p> </body> </html>

The rendering is: p1 p2

When p1 is clicked, an alert box appears with text first. When p2 is clicked, an alert box appears with text second. The alert boxes may be raised and dismissed any number of times.

213

Internet Systems

The event Object, and Tracking the Mouse with Event onmouseover
The event object contains information about the triggered event. Some of the properties of event are: type is the name of the event that fired. srcElement is a reference to the object that fired the event. This object has its usual properties e.g., event.srcElement.tagName propertyName is the name of the property that changed in this event. offsetX / offsetY are the coordinates of the mouse cursor relative to the object that fired the event. x / y are the coordinates of the mouse cursor relative to the parent element of the element that fired the event. screenX / screenY are the coordinates of the mouse cursor on the screen coordinate system. clientX / clientY are the coordinates of the mouse cursor within the client area (the active area where the page is displayed). altKey is true if the ALT key was pressed when the event fired. Similar properties: ctrlKLey and shiftKey. button gives the mouse button pressed: 1 (left), 2 (right), 3 (left and right), 4 (middle), 5 (left and middle), 6 (right and middle), or 7 (all three). See Figure 14.5, p. 464 in the text for more.

214

Internet Systems

Event onmousemove fires constantly when the mouse is in motion. Example:


<html> <head> <title>onmousemove example</title> <script type = "text/javascript"> function updateMouseCoordinates() { coordinates.innerText = event.srcElement.tagName + " (" + event.offsetX + ", " + event.offsetY + ")"; } </script> </head> <body onmousemove = "updateMouseCoordinates()"> <span id = "coordinates">(0, 0)</span><br> <img src = "ellipse.bmp" style ="position: absolute; top: 100; left: 100"> </body>

215

Internet Systems

When the mouse cursor is not over the image, the coordinates are in the bodys coordinate system.

When its over the image, the coordinates are in the images coordinate system.

216

Internet Systems

Rollovers with onmouseover and onmouseout


When the mouse cursor moves over an element, event onmouseover is fired for that element. When the mouse cursor leaves an element, event onmouseout is fired for that element. Handling these events, we can achieve a rollover effect: the text of an element changes as the mouse moves over and out of it. The document object has predefined event-handler slots for certain events. You can associate an event handler with an event by assigning its name to the corresponding slot: document.event_handler_slot = event_handler; Then, when the corresponding event happens, event_handler is invoked. The name event_handler_slot is usually the lowercase event name. Examples: document.onmouseover = mOverHandler; document.onmouseout = mOutHandler; Here mOverHandler and mOutHandler are event handlers for the events onmouseover and onmouseout written by the programmer. The following is needed for the next example. We can create a new image object and set its src property to the file containing the image with variable_name = new Image(); variable_name.src = file_name; Creating an image object lets us pre-load the desired image rather than delaying download to when the image is displayed.

217

Internet Systems

Example: Here we define in the body a 22 table (where we show the ids in parentheses): 1 (E0) 3 (E2) 2 (E1) 4 (E3)

In the script, we initialize two array variables: ar1 = [ one, two, three, four ], ar2 = [ I, II, III, IV ] When the mouse cursor moves over the cell with id Ei, the numeral word ar1[ i ] appears in the cell. When the mouse cursor moves out of the cell, the Roman numeral ar2[ i ] appears in it. The name (a string) of the of the source element of the event is given by event.srcElement.id For this example, we use all but the first character of this as a subscript into either the ar1 or the ar2 array: ar1[ event.srcElement.id.substr( 1 ) ] Both event handlers first check whether the event was the image object (with id first). If not, they check that the source element of the event has an id (that the id property is not undefined): if ( event.srcElement.id ) We must do this since both events (onmouseover and onmouseout) fire for any element, but we process these events only for certain elements (those with ids).

218

Internet Systems

<html> <head> <title>Rollover Example</title> <script type = "text/javascript"> var image1 image2 ar1 ar2 = = = = new Image(), new Image(), [ "one", "two", "three", "four" ], [ "I", "II", "III", "IV" ];

image1.src = "ellipse.bmp"; image2.src = "rectangle.bmp"; document.onmouseover = mOverHandler; document.onmouseout = mOutHandler; function mOverHandler() { if ( event.srcElement.id == "first" ) event.srcElement.src = image2.src; else if (event.srcElement.id ) event.srcElement.innerText = ar1[ event.srcElement.id.substr(1) ]; } function mOutHandler() { if ( event.srcElement.id == "first" ) event.srcElement.src = image1.src; else if (event.srcElement.id ) event.srcElement.innerText = ar2[ event.srcElement.id.substr(1) ]; } </script> </head>

Continued next page

219

Internet Systems

Continued from previous page


<body> <img src = "ellipse.bmp" id = "first"> <table style = "width: 30%; text-align: center"> <caption>Some Numbers</caption> <tr style = "text-align: center"> <td id = E0 style= "width: 15%">1</td> <td id = E1 style= "width: 15%">2</td> </tr> <tr style = "text-align: center"> <td id = E2 style= "width: 15%">3</td> <td id = E3 style= "width: 15%">4</td> </tr> </table> </body> </html>

220

Internet Systems

When the mouse cursor enters the area with the image of the ellipse, the image of a rectangle appears. When the mouse cursor leaves the area with the image of the rectangle, the image of ellipse re-appears. These images keep swapping: when the mouse cursor is in the area, we have a square; when its out, we have am ellipse. When the mouse cursor enters a cell with one of the numbers, say, 2, it is replaced with its number word, two. When the mouse cursor leaves this cell, the Roman number II appears. Two and II keep swapping: when the mouse cursor is in the cell, we have two; when its out, we have II. But 2 never re-appears.

221

Internet Systems

Error Handling with onerror


Scripts can use the onerror event to execute specialized errorhandling code in place of the error dialog presented by browsers. Suppose we define a function errorHandler as the handler for the onerror event: document.onerror = errorHandler; The header of this function should have three arguments (the names are up to you): function errorHandler( errType, errURL, errLineNum ) Here errType (a string) is the type of the error, errURL (a string) is URL of the page where the error occurred, and errLineNum (an integer) is the number of the line where the error occurred. It returns true to indicate that it has handled the error. If it returns false, the default response (an error dialog) occurs. The following is needed for the next example. We can cause text to appear in the status bar at the bottom of the browser window by assigning it to window.status.

222

Internet Systems

Example We define an error handler that writes to the status bar the type of error and the line and URL where it occurred. We force an error by associating a call to an undefined function with the onclick event of a paragraph element.
<html> <head> <title>onerror event</title> <script type = "text/javascript"> document.onerror = errorHandler; function errorHandler( errType, errURL, errLineNum ) { window.status = "Error: " + errType + " on line " + errLineNum + " of " + errURL; return true; } </script> </head> <body> <p onclick = "doThis()">Click here</p> </body> </html>

223

Internet Systems

When the text Click here of the paragraph is clicked, we get:

To make sure this example works, open the Control Panel and select Internet Options. Click the Advanced tab. Under Browsing, make sure the Disable script debugging check box is not selected.

224

Internet Systems

Event Bubbling
Suppose an element and one of its ancestors both respond to a given event. Then, without provision to the contrary, the event bubbles up from the element to the ancestor. Suppose you want the event to be handled by the given elements event handler and not by that of the ancestor. Then you can set the events cancelBubble property: event.cancelBubble = true;

Example: Here the document has a handler for event onclick: document.onclick = documentClick; Both paragraphs in the body use paragraphClick( b_value ), defined in the script, as their handler for onclick. One has true as the argument, which cancels bubbling. The other has false, permitting bubbling.

225

Internet Systems

<html> <head> <title>Event Bubbling</title> <script type = "text/javascript"> function documentClick() { alert( "You clicked in the document" ); } function paragraphClick( value ) { alert( "You clicked the text" ); if ( value ) event.cancelBubble = true; } document.onclick = documentClick; </script> </head> <body> <p onclick = "paragraphClick( false )"> Click here!</p> <p onclick = "paragraphClick( true )"> Click here, too!</p> </body> </html>

226

Internet Systems

The following shows the screen after the text Click here! was clicked, and after the alert box stating You clicked the text was dismissed. The onclick event has bubbled up from the paragraph to the document.

If the text Click here, too! is clicked, then an alert box stating You clicked the text again appears. But now, when this alert box is dismissed, no further alert box appears bubbling up to the document has been canceled.

More DHTML Events See Figure 14.10, pp. 474-476, in the text for descriptions of the remaining events, not discussed in detail in Chapter 14.

227

You might also like