Disable Swiper Slider if only 1 slide

One of the options would be to conditionally add options, as below:

    let options = {};

    if ( $(".swiper-container .swiper-slide").length == 1 ) {
        options = {
            direction: 'horizontal',
            loop: false,
            autoplayDisableOnInteraction: false,

            keyboardControl: true,
            mousewheelControl: true,

            pagination: '.swiper-pagination',
            paginationClickable: true,
        }
    } else {
        options = {
            loop: false,
            autoplay: false,
        }
    }

    var swiper = new Swiper('.swiper-container', options);

Simply add a condition:

if ($('.swiper-container .swiper-slide').length > 1) {
  var swiper = new Swiper('.swiper-container', {
    // Optional parameters
    direction: 'horizontal',
    loop: false,
    //autoplay: 6500,
    autoplayDisableOnInteraction: false,

    keyboardControl: true,
    mousewheelControl: true,

    pagination: '.swiper-pagination',
    paginationClickable: true,

  });
}

There is an option in Swiper API that might be useful :

watchOverflow (boolean|false)
// When enabled Swiper will be disabled and hide navigation buttons on case there are not enough slides for sliding

I was looking for a way to do so too, but since I didn't find any “official” way to disable the swipe and hide the pagers, I decided to improvise a bit.

So in your script, you can add this after your Swiper variable:

JS:

if($(".slider .slide").length == 1) {
    $('.swiper-wrapper').addClass( "disabled" );
    $('.swiper-pagination').addClass( "disabled" );
}

This will add the class disabled to your wrapper and your pagination if there is only one slide in your slider. You can now add some CSS to bypass the Swiper effexts:

CSS:

.swiper-wrapper.disabled {
    transform: translate3d(0px, 0, 0) !important;
}
.swiper-pagination.disabled {
    display: none;
}

Note that this will only work when the loop is set to false (like in your case). If the loop is active, Swiper will add slide duplicates before and after your only slide, making a total of 3 identicals slides. You can then change the length == 1 to length == 3.

Hope this will help!

Tags:

Swiper