Topic: Can you manually initialize a carousel/multi-carousel via JavaScript?

Winterrabe priority asked 3 years ago


I'm loading page content via an ajax call. In that new content is a multi-carousel but it does not work, because it can't get initialized on page load. The same problem also occors with the tooltips and I suppose that'll happen with every component that doesn't get initialized on page load.

I couldn't find any help in the API.


Dawid Wajszczuk staff answered 3 years ago


Hi. You can try this code from our API tab:

const myCarousel = document.querySelector('#myCarousel')
const carousel = new mdb.Carousel(myCarousel)

Here is something similar but it should prevent from double initialization:

document.querySelectorAll('[data-mdb-ride="carousel"]').forEach((el) => {
    let instance = Carousel.getInstance(el);
    if (!instance) {
      instance = new Carousel(el);
    }
  });

For tolltip try something like this:

document.querySelectorAll('[data-mdb-toggle="tooltip"]').forEach((el) => {
    let instance = Tooltip.getInstance(el);
    if (!instance) {
      instance = new Tooltip(el);
    }
  });

For multi-carousel try this:

document.querySelectorAll('.multi-carousel').forEach((el) => {
  new MultiCarousel(el).init();
});

Make sure to run this JS code after your page has loaded.


Winterrabe priority commented 3 years ago

This works, thank you!



Please insert min. 20 characters.

FREE CONSULTATION

Hire our experts to build a dedicated project. We'll analyze your business requirements, for free.

Status

Resolved

Specification of the issue

  • ForumUser: Priority
  • Premium support: Yes
  • Technology: MDB Standard
  • MDB Version: MDB5 3.9.0
  • Device: Desktop
  • Browser: All
  • OS: Windows 10
  • Provided sample code: No
  • Provided link: No