Course Content
HTML & JavaScript Interactivity for Beginners
HTML & JavaScript Interactivity for Beginners
Adding Event Listeners to HTML Elements
In the previous chapter, you saw how events trigger function calls through event attributes inside an HTML element. However, that method has many drawbacks. If an element had multiple events, putting all the event attributes to handle each of them inside an HTML tag makes the code look bloated and unreadable.
Therefore a better way around this issue is to keep the functionality separate from the structure. Thus it would help if you add an event listener to each HTML element through JavaScript, and then when the event triggers, the relevant function will be called.
Let's start with a simple example for the click
event.
Event Listener with Click Event
index
index
index
Adding Multiple Event Listeners
You can add multiple event listeners to the same HTML element and call different functions for each triggered event. This is ideal in scenarios where the HTML element handles numerous events.
index
index
index
Passing Parameters to Event Listeners
You can also pass parameters to an event listener. In the below example, you'll discover how you can pass the element that triggered the event and get its value. Likewise, you can pass any numerical values and so on.
index
index
index
Event Bubbling and Capturing
You can propagate events in the HTML DOM in two ways: bubbling and capturing.
Event propagation is the process of the occurrence of events from child elements to parent elements or vice versa.
Suppose there is a <div>
element that houses a paragraph element, and if the event handler is placed on both elements, there will be a question of what happens when a user clicks on the <div>
element, for instance.
- Bubbling: The inner element handles the event first, followed by the outer element;
- Capturing: The outer element handles the event first, followed by the inner element.
You can decide whether to use bubbling or capturing based on the parameters set on the useCapture
parameter. By default, it is set to false, which is bubbling, and if set to True
, it will use capturing.
index
index
index
Thanks for your feedback!