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.