π What is Closure in JavaScript? ? Explained with Simple Examples

When building modern web applications, adding event listeners to multiple DOM elements can quickly become a hassle — and impact performance. But what if you could use just one event listener to control many elements? That’s the power of Event Delegation in JavaScript!
Event Delegation is a JavaScript technique where a single event listener is attached to a parent element, and events from child elements are caught during the bubbling phase.
Instead of assigning handlers to each item individually, you delegate the event to the parent, checking the event’s target to determine what was clicked or interacted with.
document.querySelectorAll('.btn').forEach(button => {
button.addEventListener('click', () => {
alert('Button clicked!');
});
});
This method works, but creates multiple listeners — not ideal for performance.
document.getElementById('button-container').addEventListener('click', (e) => {
if (e.target.classList.contains('btn')) {
alert('Button clicked!');
}
});
Just one listener, no matter how many buttons you have — now that’s efficient!
e.target
or e.currentTarget
to identify the source of the event.classList.contains()
or matches()
to ensure you're targeting the right element.e.stopPropagation()
wisely.Event Delegation is a simple yet powerful trick every JavaScript developer should know. By leveraging bubbling, you write less code, create faster apps, and build dynamic UIs with ease.
π Explore More JavaScript Tips at: https://webcodingwithankur.blogspot.com
π¬ Have questions? Drop them in the comments below or share this post with your fellow devs!
Comments
Post a Comment