Skip to content
Advertisement

How to init hidden swiper on page load?

I have a swiper positioned inside a tab on a wordpress site, thus it is not initiated on page load, so the navigation function does not work. You can see it here by clicking on the “görüşler” tab.

I did a research and I found out that it’s a common issue and it can be initiated with some custom jquery. I’ve added the following code as an external javascript, however I can’t get it to work. If anyone can help me out, I’d appreciate it as it is driving me insane. Many thanks in advance.

jQuery(document).on("pageinit", function($) {
  var swiper = new Swiper('.swiper-container', {
    parallax: true,
    autoHeight: true,
    setWrapperSize: true,
    slidesPerView: 1,
    spaceBetween: 30,
    centeredSlides: true,
    autoplay: {
      delay: 2500,
      disableOnInteraction: false,
    },
    navigation: {
      nextEl: '.swiper-button-next',
      prevEl: '.swiper-button-prev',
    },
    observer: true,
    observeParents: true,
  });
  swiper.init();
});

Advertisement

Answer

I ended up using this code, posting it here in case anyone needs it.

// Call On Page Load

var observer = new IntersectionObserver( (entries, observer) => {
    entries.forEach(entry => {
        if (entry.intersectionRatio > 0) {
            window.dispatchEvent(new Event('resize')); 
            observer.unobserve(entry.target);
            if (entry.target.swiper) {
                entry.target.swiper.slideTo(0);
            }
        };
    });
}, null);
  
observer.observe(document.querySelector('#yepss .swiper-container'));
Advertisement