Search code examples
javascripteventsevent-delegation

Event delegation with vanilla JS


Based on the following HTML markup:

<div class='list-container'>
  <button class="btn">More details </button>
</div>

<div class="details">Lorem ipsum lorem ipsum lorem ipsum</div>

I wrote the following JavaScript code:

let btn = document.querySelector('.btn');
let detailsContainer = document.querySelector('.details');

btn.addEventListener('click', function(e) {
  e.preventDefault();
  detailsContainer.classList.toggle('visible');
});

But I need to change the JS code to use the event delegation so that the eventListener gets added to the list-container instead of to the btn.

It's easy in jQuery, but how can I do it in vanilla JS?


Solution

  • Just add a listener to the .list-container instead, and on click, check to see if the target matches the .btn:

    const detailsContainer = document.querySelector('.details');
    document.querySelector('.list-container').addEventListener('click', ({ target }) => {
      if (target.matches('.btn')) detailsContainer.classList.toggle('visible');
    });
    .details { display: none }
    .visible { display: block }
    <div class='list-container'>container outside of button
      <button class="btn">More details </button>
    </div>
    
    <div class="details">Lorem ipsum lorem ipsum lorem ipsum</div>