Last active
October 8, 2024 09:00
-
-
Save Jehu/1f4038fdbcf9ee8c0b5a58cefd7cbbfd to your computer and use it in GitHub Desktop.
Splide with custom pagination that only shows that many dots
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Show only MAX_DOTS in Splide Pagination. | |
* | |
* This code generates a custom pagination. | |
* Therefore you need to disable the Splide pagination with the option `pagination: false`. | |
* You can configure the number of visible pagination dots via MAX_DOTS. | |
* The active dot is moved from left to right and starts at the left if the end of | |
* MAX_DOTS is reached. So the user can see that there is something happen when using the Slider. | |
*/ | |
// Splide Configuration | |
const slider_options = { | |
pagination: false, // => this is important | |
}; | |
const createCustomPagination = (splide) => { | |
const MAX_DOTS = 8; | |
const customPagination = document.createElement('ul'); | |
customPagination.className = 'splide__pagination'; | |
const updatePagination = () => { | |
const totalSlides = splide.length; | |
const currentIndex = splide.index; | |
let start = Math.floor(currentIndex / MAX_DOTS) * MAX_DOTS; | |
const end = Math.min(start + MAX_DOTS, totalSlides); | |
customPagination.innerHTML = ''; | |
for (let i = start; i < end; i++) { | |
const li = document.createElement('li'); | |
li.className = 'splide__pagination__page'; | |
if (i === currentIndex) { | |
li.classList.add('is-active'); | |
} | |
li.setAttribute('role', 'button'); | |
li.setAttribute('aria-controls', `splide01-slide0${(i % totalSlides) + 1}`); | |
li.setAttribute('aria-label', `Go to slide ${(i % totalSlides) + 1}`); | |
li.addEventListener('click', () => splide.go(i)); | |
customPagination.appendChild(li); | |
} | |
}; | |
// Initialize pagination immediately | |
updatePagination(); | |
// Update splide pagination when moved | |
splide.on('moved', updatePagination); | |
return customPagination; | |
}; | |
const splide = new Splide('.splide', slider_options); | |
splide.on('mounted', function () { | |
const customPagination = createCustomPagination(splide); | |
splide.root.appendChild(customPagination); | |
}); | |
splide.mount(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment