Media Queries in JavaScript - How to add Breakpoints and change "slidesPerView" in "Swiper" Slideshow

Viewed 22802

I'm using the this script:

    var swiper = new Swiper('.swiper', {
    slidesPerView: 3,
    spaceBetween: 50,
});

I would like the "slidesPerView: 3" to change to "slidesPerView: 2" when the screen width gets smaller then 1000px, and to "slidesPerView: 1" when screen width gets smaller then 500px.

As I know nothing of javascript syntax, please help me out by writing the full code.

Thanks you for your help.

EDIT:

Thank you all for your replies.

I still can't get it to work though...

Bellow is the complete script.

What am I doing wrong???

var swiper2 = new Swiper('.swiper2', {
    slidesPerView: 3,
    spaceBetween: 50,
    freeMode: true,
    loop: true,
    nextButton: '.swiper-button-next',
    prevButton: '.swiper-button-prev',
    breakpoints: {
        // when window width is <= 499px
        499: {
            slidesPerView: 1,
            spaceBetweenSlides: 30
        },
        // when window width is <= 999px
        999: {
            slidesPerView: 2,
            spaceBetweenSlides: 40
        }
    }
});
5 Answers

To update @faino's answer to be jQuery free

   let onresize = function (e) {
   let width = e.target.innerWidth;
        if (width < 500) {
            swiper_services.params.spaceBetween = 100;
        } else {
            swiper_services.params.spaceBetween = 50;
        }
    }
    window.addEventListener("resize", onresize);

You can follow this example.

breakpoints: {
  // when window width is >= 320px
  320: {
    slidesPerView: 2,
    spaceBetween: 20
  },
  // when window width is >= 480px
  480: {
    slidesPerView: 3,
    spaceBetween: 30
  },
  // when window width is >= 640px
  640: {
    slidesPerView: 4,
    spaceBetween: 40
  }
}
Related