What's Event Capturing?

When an event occurs on a DOM element, that event does not entirely occur on that just one element. In Capturing Phase, the event starts from the window all the way down to the element that triggered the event.

If we have an example markup like this.

<div class="grandparent">
<div class="parent">
<div class="child">1</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) {
}, true);
addEvent(parent, 'click', function (e) {
}, true);
addEvent(grandparent, 'click', function (e) {
}, true);
addEvent(document, 'click', function (e) {
}, true);
addEvent('html', 'click', function (e) {
}, true)
addEvent(window, 'click', function (e) {
}, true)

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 window,document, html, grandparent and parent and child respectively on the console. This is Event Capturing.

October 02, 2022