Event Delegation: Save thou webpage

Kumar Chetan Sharma
1 min readDec 24, 2023

To make a web page interactive web developers rely on Events on the page. Event handling could be as easy as reloading the page on click of a button or as complex as following mouse pointer and responding to it. The usual way to do this is onEvent do some thing.

<button name="aButton" id="aButton" onclick="alert('Hello World!')">CLICK ME!!!</button>

Easy.

There are so many ways to handle events and then do something. Inline, shown above, unobtrusive, shown below.

<button name="anotherButton" id="anotherButton">CLICK ME!!!</button>
<script>
document.getElementById('anotherButton').addEventListener('click', function(){alert('Hello World!')}, false);
</script>

One can add as many as event listeners required for an event occurring for an element. Well, not really a wise idea. Think of Gmail inbox set to display 100 emails in a row. Does that mean 100 addEventListener? Not a good idea. Here comes a very simple technique called Event Delegation. Example:

<ol id="olElem">
<li id="li1">One</li>
<li id="li2">Two</li>
<li id="li3">Three</li>
<li id="li4">Four</li>
<li id="li5">Five</li>
<li id="li6">Six</li>
<li id="li7">Seven</li>
<li id="li8">Eight</li>
<li id="li9">Nine</li>
<li id="lin">n</li>
</ol>
<script>
document.getElementById('olElem').onclick = (e) => {
e = e || window.event;
const target = e.target || e.srcElement;
const textClicked = document.getElementById(target.id).innerHTML;
alert('You clicked ' + textClicked);
}
</script>

This is all due to Event Bubbling which simply means that an event bubbles up to document root. So, when I click on “Nine”, the element li9 tells its parent that it got clicked, which in turn informs its parent and so on.

--

--

Kumar Chetan Sharma

C0d3🐵 from 🇮🇳. selfTaught. 😨 of CS, Algos & DS. World famous 👨‍🍳 at home. Pro Level Pro-Crastinator. Man child. Dad of (✿◠‿◠)(◠‿◠✿)