Working with the Event Listener

When the DOM came into prominence and DHTML became a viable web technology we seemed to gain a lot of new tools. The great thing about a lot of the new tools is that they are very useful. The downside is that some of them force you to delve a little deeper into JavaScript and maybe learn something new. In other words, you have to step outside your comfort zone. Trust me, this is a good thing!

The event listener was added when the W3C event model was introduced. But first let’s make sure we know what an event is – what indeed is an event? Someone once said “without events there are no scripts” and that is pretty much correct. Take a look at your scripts and HTML pages and you’ll notice that in order to run your functions, you are triggering them via events.

$2.89
- OR -

Overview

What are events?

An event allows the user to interact with the web page, and allow JavaScript to react to that interaction. Events are what allow JavaScript to truly make pages interactive. JavaScript needs a way to detect what the user has done in your pages, and then respond to them accordingly. When a user interacts with a page, an event is generated. Sometimes, the page itself generates an event, not the user. For example, the load and unload events are triggered by the page, not the user (even though the user probably caused the page to load/unload, it is technically triggered by the page).

What about event handlers?

So how does JavaScript allow us to handle these events? Since Netscape 2 we’ve been able to handle events with an event handler. You’ve certainly been through the source of an HTML page and seen many events attached to HTML elements, such as onMouseover, onFocus and onChange. And even though we are moving toward an “unobtrusive JavaScript” model where these handlers are not going to be directly in the HTML – the concept is still the same and they will still work the same way. These event handlers tell JavaScript what to do when the event is fired.

We will still attach event handlers to elements, we’ll just do it in a more efficient manner. We’re now able to attach event handlers directly to elements using new methods that will keep our HTML free of clutter – and make our scripts more powerful. For example, suppose you wanted to use TWO events on one element. With the new methods you could add one, listen for the event and handle it, then remove the first one and add a second one. That would be extremely difficult to do the old way.

The only issue we’ll have to deal with is different event models, because IE and Mozilla handle things differently. Not to worry though, we’ll use object detection and it will be as simple as pie.

Reviews

Be the first to write a review

You must me logged in to write a review.