Event Listeners
The addEventListener() Method
The addEventListener() method attaches an event handler to an
element without overwriting existing event handlers.
element.addEventListener(event, function, useCapture);
The Event Object
When an event occurs, the browser creates an event object, puts details into it, and passes it as an argument to the handler.
Event Bubbling vs Capturing
There are two ways of event propagation in the HTML DOM: bubbling and capturing.
- Bubbling (Default): The inner element's event is handled first, then the outer.
- Capturing: The outer element's event is handled first, then the inner.
Removing Listeners
The removeEventListener() method removes event
handlers that have been attached with the addEventListener()
method.
Note: To remove a handler, the handler function must be a named function (not an anonymous function).
Summary
- Use
addEventListenerto attach multiple handlers to an element. - The
eventobject contains information about the event. - Event bubbling handles inner elements first; capturing handles outer elements first.
- Use
removeEventListenerto clean up event handlers.
Quick Quiz
Which method stops the event from bubbling up the DOM tree?
Enjoying these tutorials?