Skip to content

Instantly share code, notes, and snippets.

@MSerj
Last active July 27, 2022 16:07
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save MSerj/ae74d2b99879194249070476385d205c to your computer and use it in GitHub Desktop.
Save MSerj/ae74d2b99879194249070476385d205c to your computer and use it in GitHub Desktop.
Multiple Instances of Swiper on Same page
if ($('.swiper-container').length > 0) { //some-slider-wrap-in
let swiperInstances = [];
$(".swiper-container").each(function(index, element){ //some-slider-wrap-in
const $this = $(this);
$this.addClass("instance-" + index); //instance need to be unique (ex: some-slider)
$this.parent().find(".swiper-pagination").addClass("pagination-" + index);
$this.parent().find(".swiper-button-prev").addClass("prev-" + index); //prev must be unique (ex: some-slider-prev)
$this.parent().find(".swiper-button-next").addClass("next-" + index); //next must be unique (ex: some-slider-next)
swiperInstances[index] = new Swiper(".instance-" + index, { //instance need to be unique (ex: some-slider)
// your settings ...
navigation: {
prevEl: ".prev-" + index, //prev must be unique (ex: some-slider-prev)
nextEl: ".next-" + index, //next must be unique (ex: some-slider-next)
},
pagination: {
el: '.pagination-' + index,
type: 'bullets',
clickable: true
},
});
});
// Now you can call the update on a specific instance in the "swiperInstances" object
// e.g.
swiperInstances[3].update();
//or all of them
setTimeout(function () {
for (const slider of swiperInstances) {
slider.update();
}
}, 50);
}
<div class="swiper-container">
<div class="swiper-wrapper">
<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-button-next"></div>
<div class="swiper-button-prev"></div>
</div>
@OneX
Copy link

OneX commented May 18, 2020

i think you don't need to pass selectors as pagination and navigation properties, you could just pass HTML elements.
This way you don't need to set classes and you don't need to update instances. Also you will not need to save instances.

Example:

var paginationEl = $this.find(".swiper-pagination")[ 0 ];

Then you can do:

pagination: { el: paginationEl, type: 'bullets', clickable: true }

Type parameter is also not needed, because you are using default option.

@OneX
Copy link

OneX commented May 18, 2020

Also, this is not need:

if ($('.swiper-container').length > 0) { //some-slider-wrap-in

First you are looping over elements you find here:

$(".swiper-container").each(function(index, element){

So, if there is no element nothing will be run.
Also, you can remove jquery and use plain js. You will have one problem less. :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment