How can I increase-decrease the slidesPerView according to the window size of a Swiper slider?

1.8k Views Asked by At

My motive is when the display size will be small then the slidesPerView will be 1. I tried the below way, it's working when I refresh the page. But I want it will work automatically. When the window size will increase automatically the slidesPerView will be increased, again when the window size will decrease automatically the slidesPerView will be decreased. Where am I doing the mistake? give me a relevant solution...

swiper.js:

if(window.innerWidth>768){
  var swiper = new Swiper(".productSwiper", {
    slidesPerView: 3,
    spaceBetween: 30
  });
}else{
  var swiper = new Swiper(".productSwiper", {
    slidesPerView: 1
  });
}

index.html:

<div class="swiper productSwiper my-5">
        <div class="swiper-wrapper col-6 col-md-5 col-lg-3">

            <div class="swiper-slide card" style="width: 18rem;">

                <div class="d-flex justify-content-center">
                    <img src="static/1_medicine/2.jpg" class="card-img-top product_img d-block py-3" alt="product image 1">
                </div>
            
            </div>
        </div>
    </div>

Note: I used this slider: https://swiperjs.com/demos#slides-per-view

1

There are 1 best solutions below

0
On

You can define a swiper object in which you can apply all the settings you need and then initialize the swiper with it. An example from some old use case of mine is this;

const swiperObject = {
  slidesPerView: 'auto',
  spaceBetween: 50,

  scrollbar: {
    el: '.swiper-scrollbar',
    draggable: true,
    snapOnRelease: true,
  },

  breakpoints: {
    0: {
      navigation: {
        enabled: false,
      },
    },

    1024: {
      slidesPerView: 'auto',
      spaceBetween: 130,
      slidesPerGroupAuto: true,
      centerInsufficientSlides: true,

      navigation: {
        enabled: true,
        nextEl: '.swiper-button-next',
        prevEl: '.swiper-button-prev',
      },
    },
  },
};

Then, when it is time to initialize your swiper, you just pass the configuration object in;

new Swiper(".swiper", swiperObject);

You can use these breakpoints and more (just pass whatever values you need), and in each you can change/overwrite the values dictated by the previous ones.

So, in your case, you would use something like;

const swiperObject = {
  slidesPerView: 1,
  breakpoints: {
    769: {
       slidesPerView: 3,
       spaceBetween: 30,
    }
  }
}