๐Ÿ›  Carousel: Event delegation

Hey ,

I'm thrilled to help you learn JavaScript. Unfortunately, you've landed on a page where you cannot access with your current purchase.

Please upgrade (use this link) access this content.

I'm super eager to help you learn more!

๐Ÿ›  Carousel: Event delegation

We can use the event delegation pattern to listen for a click event on the dots. If we do this, weโ€™ll use one event listener instead of 3 (or however many dots there are).

Using the event delegation pattern

We should listen for the event on the closest possible ancestor parent. In this case, the closest possible ancestor parent is .carousel__dots.

<div class="carousel__dots">
  <button class="carousel__dot is-selected"></button>
  <button class="carousel__dot"></button>
  <button class="carousel__dot"></button>
</div>
const dotsContainer = carousel.querySelector('.carousel__dots')

dotsContainer.addEventListener('click', event => {
  // ...
})

The callback triggers whenever you click inside dotsContainer. It triggers even if you click on the spaces between the dots.

Arrows pointing to empty spaces between dots

We donโ€™t want to do anything if the user clicks on the space between the dots. We only want to do something if they click on a dot.

To ensure this happens, we make sure the user clicks on a dot with either closest or matches.

dotsContainer.addEventListener('click', event => {
  const dot = event.target.closest('button')
  if (dot) {
    // Do something
  }
})

The rest of the component remains the same.