I have a SplideJS slider with an amount of slides. I need to perform an action when the last slider is active.
I check documentation but I didn't found any reference to this kind of event so I write a script to acheive that goal but i need some help
My code :
// Class for each slide
const splideSlide = document.querySelector('.splide__slide')
// Check if a next element sibling is available
if(splideSlide.nextElementSibling === undefined) {
console.log("On last, I call aother action")
} else {
console.log("Not last")
}
Going with what @CBroe mentioned in the commends, active
is the one that might work for you.
const maxSlideIndex = document.querySelectorAll("li.splide__slide").length - 1;
secondarySlider = new Splide( '#example', {
perPage : 1,
perMove : 1,
focus : 'center',
trimSpace : false,
autoWidth: true,
} ).mount();
secondarySlider.on("active",function(e){
if(e.index === maxSlideIndex) {
console.log("I'm the last one!");
}
});
#example {
max-width: 650px;
}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@splidejs/splide@4.1.4/dist/css/splide.min.css">
<script src="https://cdn.jsdelivr.net/npm/@splidejs/splide@4.1.4/dist/js/splide.min.js"></script>
<div id="example" class="splide">
<div class="splide__track">
<ul class="splide__list">
<li class="splide__slide"><img src="https://placehold.co/600x400/EEE/FF343C" alt="Sample Image 01"></li>
<li class="splide__slide"><img src="https://placehold.co/600x400/EEE/3FF43C" alt="Sample Image 02"></li>
<li class="splide__slide"><img src="https://placehold.co/600x400/AAA/31FF3C" alt="Sample Image 03"></li>
<li class="splide__slide"><img src="https://placehold.co/600x400/EEE/313FFC" alt="Sample Image 04"></li>
<li class="splide__slide"><img src="https://placehold.co/600x400/AAA/3134FF" alt="Sample Image 05"></li>
<li class="splide__slide"><img src="https://placehold.co/600x400/EEE/F1343F" alt="Sample Image 06"></li>
</ul>
</div>
</div>
First thing I'm doing is getting the max index value, so that I'll know which slide is the last one. This could have been handled in other ways (for example li.splide__slide:nth-child
and then getting the index of that one).
Next, after initializing the Splide slider, I'm attaching an active
event listener, and checking if the currently active slide's index is the same as the index of the last li.splide__slide
.