본문으로 건너뛰기

Activating the Carousel

Now, we will use JavaScript to make the carousel operational.


Setting Initial Values

Setting Initial Values
let slideIndex = 1;
showSlides(slideIndex);

Before we start creating the functionality of the carousel, we need to set some initial configurations.

First, we create a variable named slideIndex to store the index of the currently displayed slide.

To show the first slide initially, we set the value of slideIndex to 1.

Then, we call a function named showSlides and pass the value of slideIndex as an argument.

Since slideIndex is 1 here, it will display the first slide.


Implementing Slide Transition Function

Creating Previous/Next Buttons
<a class="prev" onclick="plusSlides(-1)">&#10094;</a>
<a class="next" onclick="plusSlides(1)">&#10095;</a>

While setting up the structure of the carousel, we created previous/next buttons.

Now, we need to make these buttons function so that the slides transition when clicked.

Declaring the plusSlides Function to Transition Slides
function plusSlides(n) {
showSlides((slideIndex += n));
}

We previously mentioned that the showSlides function changes the displayed slide based on the value of its argument.

The example code's plusSlides function is created to call the showSlides function.

However, it calls showSlides by increasing or decreasing the slideIndex value by n.

So, if n is 1, the slideIndex value increases by 1, and if it's -1, the slideIndex decreases by 1.

Therefore, if slideIndex is 1 and the first slide is being shown, calling plusSlides(1) will increase slideIndex to 2, displaying the second slide.

Similarly, if slideIndex is 2 and the second slide is being shown, calling plusSlides(-1) will decrease slideIndex to 1, showing the first slide again.

By calling the plusSlides function, the slideIndex value increases or decreases by 1, resulting in the transition of the slides.


Creating a Function to Transition to Specific Slides

Creating Indicators
<span class="dot" onclick="currentSlide(1)"></span>
<span class="dot" onclick="currentSlide(2)"></span>
<span class="dot" onclick="currentSlide(3)"></span>

In addition to the previous/next buttons, I also created indicators.

These dot indicators are designed so that clicking on them takes you to a specific slide.

Clicking on the first dot takes you to the first slide, the second dot to the second slide, and the third dot to the third slide.

Declaring the currentSlide Function
function currentSlide(n) {
showSlides((slideIndex = n));
}

The currentSlide function, like the recently created plusSlides function, is also made to call the showSlides function.

However, when calling showSlides, the value of slideIndex is set to n.

So, if n is 1, then slideIndex becomes 1, if it's 2, then slideIndex becomes 2, and if it's 3, slideIndex becomes 3.

Thus, if slideIndex is 1 and the first slide is being shown, calling currentSlide(3) will set slideIndex to 3, and the third slide will be displayed.