Javascript enables our web apps to be interactive. It can recognize events generated by a user such as a mouse click, scrolling on a mouse wheel, pressing down on a key of the keyboard, etc... Handling these types of user actions smoothly is important for a great user experience. Today, we will learn how we can efficiently handle JavaScript events using mouse click events as an example.
addEventListener method
JavaScript has a built-in method called addEventListener which you can append onto HTML nodes. It takes in a total number of 3 arguments as follows:
- Name of an event.
- The callback function to run some code when the specified event is triggered.
- Optional: the Boolean value of capture. (Set to false by default).
<div id="div1">I am a div1</div>
const div1 = document.getElementById("div1");
div1.addEventListener("click", function() {
console.log("div1 clicked");
});
As you would expect, clicking on 'I am a div' text will print 'div1 clicked' on the console. Let's wrap the text with a new div in the HTML. Can you guess what the output is now if you click on the text?
<div id="div1">
<div id="div2">I am a div1</div>
</div>
const div1 = document.getElementById("div1");
div1.addEventListener("click", function() {
console.log("div1 clicked");
});
The result stays the same and prints "I am a div1" even though we clicked on the div with the id of 'div2'.
Event bubbling
By default, events bubble in JavaScript. Event bubbling is when an event will traverse from the most inner nested HTML element and move up the DOM hierarchy until it arrives at the element which listens for the event. This move is also popularly known as Event Propagation or Event Delegation.
In the above example, Clicking on the text 'I am a div1' is equivalent to clicking on #div2. Because we have the event listener on the parent element #div1, the event starts the most inner child #div2 and bubbles up.
Here is an additional example. Let's also attach an event listener to the div2 in JavaScript.
<div id="div1">
<div id="div2">I am a div</div>
</div>
const div1 = document.getElementById("div1");
const div2 = document.getElementById("div2");
div1.addEventListener("click", function() {
console.log("div1 clicked");
});
div2.addEventListener("click", function() {
console.log("div2 clicked");
});
Here is the result of event bubbling.
div2 clicked
div1 clicked
Note we can also add event listeners to root level elements such as html and body, the events will bubble until then. This is the hierarchy:
Target -> Body -> HTML -> Document -> Window
Stop propagation
Sometimes, you don't want events to trave in a direction, then you can use stopPropagation() of the event object. The event object is provided as a parameter in the callback function.