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.
Lessons in this unit:
Are you intimidated by Git? Can’t figure out
merge vs rebase? Are you afraid of screwing up
something any time you have to do something in
Git? Do you rely on ChatGPT or random people’s
answer on StackOverflow to fix your problems?
Your coworkers are tired of explaining Git to
you all the time? Git is something we all need
to use, but few of us really master it. I
created this course to improve your Git (and
GitHub) knowledge at a radical level. Launching
May 21, 2024. Join the waiting list!