Add swiper slider to Powerful Rich Text from Finsweet
In a recent project I had to implement custom components inside a Rich text field. One of the components was a slider, with images from a Multi-image field from the CMS.
With the Finsweet Powerful Rich Text we pull the components from the page into the rich text field.
But the slider didn’t work, because on load swiper initializes the slider but then the Finsweet script moves it. The solution is obvious, we need to initialize the swiper slider when the component has finished moving.
We utilize the callback function from Finsweet to detect when the “richtext” has finished loading. At that point, the script moves the CMS collection with images into the richtext field, allowing us to begin initializing the swiper script. We then select the component by class and trigger the swiper slider script. We are now certain that the swiper has loaded after the richtext field has finished loading/moving components.
<script>
window.fsAttributes = window.fsAttributes || [];
window.fsAttributes.push([
"richtext",
(textInstances) => {
const swipperGallery = document.querySelector(".gallery-swiper .swiper-wrapper");
if (swipperGallery && swipperGallery.children.length > 0) {
const gallerySwiper = new Swiper(".gallery-swiper", {
speed: 400,
slidesPerView: 1,
loop: true,
spaceBetween: 0,
navigation: {
nextEl: ".gallery-nav-next",
prevEl: ".gallery-nav-prev",
},
});
} else {
console.log("No .gallery-swiper element found on the page.");
}
},
]);
</script>