1. Home
  2. Computing & Technology
  3. JavaScript

The Javascript DOM

16. Event Handlers

clr gif

So far in looking at how to access the DOM we have looked at how to reference parts of the web page and how we can read, add, alter, and delete parts of the page content. What we haven't looked at yet is how our visitors can interact with the web page in order to initiate these changes and how we can detect when our visitors want to do so.

Our visitors interwact with our web page by pressing keys on their keyboard, by moving their mouse, clicking mouse buttons etc. These actions when they relate to the web page are called events and there are two aspects to our being able to handle these events.

  1. We need to detect when these events have occurred so as to respond to them. We do this by attaching event handlers to our web page that will detect when the event occurs and trigger the required processing.
  2. We also need to detect where the event occurred since the same event when applied to different parts of the page can have totally different requirements.

Traditionally both of these two aspects of handling events were taken care of by physically attaching the Javascript event handler into the part of the page where the particular action is to be performed when that event occurs. For example:

<a href="next.htm"
onclick="window.open(this.href,'','width=200,height=200">

Adding event handlers this way "pollutes" our (X)HTML with Javascript code and means that we need to edit the HTML every time that we want to add, change, or delete event handling on our page.

The better way of handling events triggered by our visitors is to separate the Javascript for the event handlers out into the external file along with the rest of our Javascript and to make use of the DOM to attach the events to the appropriate parts of the page.

There are actually a couple of different ways that we can attach event handlers to our page via the DOM and we will look at those in more detail over the next few tutorials.

Explore JavaScript
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. JavaScript

©2009 About.com, a part of The New York Times Company.

All rights reserved.