Browser events: Handling events

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 handlers is very rarely used today, due to its constraints, but it was the only way in the JavaScript early days:

<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 to register as many handlers as we need, and it’s the one you will find mostly used 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 to specific elements to check events happening specifically 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
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!