Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.
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 ancestor elements 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) has an event object that extends this base Event object.
Lessons in this unit:
| 0: | Introduction |
| 1: | Handling events |
| 2: | The `DOMContentLoaded` event |
| 3: | ▶︎ The `event` object |
| 4: | Mouse events |
| 5: | Keyboard events |
| 6: | `preventDefault()` |
| 7: | Stopping event propagation |
| 8: | Bubbling and capturing |
| 9: | Form submit event |
| 10: | Input fields events |
| 11: | Creating custom events |
| 12: | Keyboard Events |
| 13: | Mouse Events |
| 14: | Touch Events |
| 15: | Form Events |