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.
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.
Welcome! Unfortunately, you don’t have access to this lesson. To get access, please purchase the course or enroll in Magical Dev School.
Unlock this lesson