Search code examples
swiper.js

Disable Swiper Slider if only 1 slide


I'm using swiper slider on a site and would like to have it disabled if there is only one slide.

Currently with only one slide the pagination appears and you can click that or swipe. Ideally there shouldn't be any interaction if there is only one slide.

My current js is:

  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,

  });

Solution

  • 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!