Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.
You can respond to any event using an Event Handler, which is a function that’s called when an event occurs.
You can register multiple handlers for the same event, and they will all be called when that event happens.
JavaScript offers three ways to register an event handler:
- Inline event handlers
- DOM on-event handlers
- addEventListener
Let’s see each of them.
Inline event handlers
This style of event handler is rarely used today because of its limitations, but it was the only way in the early days of JavaScript:
<a href="#" onclick="alert('link clicked')">A link</a>
DOM on-event handlers
This is common when an object has at most one event handler, as there is no way to add multiple handlers in this case:
document.querySelector('a').onclick = () => {
alert('link clicked')
}
Using addEventListener
Using addEventListener is the modern way. This method allows you to register as many handlers as you need, and it’s the one you’ll find most often in the wild:
window.addEventListener('load', () => {
// window loaded
})
Sometimes addEventListener is called on window, sometimes on a specific DOM element, like this:
document.querySelector('div').addEventListener('click', () => {
//
})
Why? It’s a matter of determining how large of a net you want when you are looking at intercepting events.
You can listen on window to intercept “global” events, like the usage of the keyboard, or you can listen on specific elements for events that happen only on them, like a mouse click on a button.
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 |