Ok, so I know I'm late for the party, but I had similar problems, and in the end I found a solution that works solidly.
History : Swiper should run on the desktop, but not on mobile devices (small screens) and should be able to change between them when resizing.
Requirements . In my example, I use jQuery, Swiper and Modernizr (for media queries, since the width of the window, etc. is unreliable).
Javascript
(function($, Modernizr) { 'use strict'; var state = { swiper: false, setOrGetDevice: function(device) { if (typeof(device) === 'undefined') { var mq = Modernizr.mq('only screen and (min-width: 768px)') ? 'desktop' : 'mobile'; device = mq; } return device; }, device: function() { return state.setOrGetDevice(); } }; var cache = { $window: $(window), $swiper: $('.swiper-container'), $swiperElements: $('.swiper-container, .swiper-wrapper, .swiper-slide') }; var swiper; var app = { init: function() { app.swiper(); }, swiper: function() { if(state.device() === 'desktop' && !state.swiper) { swiper = cache.$swiper.swiper({ parallax: false, initialSlide: 0, direction: 'horizontal', loop: true, autoplay: 3000, speed: 1000 }); state.swiper = true; } else if(state.device() === 'mobile' && state.swiper) { swiper.destroy(); swiper = undefined; cache.$swiperElements.removeAttr('style'); state.swiper = false; } } }; $(function() { app.init(); }); cache.$window.on('resize', function() { var mq = Modernizr.mq('only screen and (min-width: 768px)') ? 'desktop' : 'mobile'; state.setOrGetDevice(mq); app.init(); }); })(window.jQuery, window.Modernizr);
In addition to checking the โdeviceโ (in other words, the size of the mobile phone or desktop), it checks the flag set in state.swiper . Since this is a mobile approach, this flag is initially set to false .
I know that my explanation is short-lived, but it works 100% and has the advantage of not initializing Swiper at every stage of resizing, thanks to the flags.
HTML will be just the standard HTML that Swiper requires, so you should use it if you intend to use this solution.Hope this can help someone.
Thanks, Mikey.
Michael Giovanni Pumo
source share