22. Can you explain the concept of 'event delegation' in JavaScript?

Event delegation is a technique in JavaScript where a single event listener is added to a parent element instead of adding multiple event listeners to individual child elements. This is particularly useful for managing events on dynamically generated elements or when there are many child elements.

Here’s how it works:

  1. Event Bubbling: When an event is triggered on an element, it first runs the handlers on that element and then bubbles up to the parent elements, running their handlers as well.
  2. Using a Single Event Listener: By placing an event listener on a common ancestor of all the elements that need to be monitored, you can capture events as they bubble up.
  3. Identifying the Target: Within the event handler, you can determine the actual target of the event using the event.target property and perform the necessary action.

Example:

// Parent element const parent = document.getElementById('parent'); // Event delegation parent.addEventListener('click', function(event) { if (event.target && event.target.matches('button.someClass')) { console.log('Button clicked:', event.target); } });

Event delegation is efficient and helps in reducing memory usage and improving performance, especially when dealing with large lists or dynamic content.

devFlipCards 2024

Do you accept cookies?

Cookies are small amounts of data saved locally on you device, which helps our website - it saves your settings like theme or language. It helps in adjusting ads and in traffic analysis. By using this site, you consent cookies usage.