Friday, December 16, 2022
The Great Tit
Updated: 16. 12. 2022, Added: 16. 12. 2022

Swiper: Prevent single slide swipe with loop enabled

If you want to use Swiper slider and you have a situation where you want to disable sliding if there is only one slide, but use infinite loop when there is more than one slide, you cannot achieve it only with Swiper settings. It looks like you can with watchOverflow:true and loop:true... But those two does not work together. Once loop is true, watchOverflow stop working.

The solution is setting the loop:true; only when there is more than one slide.

Enable Swiper loop only if slider has more than one slides:

loop: jQuery(".product-slider_main .swiper-slide").length != 1,

Disable Swiper sliding and navigation if there is only one slide:

    watchOverflow: true,

Full example code of Swiper with custom prev/next buttons and with afterInit function to hide some elements if there is only one slide.

const productsPrimary = new Swiper('.product-slider_main', {
    hashNavigation: {
        watchState: true,
    },
    watchOverflow: true,
    loop: jQuery(".product-slider_main .swiper-slide").length != 1,
    slidesPerView: 1,
    spaceBetween: 10,
    navigation: {
        nextEl: '.product-slider_container-primary .swiper-button-next',
        prevEl: '.product-slider_container-primary .swiper-button-prev',
    },

    on: {
        afterInit: function() {
            if (this.slides.length == 1) {
                jQuery('.product-slider_nav').hide();
            }
        },
    },
});
Did I help you? Support me on Patreon!
Beep this article to your friends!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

linkedin facebook pinterest youtube rss twitter instagram facebook-blank rss-blank linkedin-blank pinterest youtube twitter instagram