What's Event Bubbling?
When an event occurs on a DOM element, that event does not entirely occur on that just one element. In the Bubbling Phase, the event bubbles up or it goes to its parent, to its grandparents, to its grandparent's parent until it reaches all the way to the window.
If we have an example markup like this.
<div class="grandparent"><div class="parent"><div class="child">1</div></div></div>
And our js code.
function addEvent(el, event, callback, isCapture = false) {if (!el || !event || !callback || typeof callback !== 'function') return;if (typeof el === 'string') {el = document.querySelector(el);}el.addEventListener(event, callback, isCapture);}addEvent(document, 'DOMContentLoaded', () => {const child = document.querySelector('.child');const parent = document.querySelector('.parent');const grandparent = document.querySelector('.grandparent');addEvent(child, 'click', function (e) {console.log('child');});addEvent(parent, 'click', function (e) {console.log('parent');});addEvent(grandparent, 'click', function (e) {console.log('grandparent');});addEvent(document, 'click', function (e) {console.log('document');});addEvent('html', 'click', function (e) {console.log('html');});addEvent(window, 'click', function (e) {console.log('window');});});
The addEventListener
method has a third optional parameter useCapture with a default value of false
the event will occur in the Bubbling phase if true
the event will occur in the Capturing Phase. If we click on the child
element it logs child
,parent
,grandparent
, html
, document
and window
respectively on the console. This is Event Bubbling.
October 03, 2022
1685
Read more
What is the JavaScript += Operator and How Do You Use It?
December 04, 2022
JavaScriptUsing the startsWith() Method in JavaScript
December 04, 2022
JavaScriptReverse a String in JavaScript: 2 Easy Methods
December 02, 2022
JavaScript