Advanced JavaScript Events
In addition to basic event handling, JavaScript provides advanced techniques for managing events.
Event Propagation
Events propagate through the DOM in two phases:
- Capturing Phase: The event moves from the root to the target element.
- Bubbling Phase: The event moves back from the target to the root.
You can specify the phase using the third parameter of addEventListener:
element.addEventListener("click", function() {
console.log("Event triggered!");
}, true); // true for capturing phase
Event Delegation
Event delegation allows you to handle events efficiently by attaching a single event listener to a parent element:
document.getElementById("parent").addEventListener("click", function(event) {
if (event.target.tagName === "BUTTON") {
console.log("Button clicked:", event.target.textContent);
}
});
Example
<!DOCTYPE html>
<html>
<body>
<div id="parent">
<button>Button 1</button>
<button>Button 2</button>
</div>
<script>
document.getElementById("parent").addEventListener("click", function(event) {
if (event.target.tagName === "BUTTON") {
alert("Button clicked: " + event.target.textContent);
}
});
</script>
</body>
</html>