The addEventListener() method in JavaScript is used to attach an event handler to a specific element. This method allows you to listen for events on the element and respond when the event occurs. Unlike setting event handlers directly (e.g., using onclick), addEventListener() allows you to add multiple handlers for the same event type without overriding each other.
element.addEventListener(event, function, useCapture);
• event: (Required) A string that specifies the event to listen for. Examples include "click", "mouseover", "keydown", etc. Do not prefix with "on" (e.g., use "click" instead of "onclick").
• function: (Required) The function to execute when the event occurs. This is the event handler function.
• useCapture: (Optional) A boolean indicating whether the event should be captured during the capturing phase (true) or the bubbling phase (false). Defaults to false (bubbling).
Events in JavaScript propagate through the DOM in two phases: capturing and bubbling.
Event Bubbling: The event starts from the target element and bubbles up to the root element. For example, if you have a <p> element inside a <div>, and both elements have click event listeners, the click event on the <p> will be handled first, and then the event will bubble up to the <div>.
Event Capturing: The event starts from the root element and travels down to the target element. In this case, the <div> event will be handled first, followed by the event.
<div style="padding: 20px; border: 1px solid black;" id="container1">
<span style="margin: 10px; padding: 10px; border: 1px solid red;"
id="inner1">Click me (Bubbling)</span>
</div><br>
<div style="padding: 20px; border: 1px solid black;" id="container2">
<span style="margin: 10px; padding: 10px; border: 1px solid red;"
id="inner2">Click me (Capturing)</span>
</div>
<script>
// Bubbling Example
document.getElementById('container1').addEventListener('click', function() {
alert('Container 1 Clicked (Bubbling)');
});
document.getElementById('inner1').addEventListener('click', function() {
alert('Inner 1 Clicked (Bubbling)');
});
// Capturing Example
document.getElementById('container2').addEventListener('click', function() {
alert('Container 2 Clicked (Capturing)');
}, {capture: true}); // Set useCapture to true for capturing
document.getElementById('inner2').addEventListener('click', function() {
alert('Inner 2 Clicked (Capturing)');
}, {capture: true}); // Set useCapture to true for capturing
</script>