JAVASCRIPT
Implement Event Delegation for Dynamic Content
Master event delegation in JavaScript to efficiently handle events on dynamically added elements by attaching a single event listener to a parent element.
<div id="parentContainer" style="border: 1px solid #ccc; padding: 10px; min-height: 50px;">
<p>Click dynamic buttons below:</p>
</div>
<script>
document.getElementById('parentContainer').addEventListener('click', function(event) {
if (event.target && event.target.matches('.dynamic-button')) {
console.log('Dynamic button clicked:', event.target.textContent);
event.target.textContent = 'Clicked!';
event.target.style.backgroundColor = '#dcedc8'; // Greenish background
}
});
// Example of dynamically added content after initial load
setTimeout(() => {
const btn1 = document.createElement('button');
btn1.classList.add('dynamic-button');
btn1.textContent = 'Click Me One';
btn1.style.margin = '5px';
btn1.style.padding = '8px';
btn1.style.backgroundColor = '#bbdefb';
const btn2 = document.createElement('button');
btn2.classList.add('dynamic-button');
btn2.textContent = 'Click Me Two';
btn2.style.margin = '5px';
btn2.style.padding = '8px';
btn2.style.backgroundColor = '#bbdefb';
const container = document.getElementById('parentContainer');
container.appendChild(btn1);
container.appendChild(btn2);
console.log('Dynamic buttons added.');
}, 1000);
</script>
How it works: Event delegation is a powerful technique to improve performance and simplify event handling, especially for elements that are added to the DOM dynamically. Instead of attaching individual event listeners to each element, a single listener is attached to a common parent. When an event (like a click) bubbles up to the parent, the `event.target` property is used along with `matches()` to check if the event originated from a specific descendant element, even if that descendant was created and added after the initial event listener setup.