Event Bubbling & Propogation
Video
JavaScript Notes
JavaScript
// JavaScript Event Bubbling and Propagation
// By default events bubble up through the DOM tree
// element.addEventListener(type, function, useCapture); - to capture down
let m = document.getElementById('m');
let d = document.getElementById('d');
let p = document.getElementById('p');
let s = document.getElementById('s');
let log = console.log
let highlight = (ev) =>{
// add CSS class "gold" to the clicked element
ev.stopPropagation( ); // stops propagation up the DOM tree
let target = ev.currentTarget
target.className = "gold";
reset (target);
}
let reset = (_element) => {
setTimeout( ( ) => {_element.className = ' ';
}, 2000);
} );
d.addEventListener('click', (ev)=>{
ev.stopImmediatePropagation ( ); // stops click event from going to main, and other click events on div
log('Hi I\’m a DIV');
}, false); // third parameter is false by default
[m, d, p, s].forEach( element ( ) => {
element.addEventListener('click', highlight)
});
Feedback
Submit and view feedback