JavaScript is partly an object-oriented language.
To learn JavaScript, we got to learn the object-oriented parts of JavaScript.
In this article, we’ll look at listening to events.
Events
We can listen to events triggered by users.
For instance, we can listen to mouse button clicks, keypresses, page load etc.
We can attach event listener functions to listen to all these events.
Inline HTML Attributes
One way to add event listeners to our elements is to add them as attribute values.
For instance, we can write:
<div onclick="alert('clicked')">click me</div>
We have the onclick
attribute with value being the JavaScript code alert(‘clicked’)
.
This is easy to add, but hard to work with if the code gets complex.
Element Properties
We can also add them as element properties.
For instance, given the following HTML:
<div>click me</div>
We can write:
const div = document.querySelector('div');
div.onclick = () => {
alert('clicked');
};
We have the div which we get with document.querySelector
.
Then we set the onclick
property to a function that runs when we click on the div.
This is better because it keeps JavaScript out of our HTML.
The drawback of this method is that we can only attach one function to the event.
DOM Event Listeners
The best way to listen to browser events is to add event listeners.
We can have as many as of them as we want.
And the listeners don’t need to know about each other and can work independently.
To attach an event listener to our element, we can call the addEventListener
method.
For instance, we can write:
const div = document.querySelector('div');
div.addEventListener('click', () => {
alert('clicked');
});
div.addEventListener('click', console.log.bind(div))
We added 2 different event listeners.
One is a function to display an alert.
The other is to log the event object in the console.
Capturing and Bubbling
The addEventListener
method takes a 3rd parameter.
It lets us set whether to listen in capture mode or not.
Event capturing is when an event propagates down from the document
object to the element which originally triggered the event.
Event bubbling is the opposite. It’s where an event propagates from element that triggered the event to the document
object.
If we set the 3rd parameter to true
, then we listen to the event propagation from the docuemnt
object to the original element.
An event goes from the capture phase to the originating element, to the bubbling phase.
Most browsers implement all 3 phases, so we can set the optional anywhere.
We can stop the propagation from the originating element to the document by calling stopPropagation
on the event object.
We can also use event delegation to check which element triggered an event.
Conclusion
There are a few ways to listen to events from elements.
We can add event listeners or add inline JavaScript to HTML.