When a user clicks the right button, the carousel should move to the next slide. When they click the left button, the carousel should move to the previous slide.
To do this, we need to differentiate between the left and right buttons.
When a user clicks the next button, we want to show the next slide. To show the next slide, we need to know what’s the currently displayed slide.
The easiest way to tell JavaScript about the current slide is through a class. Since the carousel starts by showing the first slide, we add an is-selected class to the first slide.
After changing the displayed slide, we need to update the location of the is-selected class. If we don’t update the is-selected class, we won’t be able to move to the third slide.
Here, we remove is-selected from currentSlide and add it to nextSlide. (This is because nextSlide is the displayed slide after we changed the left property).
When the page loads, we show the first slide of the carousel. Since we’re on the first slide, users should not be able to move to a “previous” slide. (There are no previous slides).
We can hide the button to make better UX. To hide the button, we add a hidden attribute to the HTML.
When a user clicks the next button, we show the second slide. When the carousel is at the second slide, users should be able to go back to the first slide. Here, we need to show the previous button again.
When the user clicks the next button for a second time, we show the third slide in the carousel. This third slide also the last slide in the carousel. User should not be able to move to a fourth slide (because it doesn’t exist). We need to hide the next button.
Here’s how we can hide the next button:
When a user clicks the next button
We check if there’s one more slide after the nextSlide.
If there are no more slides, we know nextSlide is the last slide.
If nextSlide is the last slide, we hide the next button by adding the hidden attribute.
nextButton.addEventListener('click', event => {
// ...
// Hides next button
if (!nextSlide.nextElementSibling) {
nextButton.setAttribute('hidden', true)
}
})
Now, if the user clicks the left button, we go back to the second slide. We must show the next button again (because they can move back to the third slide).
If the user clicks the left button again, they will arrive at the first slide. Here, we must hide the previous button again (because there are no more “previous” slides).
Here’s how we can hide the previous button:
When a user clicks the previous button
We check if there’s one more slide before the previousSlide.
If there are no more slides, we know previousSlide is the first slide.
If previousSlide is the first slide, we hide the previous button by adding the hidden attribute.