We can use 4 of 11 features we learned for the carousel. They are:
- Early returns
- Template literals
- Rest and Spread operators
- Useful array methods
Using array spread
You can replace Array.from with the spread operator if you wish to:
// Change theseconst slides = Array.from(carousel.querySelectorAll('.carousel__slide'))const dots = Array.from(carousel.querySelectorAll('.carousel__dot'))// To theseconst slides = [...carousel.querySelectorAll('.carousel__slide')]const dots = [...carousel.querySelectorAll('.carousel__dot')]Using template literals
We can use template literals to move each slide.
// Change thiscontents.style.transform = 'translateX(-' + destination + ')'// To thiscontents.style.transform = `translateX(-${destination})`Early returns
We can use early returns in dot container’s event handler.
// Change thisdotsContainer.addEventListener('click', event => { const dot = event.target.closest('button') if (dot) { // Stuff here }})// To thisdotsContainer.addEventListener('click', event => { const dot = event.target.closest('button') if (!dot) return
// Stuff here})JavaScript array features
When we searched for targetIndex in dot container’s event handler, we used a for loop. We can replace this with findIndex.
let clickedDotIndex
for (let index = 0; index < dots.length; index++) { if (dots[index] === dot) { clickedDotIndex = index }}const clickedDotIndex = dots.findIndex(d => d === dot)And we’re done improving the carousel.
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