javascriptswiper.jsswup

How to restart Swiper js with active Swup?


There is the following script on the page that changes the content without reloading the page:

var swup = new Swup({
        animationSelector: '[class*="swup-transition-"]'
      });

On the main page there is a slider with a connected swiper. At the initial loading, the slider works, everything is fine. But as soon as I go to another page and come back the slider does not work, the buttons are not active... The swiper initialization script itself looks like this:

import Swiper from 'https://cdn.jsdelivr.net/npm/swiper@11.1.1/swiper-bundle.min.mjs'
      var swiper = new Swiper(".mySwiper", {
        autoplay: {
          delay: 5000,
        },
        loop: true,
        scrollbar: {
          el: ".swiper-scrollbar",  
          hide: true,
        },
      });

I tried to do it through api methods .UpdateProgress(), .update Size(), .update Slides(), .update(). Nothing happens...


Solution

  • Swup will navigate to new pages without a full reload — that means your Swiper init code will only ever run once on initial load. You need a way of re-running your init code after each navigation triggered by swup. As mentioned by @Invulner, custom hooks is the way to go here. However, the animation hooks don't always get called, e.g. on history visits or other non-animated visits.

    For code to reliably run after each navigation, it's best to use the page:view hook.

    import Swiper from 'https://cdn.jsdelivr.net/npm/swiper@11.1.1/swiper-bundle.min.mjs'
    
    function initSwiper() {
      const swiper = new Swiper('.mySwiper', {
        autoplay: {
          delay: 5000
        },
        loop: true,
        scrollbar: {
          el: '.swiper-scrollbar',  
          hide: true
        }
      })
    }
    
    cons swup = new Swup({
      animationSelector: '[class*="swup-transition-"]'
    })
    
    swup.hooks.on('page:view', () => initSwiper())
    
    initSwiper()