splide
splide copied to clipboard
Autoplay not working when slides is less than perPage AND in loop mode
trafficstars
Checks
- [x] Not a duplicate.
- [x] Not a question, feature request, or anything other than a bug report directly related to Splide. Use Discussions for these topics: https://github.com/Splidejs/splide/discussions
Version
v4.1.4
Description
When in loop mode, and if the slides are equal to or less than perPage, the autoplay doesn't seem to work. For example, I have 2 slides with this config:
{
"type": "loop",
"autoplay": true,
"mediaQuery": "min",
"perPage": 1,
"breakpoints": {
"1024": {
"perPage": 2
}
}
}
So on >1024px viewport, it doesn't work.
Even trying to force play() doesn't work. I've seen similar questions where answers were just "Why do you want to autoplay if you don't have enough slides?" - but this is with loop. So there is definitely enough slides (the user can manually drag through the duplicates).
Reproduction Link
No response
Steps to Reproduce
- Use the above options.
Expected Behaviour
The autoplay works with the above options.
For anyone with this same issue, I've created this extension to get around this issue (also any feedback from the Splide authors would be great):
/**
* A custom extension for fixing an autoplay + loop issue.
* - When `perPage` is >= the slide count, autoplay won't start.
* - Splide seems to base this on the original slides, not clones (such as those created with loop mode).
* - So this adds our own "clones" to the original slide list until there are enough.
* @param {Object} Splide - The Splide context.
* @returns {Object}
*/
function AutoplayLoopFix(Splide) {
/**
* Clones slides until there are more than `perPage`.
* @param {Object} options - The current Splide options.
*/
function autoplayLoopFix(options) {
if (!options.autoplay || !(options.type === 'loop')) return;
const slides = Splide.Components.Slides.get(true);
const clones = [];
while (slides.length + clones.length <= options.perPage) {
clones.push(...slides.map(({ slide }) => slide.innerHTML));
}
Splide.Components.Slides.add(clones);
}
return {
mount() {
autoplayLoopFix(Splide.options);
/**
* Handle when the options update, like at a breakpoint.
*/
Splide.on('updated', autoplayLoopFix);
},
};
}