Introduction:
In this article, you will learn the concept of addEventListener, which is a DOM method.
What is addEventListener?
addEventListener() is a DOM method and it is used to attach an event handler to an element.
Old way
<button onclick="handleClick()">Click</button>
In Modern JavaScript use:
button.addEventListener("click", handleClick);
Note: You can keep JavaScript separate from HTML, which is a best practice.
Basic Syntax
element.addEventListener(event, function, options);
Explained
event: Type of event (click, mouseover, keydown, etc.).
function: Callback function that runs when the event occurs.
options: Optional (capture, once, passive).
Basic Example
<button id="btn">Click Me</button>
<script>
const button = document.getElementById("btn");
button.addEventListener("click", function() {
alert("Button Clicked!");
});
</script>
When the button is clicked, the function runs.
Why Use addEventListener Instead of onclick?
| Feature | addEventListener | onclick |
|---|---|---|
| Multiple Handlers | Yes | No |
| Separation of Concerns | Yes | No |
| Modern Practice | Yes | Outdated |
| Remove Event Easily | Yes | Limited |
Multiple Event Listeners Example
button.addEventListener("click", function() {
console.log("First handler");
});
button.addEventListener("click", function() {
console.log("Second handler");
});
Note: both functions will be called when you click the button.
Some Common Events You Should Know
Mouse Events
- click
- dblclick
- mouseover
- mouseout
Keyboard Events
- keydown
- keyup
- keypress
Form Events
- submit
- change
- input
Window Events
- load
- resize
- scroll
Event Object
The callback function receives an event object.
Example:
button.addEventListener("click", function(event) {
console.log(event.target);
});
The event object contains:
- Target
- Type
- preventDefault()
- stopPropagation()
❌ Removing Event Listener
To remove an event, you must use the same function reference.
function handleClick() {
console.log("Clicked");
}
button.addEventListener("click", handleClick);
button.removeEventListener("click", handleClick);
Note: Anonymous functions cannot be removed.
Common Beginner Mistakes
❌ Calling the function immediately
button.addEventListener("click", handleClick()); // Wrong
✅ Correct way
button.addEventListener("click", handleClick);
Event Bubbling & Capturing in JavaScript
In this article, you will clear the concept of Event Bubbling & Capturing.
If you don’t understand Event Bubbling and Capturing, you’ll eventually face unexpected bugs in JavaScript.
What is Event Propagation?
Event propagation defines how events travel in the DOM tree.
When an event occurs, it doesn’t just happen on one element. It moves through the DOM in three phases:
- Capturing Phase
- Target Phase
- Bubbling Phase
Capturing Phase
The event starts from the root (document) and travels down to the target element.
document → html → body → parent → child
Target Phase
The event reaches the actual element that was clicked.
Bubbling Phase (Default Behavior)
The event bubbles back up from the target to the root.
child → parent → body → html → document
Note: By default, JavaScript uses the bubbling phase.
Example of Event Bubbling
HTML:
<div id="parent">
<button id="child">Click Me</button>
</div>
JavaScript:
document.getElementById("parent").addEventListener("click", function() {
console.log("Parent clicked");
});
document.getElementById("child").addEventListener("click", function() {
console.log("Child clicked");
});
Output:
Child clicked
Parent clicked
Example of Event Capturing
To enable capturing, pass true as the third parameter.
document.getElementById("parent").addEventListener("click", function() {
console.log("Parent clicked");
}, true);
Output:
Parent clicked
Child clicked
Note: the event is captured before reaching the target.
Bubbling vs Capturing
| Feature | Event Bubbling | Event Capturing |
|---|---|---|
| Direction | Child → Parent | Parent → Child |
| Default Behavior | Yes | No |
| addEventListener Third Parameter | false (default) | true |
| Use Case | Event Delegation | Special Control Cases |
How to Stop Event Bubbling
You can stop event bubbling through below method.
Syntax:
event.stopPropagation();
Example:
document.getElementById("child").addEventListener("click", function(event) {
event.stopPropagation();
console.log("Child clicked only");
});
Note: Now the parent event will NOT fire.
Real-World Use Case: Event Delegation
Event bubbling makes event delegation, you can check below example
document.getElementById("list").addEventListener("click", function(e) {
if (e.target.tagName === "LI") {
console.log("List item clicked");
}
});
Note: This improves performance in large applications.
When Should You Use Capturing?
Capturing is rarely used. You can use
- You want parent logic before child logic.
- Handling complex UI interactions
❌ Confusing stopPropagation and preventDefault
stopPropagation() → It is used to stop bubbling.
preventDefault() → It stops default browser behavior.
Interview Questions
Q 1: What is addEventListener in JavaScript?
Ans: addEventListener() is a DOM method and it is used to attach an event handler to an element. It allows you to run a function when a specific event occurs, such as a click, hover, or key press.
Q 2: What is the syntax of addEventListener?
Ans: element.addEventListener(event, function, useCapture);
Q 3: What is the difference between addEventListener and onclick?
Ans: addEventListener: It allows multiple event handlers on the same element.
onclick: It allows only one event handler.
addEventListener provides more flexibility and better control over event handling.
Q 4: Can we remove an event listener in JavaScript?
Ans: Yes, we can remove an event listener using the removeEventListener() method.
Example: element.removeEventListener("click", myFunction);
Q 5: Why is addEventListener preferred in modern JavaScript development?
Ans: Because it supports multiple events, better event management, and follows modern JavaScript standards.
Conclusion
The addEventListener is an important DOM method. Developers can attach multiple events to elements and handle them efficiently. If you compare older event-handling methods like onclick, addEventListener offers greater flexibility and better control over how events are managed.
Understanding how to use addEventListener properly will help you create more interactive and dynamic web applications.