Skip to Main Content
JavaScript: The Definitive Guide, Fourth Edition
book

JavaScript: The Definitive Guide, Fourth Edition

by David Flanagan
November 2001
Intermediate to advanced content levelIntermediate to advanced
936 pages
68h 43m
English
O'Reilly Media, Inc.
Content preview from JavaScript: The Definitive Guide, Fourth Edition

Name

EventListener — an event handler function DOM Level 2 Events

Availability

Methods

handleEvent( )

In languages such as Java that do not allow functions to be passed as arguments to other functions, you define an event listener by defining a class that implements this interface and includes an implementation for this handleEvent( ) method. When an event occurs, the system calls this method and passes in an Event object that describes the event.

In JavaScript, however, you define an event handler simply by writing a function that accepts an Event object as its argument. The name of the function does not matter, and the function itself is used in place of an EventListener object. See the Section section.

Description

This interface defines the structure of an event listener or event handler. In languages such as Java, an event listener is an object that defines a method named handleEvent( ) that takes an Event object as its sole argument. In JavaScript, however, any function that expects a single Event argument, or a function that expects no argument, can serve as an event listener.

Example

// This function is an event listener for a "submit" event
function submitHandler(e) {
  // Call a form-validation function defined elsewhere
  if (!validate(e.target))
      e.preventDefault(  );  // If validation fails, don't submit form
}

// We might register the event listener above like this
document.forms[0].addEventListener("submit", submitHandler, false);

See Also

Event, EventTarget; Chapter 19

Passed ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

JavaScript: A Beginner's Guide, Fourth Edition, 4th Edition

JavaScript: A Beginner's Guide, Fourth Edition, 4th Edition

John Pollock
Coding with JavaScript For Dummies

Coding with JavaScript For Dummies

Chris Minnick, Eva Holland

Publisher Resources

ISBN: 0596000480Supplemental ContentCatalog PageErrata