I'm working in carousel sliders located in accordion tabs using bootstrap 5 and flickity. I have seven accordion tabs. Every accordion tab contain a carousel slider with autoplay videos. works great the autoplay video in first accordion carousel, but only works in the first accordion tab, i don't know how make it work on the rest accordion tabs, I was thinking to create an array of id but this idea didn't work, also tried to use document.querySelectAll() with all ids of the tabs but this didn't work either. The script to make the first tab accordion work with carousel is this.
(function(){
const target1 = document.getElementById('flickity1');
const videos = target1.getElementsByTagName('video');
const videosLength = videos.length;
//start the first video in the carousel
videos[0].play();
const flickity = new Flickity(target1,{
wrapAround:false,
autoPlay:false,
on: {
ready: function() {
console.log('Flickity ready');
videos[0].play();
}
}
});
flickity.on('settle',changeSlide);
function changeSlide(index) {
for(let i = 0;i < videosLength; i++){
videos[i].currentTime = 0;
videos[index].play();
}
}
}());
One solution that I found is repeating for the differents ids the same script but changing the name variable for example const target2 = document.getElementById('flickity2'); and so on... But this not the correct way to do this. I thinks that an array can work. something like this:
var ids = ['flickity0', 'flickity1'];
function accorcarousel() {
for (var i = 0; i<ids.length; i++){
document.getElementById(ids[i]) = target1;}}
I was reading the bootstrap docs that i can trigger the function via data attributes. data-bs-toggle="collapse" and a data-bs-target to the element to automatically assign control of one or more collapsible elements. Any idea is very appreciate.