Home > OS >  ReInit Swiper after an AJAX Call Wordpress
ReInit Swiper after an AJAX Call Wordpress

Time:06-12

I'm posting here because after many hours of research and some headache I didn't find a solution to a problem with swiper JS in my website.

In my case, I have a WordPress website and I have an archive page with many listings each one with a slider (Swiper JS) that shows relevant images of the listing.

It works fine until I apply a filter to the page (Eg. select to show property with 4 beds) (so I think before I make an AJAX request).

The page reloads with AJAX and shows only relevant listings, the only problem is that the Swiper Slider doesn't work anymore, in fact, I cannot slide it.

By logic, I think I need to reinitialize Swiper after every AJAX call but as I'm not so good at AJAX I'm kind of wondering if anyone can point me into the right direction. Thank you very much.

My Swiper Code:

    jQuery(document).ready(function() {
const swiper = new Swiper('.swiper', {
  // Optional parameters
    direction: 'horizontal',
    effect: 'slide',
    speed: 150,
    loop: true,
    observer: true,

  // Navigation arrows
  navigation: {
    nextEl: '.swiper-button-next',
    prevEl: '.swiper-button-prev',
  },
    
      pagination: {
    el: '.swiper-pagination',
  },
});

});

CodePudding user response:

Why don't you use swiper lazy and param-lazy-loadPrevNext ?

CodePudding user response:

You're probably right. When the results container with the Swiper instances updates, Swiper needs to re-initialize the new result elements when they are attached to the DOM.

You should be able to re-use the same Swiper initializer. Just place it in a separate function. Then call that function on document load (as you are now) and when the AJAX results load, after the DOM is updated.

Example:

let swiper;

function initSwiper() {
  swiper = new Swiper('.swiper', {
    // Optional parameters
      direction: 'horizontal',
      effect: 'slide',
      speed: 150,
      loop: true,
      observer: true,

    // Navigation arrows
    navigation: {
      nextEl: '.swiper-button-next',
      prevEl: '.swiper-button-prev',
    },
      
        pagination: {
      el: '.swiper-pagination',
    },
  });
}

jQuery(document).ready(function() {
  initSwiper(); // <---------------
  
  // ...

  $.ajax({
    url: '/ajax-url/',
    dataType: "json",
    type: "Post",
    async: true,
    data: { },
    success: function (data) {
       $('#results').html(data.results_html);
       initSwiper(); // <---------------
    },
    error: function (xhr, exception) {
        // Error handling
    }
  }); 
});
  • Related