Sobes.tech
Middle+

How to implement event delegation for a list with buttons that open a modal window?

sobes.tech AI

Answer from AI

Event delegation allows attaching a single event handler to a common container of a list, instead of attaching handlers to each button. This saves resources and simplifies management.

Example in JavaScript:

const list = document.getElementById('button-list');

list.addEventListener('click', event => {
  const target = event.target;
  if (target.tagName === 'BUTTON') {
    // Open a modal window using data from the button
    const modalContent = target.dataset.modalContent;
    openModal(modalContent);
  }
});

function openModal(content) {
  const modal = document.getElementById('modal');
  modal.querySelector('.content').textContent = content;
  modal.style.display = 'block';
}

In this example, a single handler on the button-list container catches clicks on buttons inside. It checks that the click was specifically on a button, and then calls the function to open a modal window with the appropriate content.