Implementing Carousel Functionality
Now, let's use JavaScript to create a functional carousel.
Setting Initial Values
let slideIndex = 1;
showSlides(slideIndex);
Before starting to implement the carousel functionality, we need to set some initial values.
First, we'll create a variable called slideIndex
to store the index of the currently displayed slide.
To ensure the first slide is shown initially, we set slideIndex
to 1.
Then, we invoke the showSlides
function, passing the slideIndex
as an argument.
Here, because the value of slideIndex
is 1, the first slide will be displayed.
Implementing Slide Navigation Functionality
<a class="prev" onclick="plusSlides(-1)">❮</a>
<a class="next" onclick="plusSlides(1)">❯</a>
We already structured the carousel and created the previous/next buttons.
Now we need to make these buttons functional so that slides change on click.
function plusSlides(n) {
showSlides((slideIndex += n));
}
We already discussed that the showSlides
function displays a slide based on the value of the passed argument.
The plusSlides
function is designed to call the showSlides
function.
It calls the showSlides
function, increasing the value of slideIndex
by n
.
So, if n
is 1, the slideIndex
value increases by 1, and if n
is -1, the slideIndex
value decreases by 1.
Therefore, when the value of slideIndex
is 1 (showing the first slide), calling plusSlides(1)
increments the slideIndex
to 2, showing the second slide.
Similarly, if the value of slideIndex
is 2 (showing the second slide), calling plusSlides(-1)
decrements the slideIndex
to 1, showing the first slide again.
Thus, calling the plusSlides
function results in the slideIndex
value increasing or decreasing by 1, allowing for slide navigation.
Implementing Direct Slide Selection Functionality
<span class="dot" onclick="currentSlide(1)"></span>
<span class="dot" onclick="currentSlide(2)"></span>
<span class="dot" onclick="currentSlide(3)"></span>
Aside from the previous/next buttons, we also created indicators.
Clicking these dot-shaped indicators should take the user to a specific slide.
Clicking the first dot should display the first slide, the second dot should display the second slide, and the third dot should display the third slide.
function currentSlide(n) {
showSlides((slideIndex = n));
}
Similar to the plusSlides
function, the currentSlide
function calls the showSlides
function.
However, when calling showSlides
, it sets the value of slideIndex
to n
.
So, if n
is 1, slideIndex
is set to 1, if n
is 2, slideIndex
is set to 2, and if n
is 3, slideIndex
is set to 3.
Thus, when the value of slideIndex
is 1 (showing the first slide), calling currentSlide(3)
will set slideIndex
to 3, displaying the third slide.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.