Last active
July 27, 2022 16:07
-
-
Save MSerj/ae74d2b99879194249070476385d205c to your computer and use it in GitHub Desktop.
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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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. :)