Search code examples
javascriptjqueryajaxslick.jsdynamic-content

How can I reinitialize Slick carousel after appending new content via AJAX


I’m building a light fixture e-commerce site, HamptonLightings using the Slick library to display product images in a gallery. The gallery initializes correctly on page load, but when I append new content via AJAX, the newly added images don’t work with the Slick functionality. Here's the relevant code:

HTML:

<div id="gallery-container">
    <div class="gallery">
        <img src="image1.jpg" alt="Light Fixture 1">
        <img src="image2.jpg" alt="Light Fixture 2">
    </div>
</div>

JavaScript:

$(document).ready(function() {
    $('.gallery').slick(); // Initialize the gallery on page load
});

// AJAX to load more content
$.ajax({
    url: 'load-more.php',
    success: function(data) {
        $('#gallery-container').append(data);
        // The new content is added but the gallery isn’t reinitialized
    }
});

I tried calling .slick() after the content was appended, but it didn’t solve the problem. The new images appear as regular static images without the carousel functionality.

How can I ensure the gallery reinitializes properly after new content is appended?


Solution

  • Slick creates its own elements with its classes after init so append directly without knowing those elements won't work

    Instead you want to use slick api slickAdd to add slides, read more here

    $(document).ready(function () {
      $('.gallery').slick(); // Initialize the gallery on page load
    });
    
    // AJAX to load more content
    $.ajax({
      url: 'https://dog.ceo/api/breeds/image/random/3',
      success: function (data) {
        const images = data.message;
        for (const img of images) {
          $('.gallery').slick(
            'slickAdd',
            `
              <img
                src="${img}"
                alt="Light Fixture 1"
              />
          `
          );
        }
      },
    });
    

    Playground: https://stackblitz.com/edit/vitejs-vite-sgyizt?file=index.html,main.js