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);
Get JavaScript: The Definitive Guide, Fourth Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.