Meules
Meules

Reputation: 1389

Swiper init script for mobile issue

I'm using Swiper 6.4.10 for a project. It's the first time I use Swiper. This website has multiple sliders on 1 page. So I decided to create some initializing script. I'm using data-attributes to create the slider settings. Every slider has different setups. One of those settings is to run the slider only on a mobile device and destroy it on desktop or tablet.

I've read a whole lot of posts here and in Google but I just can't get it to work.

It is about this part:

if(container){
  var initID = '#' + container;
  if(mobile){
   if(mobile_breakpoint.matches){
     var init = new Swiper(this, settings)
   } else if (!mobile_breakpoint.matches){
     var init = this.swiper.destroy();
   }
  }
  //var init = new Swiper(initID, settings)
}

When I use this code here above then all carousels are destroyed OR I get an error saying this.swiper.destroy is undefined. When I run my code like this:

if(container){
  var initID = '#' + container;
  var init = new Swiper(initID, settings)
}

Then all carousels just work. When I check for data attribute mobile and try to destroy the carousels then all stop working. I clearly miss something out.

Anybody have any idea what I do wrong? Any help greatly appreciated!

Upvotes: 0

Views: 2891

Answers (1)

Ezra Siton
Ezra Siton

Reputation: 7741

"Your mistake" under else if you forgot first to Initialize swiper instance .

This is why when you uncomment this block of code - the page is broken (error: this.swiper.destroy is undefined).

enter image description here

To destroy an instance you first should create this instance (destroy() is a Method of swiper instance).

const swiper = new Swiper('.swiper-container', {});
swiper.destroy();

Otherwise, your code is like writing:

bla_bla.destroy(); /* Uncaught ReferenceError: bla_bla is not defined */
  1. Create an instance (Missing in your code)
  2. Destroy
else if (!mobile_breakpoint.matches){
   var init = new Swiper(this, settings) /* missing in your code */
   init = this.swiper.destroy();
}

In general - your code is very long ==> next time create a Minimal, Reproducible Example (A lot of code not related to your issue/error).

Upvotes: 1

Related Questions