Raddy Website Design & Development Tutorials

Multiple Instances of SwiperJs on the same page with the same settings

By Raddy in JavaScript ·

Creating two or more Sliders instances using the SwiperJs library is a fairly straightforward task. You can literally give your sliders different class names and then initialise them with JavaScript – please see the example below.

UPDATE: Swiper container element now should have class “swiper" instead of “swiper-container“.

<div class="swiper-container-1 swiper">
   <div class="swiper-slide">Slide 1</div>
   <div class="swiper-slide">Slide 2</div>
   <div class="swiper-slide">Slide 3</div>
</div>
<div class="swiper-container-2 swiper">
   <div class="swiper-slide">Slide 1</div>
   <div class="swiper-slide">Slide 2</div>
   <div class="swiper-slide">Slide 3</div>
</div>
<script>
var swiper1 = new Swiper('.swiper-container-1', { /* Options */ })
var swiper2 = new Swiper('.swiper-container-2', { /* Options */ })
</script>

What if you needed to create two or more sliders with the same options?

The most apparent and lazy way would be to keep replicating the code above and add as many sliders as you need. If you have a few sliders as I did in my project than it might be a bad idea for obvious reasons.

I actually found some really good answers on this GitHub Issues page, but everything was done with jQuery which wasn’t an option for me. So I took the best of the answers and just converted everything to vanilla JavaScript. It was fairly easy to convert the jQuery code to vanilla JavaScript, but I wanted to share the code with you so you can save some time.

Solution

Create a few sliders with the same class name of “swiper-container” ( you can add as many as you want). Your code should look similar to mine:

<div class="swiper-container swiper">
   <div class="swiper-slide">Slide 1</div>
   <div class="swiper-slide">Slide 2</div>
   <div class="swiper-slide">Slide 3</div>
</div>
<div class="swiper-container swiper">
   <div class="swiper-slide">Slide 1</div>
   <div class="swiper-slide">Slide 2</div>
   <div class="swiper-slide">Slide 3</div>
</div>
<div class="swiper-container swiper">
   <div class="swiper-slide">Slide 1</div>
   <div class="swiper-slide">Slide 2</div>
   <div class="swiper-slide">Slide 3</div>
</div>

Now we need to select the class name “swiper-container”, loop thru each available element (example: div, section) on the page and then add a new unique class name to each to initialize unique Swipers.

const myCustomSlider = document.querySelectorAll('.swiper-container');

for( i=0; i< myCustomSlider.length; i++ ) {
  
  myCustomSlider[i].classList.add('swiper-container-' + i);

  var slider = new Swiper('.swiper-container-' + i, {
   /* Options */
  });

}

That’s it.

Other – Adding thumbs 

Quick thumbs example. (This will be formatted better as soon as I get the chance)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="css/main.css">

    <link rel="stylesheet" href="https://unpkg.com/swiper/swiper-bundle.css">
    <link rel="stylesheet" href="https://unpkg.com/swiper/swiper-bundle.min.css">

    <script src="https://unpkg.com/swiper/swiper-bundle.js"></script>
    <script src="https://unpkg.com/swiper/swiper-bundle.min.js"></script>

</head>
<body>
    <!-- Add your site or application content here -->
    <p>Hello world! This is HTML5 Boilerplate.</p>

    <style>

