1

Not sure if this is the right place to ask my question, but I hope someone can help me.

I am using Sprig to re-render some cards based on some parameters (with a dropdown filter). These cards also use Swiper to create a nice slider. The problem is, when I filter and sprig re-renders the cards, the Swiper doesn't work anymore.

I tried to reinitialise the Swiper using htmx, but that doesn't seem to work.

<script>
  htmx.on('htmx:afterSwap', function(event) {
      awardSwiper.init()
   });
</script>

Does someone have some knowledge about this topic?

Thanks in regards!

1

Do you get any error messages in the console? This will tell you what's going wrong with Swiper internally.

Educated guess: Swiper probably stores some state with references to existing DOM nodes / cards. When sprig re-renders an element, it completely replaces the subtree in its scope, so this will invalidate the state stored in the Swiper instance.

You could probably solve this by destroying the previous Swiper instance (before the old DOM nodes are gone using the htmx:beforeSwap event) – see swiper.destroy(). And then after the swap, initialize a new Swiper instance from scratch the same way you do on initial page load. This will ensure Swiper loads correctly and everything works after re-rendering.

2
  • 1
    Thank you so much for helping me. Because of your answer it's fixed now! – Maurits Brouwer Jul 20 at 12:08
  • @MauritsBrouwer Glad I could help :) – MoritzLost Jul 20 at 12:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.