Building Your Learning Module...
Getting things ready for you!
Find videos you like?
Save to resource drawer for future reference!
When you click an element, the event doesn't just fire on that element! It travels through the DOM in three distinct phases: Capture (down), Target (element), and Bubble (up).
Event travels DOWN from window to target
Event reaches the target element
Event travels UP from target to window
const parent = document.querySelector('#parent');
const child = document.querySelector('#child');
// Capture phase (3rd parameter = true)
parent.addEventListener('click', function() {
console.log('Parent - CAPTURE phase');
}, true);
child.addEventListener('click', function() {
console.log('Child - TARGET phase');
});const parent = document.querySelector('#parent');
const child = document.querySelector('#child');
// Default is bubble phase
child.addEventListener('click', function() {
console.log('Child - TARGET phase');
});
parent.addEventListener('click', function() {
console.log('Parent - BUBBLE phase');
});const grandparent = document.querySelector('#gp');
const parent = document.querySelector('#p');
const child = document.querySelector('#c');
// Capture phase
grandparent.addEventListener('click', () => {
console.log('1. Grandparent CAPTURE');
}, true);
// Target phase
child.addEventListener('click', () => {
console.log('2. Child TARGET');
});
// Bubble phase
parent.addEventListener('click', () => {
console.log('3. Parent BUBBLE');
});const parent = document.querySelector('#parent');
const child = document.querySelector('#child');
child.addEventListener('click', function(e) {
console.log('Child clicked');
e.stopPropagation(); // Stop here!
});
parent.addEventListener('click', function() {
console.log('Parent clicked');
// This will NOT fire!
});const list = document.querySelector('#list');
// One listener for all items!
list.addEventListener('click', function(e) {
if (e.target.tagName === 'LI') {
console.log('Clicked:', e.target.textContent);
e.target.style.backgroundColor = 'lightgreen';
}
});
// Add new items dynamically - still works!addEventListener(event, handler, true)e.stopPropagation() - Stop bubblinge.stopImmediatePropagation() - Stop all handlerse.target to identify child