DOM Event Listener
The addEventListener
method allows you to attach event handlers to DOM elements. It provides flexibility by allowing multiple event listeners for the same event on the same element and supports options like capturing and passive behavior.
Key Topics
- Adding Event Listener
- Removing Event Listener
- Event Listener Options
- JavaScript Usage in DOM
- Key Takeaways
Adding Event Listener
The addEventListener
method attaches an event handler to a DOM element without overwriting existing event listeners.
const button = document.getElementById("myButton");
button.addEventListener("click", () => {
console.log("Button clicked!");
});
Output
> Button clicked!
Explanation: The addEventListener
method listens for the click
event on the button and logs a message when the event occurs.
Removing Event Listener
The removeEventListener
method detaches a previously added event listener, requiring a reference to the original handler function.
function handleClick() {
console.log("Button clicked!");
}
button.addEventListener("click", handleClick);
button.removeEventListener("click", handleClick);
Output
(No output after removing the event listener.)
Explanation: The removeEventListener
method removes the specified event listener from the button, preventing further event handling.
Event Listener Options
Options can be passed to addEventListener
to control behavior, such as capturing or passive events.
document.addEventListener("scroll", () => {
console.log("Scrolling detected!");
}, { passive: true });
Output
> Scrolling detected!
Explanation: The passive
option improves performance by indicating that the event listener will not call preventDefault
.
JavaScript Usage in DOM
Below is a complete DOM example demonstrating how to add and remove event listeners dynamically.
<!DOCTYPE html>
<html>
<head>
<title>DOM Event Listener Example</title>
</head>
<body>
<button id="myButton">Click Me</button>
<script>
const button = document.getElementById("myButton");
function handleClick() {
alert("Button clicked!");
}
button.addEventListener("click", handleClick);
setTimeout(() => {
button.removeEventListener("click", handleClick);
alert("Event listener removed!");
}, 5000);
</script>
</body>
</html>
Key Takeaways
- Add Listeners: Use
addEventListener
to attach event handlers dynamically. - Remove Listeners: Use
removeEventListener
to detach event handlers. - Options: Customize listener behavior with options like
passive
andcapture
. - Dynamic Interaction: Event listeners enable real-time interaction with webpage elements.