Adriano Varlotta
Adriano Varlotta

Reputation: 525

Swiper Slider - Only show on mobile

Im working on code that init/resize Swiper Slider if screen is smaller than 768px and destoy if is larger.

This code is working but when the browser starts over than width:768px appear a error message:

Uncaught TypeError: swiper.destroy is not a function at swiperMode (home.js:1:817) at home.js:1:878

    /* Swiper Slider Cards Home - Show only on mobile */
    var swiper = Swiper;
    var init = false;
    function swiperMode() {
      let mobile = window.matchMedia("(min-width: 0px) and (max-width: 768px)");

      if (mobile.matches) {
        if (!init) {
          init = true;
          swiper = new Swiper(".slider-cards-js", {
            direction: "horizontal",
            slidesPerView: "auto",
            centeredSlides: true,
            spaceBetween: 32,
            pagination: {
              el: ".swiper-pagination",
              clickable: true,
            },
          });
        }
      } else {
        swiper.destroy();
        init = false;
      }
    }

    window.addEventListener("load", function () {
      swiperMode();
    });

    window.addEventListener("resize", function () {
      swiperMode();
    });

Upvotes: 5

Views: 21113

Answers (1)

Adriano Varlotta
Adriano Varlotta

Reputation: 525

Solution:

var init = false;
var swiper;
function swiperCard() {
  if (window.innerWidth <= 768) {
    if (!init) {
      init = true;
      swiper = new Swiper(".slider-cards-js", {
        direction: "horizontal",
        slidesPerView: "auto",
        centeredSlides: true,
        spaceBetween: 32,
        pagination: {
          el: ".swiper-pagination",
          clickable: true,
        },
      });
    }
  } else if (init) {
    swiper.destroy();
    init = false;
  }
}
swiperCard();
window.addEventListener("resize", swiperCard);

Change .slider-cards-js to your swiper main div.

Upvotes: 17

Related Questions