Adding and Removing Event Listeners

This sample gives a few examples of how to add and remove event listeners with the Spry.Utils.addEventListener() and Spry.Utils.removeEventListener() functions.

First the basics. To add an event listener to an element on your page, define a listener function (aka handler function), and then call Spry.Utils.addEventListener() to attach it:

<script src="../../includes/SpryDOMUtils.js" type="text/javascript" language="javascript"></script>

...

<div id="myDiv">Click me!</div>

...

<script type="text/javascript>

function myClickHandler(event)
{
	alert("myClickHandler was called!");
}

Spry.Utils.addEventListener("myDiv", "click", myClickHandler, false);

</script>

A couple of important things to note about you handler function is that when it is invoked, the 'this' reference within your function will be the actual DOM element the handler was attached to with the addEventListener call. Also, for IE, the event object passed into your handler has the W3C standard stopPropagation() and preventDefault() methods defined on it, so you no longer have to set the proprietary IE equivalents. Some examples of how the value you return from your handler and calls to stopPropagation() and/or preventDefault() effect processing, can be seen below.

Another thing to note, is that if you call addEventListener() to attach the same listener function to the same element, for the same event type, repeatedly, the handler will still only be invoked once.

To remove an event listener from an element, simply call Spry.Utils.removeEventListener() with the exact same arguments you used when you called Spry.Utils.addEventListener():

<script type="text/javascript>

Spry.Utils.removeEventListener("myDiv", "click", myClickHandler, false);

</script>

In the following example, different event listeners are attached to each link in the list. Click on the links to see how the different types of handlers effect the processing of the link. To remove the event handlers on the links, press the "Remove Event Handlers" button. To add them back, press the "Add Event Handlers" button.

Event handlers are *NOT* active!