I'm trying to create a Twitter Bootstrap modal that has one of their carousels within it. I could have a separate carousel element for every instance needed on the page, but I thought it better to have a single instance and pass it what to display when needed.
I'm doing this via a data attribute on a div, which when pressed will trigger the carousel modal.
<div class="carousel trigger" data-toggle="modal"
data-target="#timeline--modal--carousel" data-src='[
"https://picsum.photos/id/100/2100/2000",
"https://picsum.photos/id/1000/2100/2000",
"https://picsum.photos/id/1011/2100/2000"
]'> TRIGGER
</div>
I can get that to work. However, I came across an issue when the trigger was pressed for a second time (as if you closed the modal & then wanted to open it again or trigger a different carousel of images to show. It would add the second instance to the first, so you would get either duplicated images or the second set appended to the first and so on.
So I've been trying to get the modal to reset the content after it is closed by doing something like this...
let carouselSrc = [],
carouselSrcArray = carouselSrc;
$j('.carousel.trigger').on('click touchend', function () {
$j(this).addClass('active');
let carouselSrc = $j(this).data('src'),
carouselSrcArray = carouselSrc, // Pass it across
i = 0, // for iterations
active = ''; // for active class on first
console.log('Clicked carouselSrc = ' + carouselSrc);
console.log('Clicked carouselSrc.length = ' + carouselSrc.length);
$j('#timeline--modal--carousel').on('shown.bs.modal', function (e) {
// console.log(carouselSrc);
// console.log(carouselSrc.length);
// For each on the array
carouselSrcArray.forEach(function (item, index, array) {
// If this is the first one, set it to active
if (i == 0) {
active = 'active';
}
// Create the indicators
$j('#timeline--modal--carousel').find(
'.carousel-indicators')
.append(
'<li data-target="#timeline--carousel" data-slide-to="' +
i +
'" class="' + active + '"></li>');
// Create the images for the carousel
$j('#timeline--modal--carousel').find('.carousel-inner')
.append(
'<div class="carousel-item ' + active +
'"><img src="' +
item +
'" class="d-block w-100"></div>');
// set vars for next in the loop
i++;
active = '';
// I tried resetting the array, but this leads to blank carousel the next time it is called ¯\_(ツ)_/¯
// if (i == carouselSrc.length) {
// carouselSrc.splice(0, carouselSrc.length);
// carouselSrcArray.splice(0, carouselSrcArray.length);
// }
});
});
});
$j('#timeline--modal--carousel').on('hide.bs.modal', function (e) {
carousel-indicators li, .carousel-inner .carousel-item', this).remove(); // remove content
});
So I remove the HTML of the images and the indicators, but that didn't work. I've also tried resetting the array after it was called but doing this means the next time I call the modal carousel, it's empty.
So you can see what I mean I have set up a demo here https://codepen.io/ashbryant/pen/KKzObGe
Can anyone please help me?
Thanks