Skip to content
Advertisement

Flickity & Swup – destroying flickity

I am trying to destroy and re-load my Flickity slideshow while using Swup for page transitions, and I am not having much luck. This is my js file:

JavaScript

But when I try this I get the error flkty is not defined. Can anyone give me any pointers on this?

Advertisement

Answer

Variable scoping

As mentioned by CBroe, your var is undefined because of where you define it. It is defined in a function, but should be defined at the “top level”.

JavaScript

Furthermore, if you are using any kind of module bundler, sometimes it can still get lost, so you could consider doing something like:

JavaScript

And always reference it in that way, i.e.

JavaScript

Only destroying instances that exist

That’s it for your variable definition. The next potential error is that you only init flkty when the query selector matches:

JavaScript

But you destroy it every willReplaceContent, so really you could do with a check on “is it inited, this page load?”. In this instance, you can do a check like so:

JavaScript

Neatening up your code

This can all get a bit out of hand, so what we started doing was creating modules. Here is a skeleton of a carousel module we use:

JavaScript

Then, in our main.js we do something like you have:

JavaScript

All of the modules have setup and unload functions that won’t break if the elements don’t exist, so we can call all of them on each page load and unload.

I love swup but also have personal experience in the nightmare of initing and destroying things so let me know if you need any further help.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement