Search code examples
javascriptajaxbootstrap-5bootstrap-carousel

Reinitialize bootstrap carousel after Ajax call


I'm setting up the bootstrap carousel after the Ajax call to the DOM. So, I'm appending elements and classes after the page load as below.

async function ajaxCall() {
    let data = await fetch('ApiLink');
    let jsonData = await data.json();

    let carousel = document.createElement('section');
    let inner = document.createElement('div');
    carousel.id = 'slider';
    carousel.className = 'carousel carousel-dark slide';
    carousel.setAttribute('data-bs-ride', 'carousel');
    inner.className = 'carousel-inner';

    jsonData.data.forEach(data => {
        let item = document.createElement('div');
        let avatar = document.createElement('img');
        item.className = 'carousel-item';
        avatar.src = data.avatar;
        item.appendChild(avatar);
        inner.appendChild(item);
    });

    inner.querySelector('.carousel-item').classList.add('active');
    carousel.appendChild(inner);
    document.body.appendChild(carousel);
}

However, the carousel doesn't work.

I guess, I need to reinitialize the carousel after creating and appending the HTML elements. So, my question is:

How can I reinitialize the bootstrap carousel after the Ajax call without using jQuery?


Solution

  • Based on the documentation, you can make a carousel instance with the carousel constructor after creating your slider element as below:

    let carousel = new bootstrap.Carousel(slider, {});
    

    Further, take a look at the carousel methods. So, you can find the getOrCreateInstance which returns a carousel instance associated with a DOM element, or create a new one in case it wasn't initialized as below:

    bootstrap.Carousel.getOrCreateInstance(slider, {});
    

    FYI, you can pass any attributes to your slider as the second parameter.

    Also, the data-bs-ride attribute reads once on page load. So, you don't need to set it up in your Ajax call.