Home arrow JavaScript arrow Page 3 - Interactive Effects

Mashable Event Handling - JavaScript

If you're looking for a quick way to delight your visitors with the addition of Ajax to your site, look no further. This article, the first part of a four-part series, will show you how to do some very nice interactive effects. It is excerpted from chapter four of Adding Ajax, written by Shelley Powers (O'Reilly, 2007; ISBN: 0596529368). Copyright 2007 O'Reilly Media, Inc. All rights reserved. Used with permission from the publisher. Available from booksellers or direct from O'Reilly Media.

TABLE OF CONTENTS:
  1. Interactive Effects
  2. Ajax-Friendly Event Handling
  3. Mashable Event Handling
  4. The Dojo Event System and the Target Object
By: O'Reilly Media
Rating: starstarstarstarstar / 7
September 20, 2007

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

Another approach, and a recommended one, is to use DOM Level 2 event handling. This technique "chains" event handlers so that when an event fires, all associated functions are run. An example of adding an event handler to the click event for the document is as follows:

  document.addEventListener("click",eventHandlerFunction,false);

In the addEventListener method, the first parameter is the event (click) and the second is the event handler function. The third optional parameter determines whether the processing of the event begins in the outermost object, flowing to the inner in a set of nested objects (true), or from the innermost to the outer (false). The first is known as the capturing phase, and the second, the default, emulates the older DOM level 0 event processing by handling the event in the bubble up phase.

To demonstrate both, Example 4-1 shows a page with two div elements, one within the other. A generic event handler routine, manageEvent, is created to attach event handlers to objects, taking as parameters three objects: the target object, the event, and the event handler function.

The first event captured is for the window, in order to assign the click event handler to the two div elements after they're loaded. The window's load event handler then assigns the click event handlers of both div elements to the same function: clickHandler.

Example 4-1. An event handler method that plays well with others

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Event Listening</title>
<style type="text/css">
#inner { width: 400px; height: 100px; background-color: #00f;}
#outer { width: 400px; background-color: #ff0; padding: 10px; }
</style>

<script type="text/javascript">
//<![CDATA[

function manageEvent(evntObject,event,eventHandler) {
   
evntObject.addEventListener(event,eventHandler,false);
}
manageEvent(window,"load",
           
function () {
  
manageEvent(document.getElementById('inner'),"click",clickHandler);
   
manageEvent(document.getElementById('outer'),"click",clickHandler);
         
});

function clickHandler() {
  
alert(this.id);
}
//]]>
</script>

</head>
<body>
<div id="outer">
<div id="inner">
</div>
</div>
</body>
</html>

In the example page, clicking on the innermost div element results in an alert message box that displays the word "inner," followed by another alert message box that displays the word "outer." Setting the third parameter in the manageEvent function to true (setting event handling to capturing phase), clicking on the two div elements results in an alert box with outer, followed by another with the word, "inner."

Capturing the event in the wrong phase can have a significantly negative impact on your application. Since most event handlers are coordinated to work in a bubble up phase, unless you want to capture an event in the capturing phase for a specific reason, you'll usually set the third parameter to false.

Using addEventListener is great, except for one thing: Microsoft's Internet Explorer (6.x and 7) doesn't support it. This browser supports another function-- attachEvent:

  document.attachEvent("onclick",eventHandlerFunction);

There are two differences between attachEvent and addEventListener. The first is that in attachEvent, you pass the event handler name, not the event, as the first parameter (onclick as compared to click). The second is that attachEvent doesn't have a third parameter because it always handles events in the bubble up phase.

To ensure that event handling works with IE 6.x/7 and other browsers, you'll need to incorporate both types of event handler methods, the W3C DOM Level 2 method and Microsoft's. This means you'll have to test to see whether a specific event listener is supported, and code accordingly. Modifying the manageEvent function to work with IE as well as other browsers results in the following:

  function manageEvent(eventObj, event, eventHandler) {
     if (eventObj.addEventListener) {
       e
ventObj.addEventListener(event, eventHandler,false);
    
} else if (eventObj.attachEvent) {
       event = "on" + event;
       eventObj.attachEvent(event, eventHandler);
   
}
  }

The event object is tested to see whether addEventListener is a property associated with the object. If it is, it's used as the event handler dispatch method; otherwise, attachEvent is checked, and it's used if found.

If the user agent doesn't support addEventListener or attachEvent, the application can then fall back to the older DOM level 0 event handler, onclick. This isn't as critical a need anymore, as browsers that can't support some form of advanced event handling have fallen more or less out of use.

To stop listening to an event, use the comple mentary methods, removeEventListener and detachEvent:

  function stopManagingEvent(eventObj,event,eventHandler) {
    if (eventObj.removeEventListener) {
       eventObj.removeEventListener(event,eventHandler,false);
    } else if (eventObj.detachEvent) {
       event = "on" + event;
       eventObj.detachEvent(event,eventHandler); 
   
}
  }

In the cases where you want to cancel an event, you'll need to stop the event propagation for the Mozilla browsers, but cancel the bubble up for IE. In addition, you'll need to stop the default event handling, which you do by using preventDefault with Mozilla/W3C browsers, and by setting the returnValue to false for IE. The following cancelEvent method should take care of this:

  function cancelEvent(event) {
    
if (event.preventDefault) {
        event.preventDefault();
        event.stopPropagation();
     } else {
        event.returnValue = false;
        event.cancelBubble = true;
    
}
  }

Event management functions are used so frequently, you'll want to add them to whatever libraries you use. I added them to this book's Ajax library as aaManageEvent, aaStopEvent, and aaCancelEvent, prepending the functions with "aa" so they won't conflict with other libraries you might be using.

If you use external libraries in your Ajax applications, most of them provide event handling. The next section briefly introduces the event handling system from one of them, Dojo's Event System.



 
 
>>> More JavaScript Articles          >>> More By O'Reilly Media
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

JAVASCRIPT ARTICLES

- Javascript for Beginners: An Introduction
- Introduction to JavaScript
- Adding Elements to a Tree with TreeView jQue...
- Using the Persist Argument in a TreeView jQu...
- Using Unique and Toggle in a TreeView jQuery...
- Using Event Delegation for Mouseover Events ...
- Using the Animate Option in a Treeview jQuer...
- Using HTML Lists with Event Delegation in Ja...
- Opened and Closed Branches on a TreeView jQu...
- Mouseover Events and Event Delegation in Jav...
- Creating a TreeView JQuery Hierarchical Navi...
- Event Delegation in JavaScript
- A Look at the New YUI Carousel Control
- Working with Draggable Elements and Transpar...
- Displaying Pinned Handles with Resizable Con...

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: