Last active
July 27, 2022 16:07
Multiple Instances of Swiper on Same page
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> |
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
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.