JavaScript Concepts I Wish I Understood Earlier: Event Bubbling & Event Delegation
"With AI writing the code, maybe it's time we finally understand what the code is doing." ๐ The rise of AI has made writing code easier than ever. It has also made one thing increasingly important for me: actually understanding JavaScript. After a year away from frontend development, I found myself coming back to JavaScript feeling more than a little disoriented, especially with the AI boom, andโฆ
In the world of JavaScript, one concept that is essential to understand is event bubbling and event delegation. These concepts can help make your code more efficient and easier to manage.
Imagine you're creating an FAQ section with accordion/drop-down buttons for each question. Each question has a button that, when clicked, reveals the answer while closing any other open answers. This creates a simple structure like this:
<div class="acc">
<div class="acc-item" data-id="1">
<h3 class="acc-title">Question 1</h3>
<button class="acc-icon-container">+</button>
<p class="acc-content hide">Answer 1</p>
</div>
<!-- Repeat the above structure for other questions -->
</div>
The issue with the traditional way of handling this was using separate listeners for each button and content. This approach created a direct relationship between the buttons, content, and headers, relying on the index to keep everything connected. This was fine, but it had its downsides. The index had to maintain the structure and order of the elements, which could be a problem if the structure changed.
The better approach is Event Delegation. Instead of attaching an event listener to every button, you can attach one listener to the parent container:
const accordionList = document.querySelector('.acc');
accordionList.addEventListener('click', (event) => {
// ...
});
This way, you have a single listener for the entire accordion. But how does the parent know which button was clicked? This is where event bubbling comes in. Event bubbling is when an event is triggered on an element, but continues to propagate up the DOM tree until it reaches the root element.
To determine which button was clicked, you can access the target of the event in your event listener:
accList.addEventListener('click', (event) => {
const target = event.target;
if (target.matches('.acc-icon-container')) {
// Handle button click
}
});
This approach is much more efficient as it reduces the number of listeners and simplifies the code. The parent container can handle the event for all its children, making the code cleaner and easier to maintain. This is a powerful technique that every JavaScript developer should understand and use in their projects.
Written by urgent.news from Dev.to's reporting โ not their text. Machine-written โ may contain errors; check the original before relying on it.