EventTarget Interface
Events serve as a communication mechanism between different parts of a program. All event operations on DOM nodes (listening and triggering) are defined within the EventTarget interface.
- addEventListener(): Attaches an event listener function
- removeEventListener(): Removes an event listener function
- dispatchEvent(): Triggers an event manually
The useCapture parameter is a boolean that determines when the listener should be triggered. When set to true, the listener activates during the capture phase. By default, it's false, meaning the listener responds during the bubbling phase.
Event Propagation Phases
- Capture Phase
- Targeet Phase
- Bubble Phase
<div>
<p>click</p>
</div>
<script>
const phaseMap = {
1: 'capture',
2: 'target',
3: 'bubble'
};
const container = document.querySelector('div');
const textElement = document.querySelector('p');
container.addEventListener('click', handler, true);
container.addEventListener('click', handler, false);
textElement.addEventListener('click', handler, true);
textElement.addEventListener('click', handler, false);
function handler(event) {
const elementTag = event.currentTarget.tagName;
const currentPhase = phaseMap[event.eventPhase];
console.log(`Tag: '${elementTag}'. EventPhase: '${currentPhase}'. event.eventPhase: ${event.eventPhase}`);
}
</script>
Output:
Tag: 'DIV'. EventPhase: 'capture'. event.eventPhase:1
Tag: 'P'. EventPhase: 'target'. event.eventPhase:2
Tag: 'DIV'. EventPhase: 'bubble'. event.eventPhase:3
Event Delegation
Since events propagate upward during the bubbling phase, you can place a single listener on a parent element to handle events from multiple child elements.
const list = document.querySelector('ul');
list.addEventListener('click', function (event) {
if (event.target.tagName.toLowerCase() === 'li') {
// Handle list item click
}
});
To halt propagation at a specific element:
// Stops propagation after reaching the p element
textElement.addEventListener('click', function (event) {
event.stopPropagation();
// event.stopImmediatePropagation(); // Prevents all subsequent listeners
}, true);
Event Object
Create custom events using the Event constructor:
const customEvent = new Event('look', {
bubbles: true,
cancelable: false
});
const clickEvent = new Event('click');
textElement.dispatchEvent(clickEvent);
- Event.target: The original element that triggered the event
- Event.currentTarget: The element currently processing the event (equivalent to
thisin the listener) - Event.type: A string representing the event type
Preevnting Default Behavior
Event.preventDefault() stops the browser's default action for the event. Common use cases include:
- Preventing form submission on button click
- Stoppping link navigation
Passive Event Listeners
Using {passive: true} tells the browser the listener won't call preventDefault(), allowing for performance optimizations.
Stopping Propagation
event.stopPropagation() prevents the event from continuing through the DOM tree.