I use multiple Swiper on my page. They should look the same, work the same. I use only one class (.swiper-container) for selector, because I don't know if I will use more instances in the future or not.
My site is responsive and I only want to use Swiper below a specific window width.
The problem: when the destory fired, only the SECOND instance destroyed, for the first one I get this error message:
Uncaught TypeError: Cannot read property 'destroy' of undefined
With only one instance everything is working.
My code:
var mySwiper = undefined;
function initSwiper() {
var screenWidth = $(window).width();
if(screenWidth < 992 && mySwiper == undefined) {
$('.swiper-container').each(function(){
mySwiper = new Swiper(this, {
scrollbar: $(this).find('.swiper-scrollbar')[0],
slidesPerView: 'auto',
effect: 'slide',
paginationClickable: true,
spaceBetween: 0,
freeMode: true
})
});
} else if (screenWidth > 991 && mySwiper != undefined) {
mySwiper.destroy();
mySwiper = undefined;
console.log("destroy");
jQuery('.swiper-wrapper').removeAttr('style');
jQuery('.swiper-slide').removeAttr('style');
}
}
//Swiper plugin initialization
initSwiper();
//Swiper plugin initialization on window resize
$(window).on('resize', function(){
initSwiper();
});
How can I force the destroy method to work on every instance?
It will not work like that, you should destroy them in the same logic using each method:
$('.swiper-container').each(function(){
this[0].swiper.destroy();
})
I can get swiper object using this[0].swiper, but how to make sure , the instances are destroyed. when i apply code above, it says "TypeError: T is null"
In case anyone else stumbles on this, removing the indexing worked for me:
$(".swiper-container").each(function(){
this.swiper.destroy(); // <-- 'this' not 'this[0]' worked for me
});
I'm using Swiper 4.1.5.
Most helpful comment
It will not work like that, you should destroy them in the same logic using each method: