destroy iDangerous Swiper if window is resized to a bigger resolution or call it when resized to a smaller resolution

fksr86 picture fksr86 · Feb 3, 2014 · Viewed 30.9k times · Source

i'm using iDangerous Swiper for my website in lower resolutions. here is how i'm calling it:

var resolution = 670;
if ($(window).width() < resolution) {
var mySwiper = $('.swiper-container').swiper({
    mode:'horizontal',
    loop: true,
    grabCursor: true,
    paginationClickable: true
});

so, when you access it in a desktop browser, the swiper will not be called. what i want to do is to "turn it on" if the user resizes the window to a size smaller than resolution or destroy it if the user accesses it in a small window size and then resizes it to bigger than resolution. i tried this, but it didn't work:

$(window).resize(function(){
    if ($(window).width() < resolution) {
        if(typeof(mySwiper) === "undefined" ) {
            var mySwiper = $('.swiper-container').swiper({
                mode:'horizontal',
                loop: true,
                grabCursor: true,
                paginationClickable: true
            });
        }
    } else {
        if (typeof(mySwiper) !== "undefined" ) {
            mySwiper.destroy();
        }
    }
});

two undesirable things happen:

  1. if the user is in a small resolution and resizes it to a resolution that still calls the swiper, it restarts the swiper.
  2. if the user is in a small resolution and resizes it to a bigger resolution, it is not destroyed.

i thing my problem is the typeof. i don't know much how variables work when they are called like this: $('.swiper-container').swiper().

how do i "uncall" swiper and how not call it if it was already called?

Answer

leone510es picture leone510es · Apr 29, 2015

My solution:

var mySwiper = undefined;
function initSwiper() {
    var screenWidth = $(window).width();
    if(screenWidth < 992 && mySwiper == undefined) {            
        mySwiper = new Swiper('.swiper-container', {            
            spaceBetween: 0,
            freeMode: true
        });
    } else if (screenWidth > 991 && mySwiper != undefined) {
        mySwiper.destroy();
        mySwiper = undefined;
        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();        
});

And it worx! :)