html,
    body {
      position: relative;
      height: 100%;
    }

    body {
      background: #000;
      font-family: Helvetica Neue, Helvetica, Arial, sans-serif;
      font-size: 14px;
      color: #000;
      margin: 0;
      padding: 0;
    }

    .swiper-container {
      width: 100%;
      height: 300px;
      margin-left: auto;
      margin-right: auto;
    }

    .swiper-slide {
      background-size: cover;
      background-position: center;
    }

    .gallery-top {
      height: 60%;
      width: 100%;
    }

    .gallery-thumbs {
      height: 20%;
      box-sizing: border-box;
      padding: 10px 0;
    }

    .gallery-thumbs .swiper-slide {
      width: 25%;
      height: 100%;
      opacity: 0.4;
    }

    .gallery-thumbs .swiper-slide-thumb-active {
      opacity: 1;
    }

    </style>

    <div class="swiper-container swiper gallery-top">
        <div class="swiper-wrapper">
        <div class="swiper-slide" style="background-image:url('https://u8x3b4g8.stackpathcdn.com/wp-content/uploads//2020/12/minimalistic-website-design-mockup_compressed.jpg')"></div>
        <div class="swiper-slide" style="background-image:url('https://u8x3b4g8.stackpathcdn.com/wp-content/uploads//2020/12/minimalistic-website-design-mockup_compressed.jpg')"></div>
        </div>
  
    </div>
    <div class="swiper-container swiper gallery-thumbs thumbs-class">
        <div class="swiper-wrapper">
        <div class="swiper-slide" style="background-image:url('https://u8x3b4g8.stackpathcdn.com/wp-content/uploads//2020/12/minimalistic-website-design-mockup_compressed.jpg')"></div>
        <div class="swiper-slide" style="background-image:url('https://u8x3b4g8.stackpathcdn.com/wp-content/uploads//2020/12/minimalistic-website-design-mockup_compressed.jpg')"></div>
        </div>
    </div>

    <div class="swiper-container swiper gallery-top">
        <div class="swiper-wrapper">
        <div class="swiper-slide" style="background-image:url('https://u8x3b4g8.stackpathcdn.com/wp-content/uploads//2020/11/swiper-js-multiple-instances_compressed.jpg')"></div>
        <div class="swiper-slide" style="background-image:url('https://u8x3b4g8.stackpathcdn.com/wp-content/uploads//2020/12/minimalistic-website-design-mockup_compressed.jpg')"></div>
        </div>
  
    </div>
    <div class="swiper-container swiper gallery-thumbs thumbs-class">
        <div class="swiper-wrapper">
        <div class="swiper-slide" style="background-image:url('https://u8x3b4g8.stackpathcdn.com/wp-content/uploads//2020/11/swiper-js-multiple-instances_compressed.jpg')"></div>
        <div class="swiper-slide" style="background-image:url('https://u8x3b4g8.stackpathcdn.com/wp-content/uploads//2020/12/minimalistic-website-design-mockup_compressed.jpg')"></div>
        </div>
    </div>


  <!-- Initialize Swiper -->
  <script>

        const myCustomSlider = document.querySelectorAll('.gallery-top');
        const myCustomGalleryThumbs = document.querySelectorAll('.thumbs-class');

        for (i = 0; i < myCustomSlider.length; i++) {

            myCustomSlider[i].classList.add('gallery-top-' + i);
            myCustomGalleryThumbs[i].classList.add('thumbs-class-' + i);

            var galleryThumbs = new Swiper('.thumbs-class-' + i , {
                spaceBetween: 10,
                slidesPerView: 4,
                freeMode: true,
                watchSlidesVisibility: true,
                watchSlidesProgress: true,
            });

            var galleryTop = new Swiper('.gallery-top-' + i, {
                spaceBetween: 10,
                thumbs: {
                    // el: '.thumbs-class',
                    // slidesPerView: 5,
                    swiper: galleryThumbs
                }
            }); 

        }

  </script>

</body>
</html>

Credit

All credit goes to the people on the GitHub Issues page. – thank you!

More Resources:

  1. Rome says:

    Hi Raddy, very nice solution, also can you help in finding a way if the multi sliders have thumbs attach to them in the options,
    how to connect them to their thumbnails?

    1. Raddy says:

      I added a quick example at the bottom of the page. I will have to format the post later as the HTML is a little bit too long.
      I hope this helps 🙂

      1. Nio says:

        How would you do this if you have custom buttons like next and previous?

        1. Raddy says:

          Are you having problems with the buttons or are you just asking how to add them? You can usually add them after the .swiper-wrapper div

  2. Kalle says:

    Thanks for posting this – very helpful! One thing: For me it looks like your thumb-slider example only works as long as you have more or the same number of .gallery-top items like .gallery-thumb items because you iterate only through the .gallery-top items and use the loop index for both types of galleries. If you had just 1 .gallery-top slider and 2 .gallery-thumb sliders only the first .gallery-thumb slider would be initiated.

    1. Raddy says:

      I think that you are right. I will have to have a look into it one day. On another note Swiper container element now should have class ‘swiper’ instead of ‘swiper-container’. I guess that’s another thing that needs updating 😅

      1. Kalle says:

        Thank you for responding! If you get the idea from your code-example (which helped me out 🙂 then you can figure out what to change yourself I guess 🙂

        About your notice about the ‘swiper’ classname: I read that by chance yesterday when checking the docs – you are right, from swiper version 7+ you need to change the wrapper classname.

        Thanks again!

  3. Kalle says:

    Thank you for responding! If you get the idea from your code-example (which helped me out 🙂 then you can figure out what to change yourself I guess 🙂

    About your notice about the ‘swiper’ classname: I read that by chance yesterday when checking the docs – you are right, from swiper version 7+ you need to change the wrapper classname.

    Thanks again!

  4. cy says:

    thank you so much!!!!!!! i solved my problem

  5. joao pedro says:

    Olá houve tudo bem?
    Houve alguma mudança nesse tipo de instância não consegui aplicar outro carroussel.

    1. Raddy says:

      Há uma nova versão do SwiperJs. O elemento container Swiper agora deve ter a classe “swiper” em vez de “swiper-container”. Eu preciso atualizar em algum momento. Desculpe pelo incômodo.

  6. Aleksandra says:

    Thank you so much!!!!!!!!!!!!

  7. Kenn says:

    Found it easiest to put the common options in an object and use the awesome spread operator …obj to pass them into the individual swiper instances. This way I can define common AND seperate options:

    const options = {

    speed: transitionSpeed,
    slidesPerView: 1,
    loop: true,
    etc.

    }

    let swiperOne = new Swiper(‘.swiper-1’, {

    …options,

    on: {
    init: function () {
    console.log(‘swiper-1 initialized’)
    },
    },

    })

    let swiperTwo = new Swiper(‘.swiper-2’, {

    …options,

    on: {
    init: function () {
    console.log(‘swiper-2 initialized’)
    },
    },
    })

    1. Raddy says:

      That is a pretty good alternative. Thank you for sharing and nice portfolio btw 🙂

  8. Sergei says:

    A bit updated version for Swiper 8.4.5 with Thumbs import and string interpolations:

    import Swiper, { Navigation, Thumbs } from “swiper”;

    const swiperThumbs = document.querySelectorAll(“.slider-thumbs”);
    const swiperThumbsNav = document.querySelectorAll(“.slider-thumbs-nav”);

    for (let i = 0; i < swiperThumbs.length; i += 1) {
    swiperThumbs[i].classList.add(`slider-thumbs-${i}`);
    swiperThumbsNav[i].classList.add(`slider-thumbs-nav-${i}`);

    const $galleryThumbs = new Swiper(`.slider-thumbs-nav-${i}`, {
    slidesPerView: 4,
    });

    const $gallerySwiper = new Swiper(`.slider-thumbs-${i}`, {
    modules: [Navigation, Thumbs],
    navigation: {
    nextEl: ".swiper-button-next",
    prevEl: ".swiper-button-prev",
    },
    thumbs: {
    swiper: $galleryThumbs,
    },
    });
    }

    1. Raddy says:

      Thank you for sharing this. I will make a note in the article so people can see your solution

  9. Romadoni says:

    Thank you so much, this solved my problem!!

    I have navigation button on my slider, so I added this to your code:

    const myCustomSlider = document.querySelectorAll(‘.slider-container’);
    const myCustomSliderNext = document.querySelectorAll(‘.slider-container-btn-next’);
    const myCustomSliderPrev = document.querySelectorAll(‘.slider-container-btn-prev’);

    for( i=0; i< myCustomSlider.length; i++ ) {

    myCustomSlider[i].classList.add('slider-container-' + i);
    myCustomSliderNext[i].classList.add('slider-container-btn-next-' + i);
    myCustomSliderPrev[i].classList.add('slider-container-btn-prev-' + i);

    var slider = new Swiper('.slider-container-' + i, {
    navigation: {
    nextEl: '.slider-container-btn-next-' + i,
    prevEl: '.slider-container-btn-prev-' + i,
    },
    });

    }

    It's work well on my page 🙂

    1. Raddy says:

      So many good examples! Thank you for sharing yours

  10. ALex says:

    Hello Rady,

    Thanks a lot on this one. Very very very useful. I needed to load more posts via Ajax and theses posts contain swiper sliders. With your solution all these sliders work like a charm.
    COngrats

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.