An event handler gets an Event
object as the first parameter, in this example I named it event
(you can use any name you want, like e
or theevent
:
const link = document.getElementById('my-link')
link.addEventListener('click', event => {
// link clicked
})
This object contains a lot of useful properties and methods, like:
target
, the DOM element that originated the eventtype
, the type of eventstopPropagation()
, called to stop propagating the event in the DOM
and more. You can see the full list here.
An event on a DOM element will be propagated to all its parent elements tree unless it’s stopped.
<html>
<body>
<section>
<a id="my-link" ...>
In this example a click event on the element defined with the a
tag will propagate to section
and then body
.
You can stop the propagation by calling the stopPropagation()
method of an Event, usually at the end of the event handler:
const link = document.getElementById('my-link')
link.addEventListener('mousedown', event => {
// process the event
// ...
event.stopPropagation()
})
Each specific kind of event, like a mouse click, a touch event, or a keyboard event, implement an event that extends this base Event
object.