Aleš Sýkora / December 16, 2022 / 1 comments

Swiper: Prevent single slide swipe with loop enabled

Post summary: 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…

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();
            }
        },
    },
});

Fuel my passion for writing with a beer🍺

Your support not only makes me drunk but also greatly motivates me to continue creating content that helps. Cheers to more discoveries and shared success. 🍻

1 comments

  • I’m trying to resolve a scenario where the slide slides halfway to the next slide when the user’s focus is on the CTA button inside the slide and then the user presses the Tab key. Oddly, once all three slides have looped and it returns to the first slide, the problem disappears. Is this a known issue for anyone else with a possible workaround?

Share Your Thoughts