Event Delegation
Event delegation is a technique by which you delegate a parent element as a listener in order to avoid to add multiple child elements.
Every event listener that you create uses memory in the browser. So with using event delegation, you save memory and simplify initialization.
Let's see in example:
Three Equal Columns
Column 1
Some text..
Column 2
Some text..
Column 3
Some text..
The HTML code is as below:
<h2>Three Equal Columns</h2>
<div class="row">
<div class="column" style="background-color:#bab;">
<h3>Column 1</h3>
<p>Some text..</p>
</div>
<div class="column" style="background-color:#bca;">
<h3>Column 2</h3>
<p>Some text..</p>
</div>
<div class="column" style="background-color:#acc;">
<h3>Column 3</h3>
<p>Some text..</p>
</div>
</div>
The row has 3 columns, but it could be more than 3.
The column background color will be changed randomly by event delegation instead of assingn an click
handler to each column (can be many).
The JavaScript code is as below:
const row = document.querySelector(".row");
const randomInt = (max, min) =>
Math.floor(Math.random() * (max - min + 1) + min);
const randomColor = () =>
`rgb(${randomInt(0, 255)}, ${randomInt(0, 255)}, ${randomInt(0, 255)})`;
row.addEventListener("click", function (e) {
//to get the clicked closest column element
const clicked = e.target.closest(".column");
// Guard clause
if (!clicked) return;
// change column background color randomly
clicked.style.backgroundColor = randomColor();
});
It doesn’t matter how many columns are in the row. column
can be added or removed dynamically at any time and the code will still work.
References: - three equal columns - event delegation
Comments