I want to set the data-interval for each slide of the carousel. Here on stackoverflow I found a JavaScript snippet for this case, but it doesn't work well. (Twitter Bootstrap Carousel slide duration) Each slide has its data-interval set inline in html with ms from 3000 to 7000 on five slides.
The real duration of the slides does not fit to my expectations and the code. Example: I set the interval to 3000 and the slide is shown around 7-8 seconds.
The js-file is written in the footer area of the site.
Here is the js code:
var t;
var start = $('#carouselExampleFade').find('.active').attr('data-interval');
t = setTimeout("$('#carouselExampleFade').carousel({interval: 1000});", start - 1000);
$('#carouselExampleFade').on('slid.bs.carousel', function() {
clearTimeout(t);
var duration = $(this).find('.active').attr('data-interval');
$('#carouselExampleFade').carousel('pause');
t = setTimeout("$('#carouselExampleFade').carousel();", duration - 1000);
})
$('.carousel-control-next').on('click', function() {
clearTimeout(t);
});
$('.carousel-control-prev').on('click', function() {
clearTimeout(t);
});
One part of the carousel:
<div class="row">
<div id="carouselExampleFade" class="carousel slide carousel-fade" data-ride="carousel">
<div class="carousel-inner">
<div class="carousel-item active" data-interval="2000">
<div class="carousel-caption d-none d-md-block text-left">
<h3>Willkommen im <br>Parkett!</h3>
</div>
<img class="d-block w-100" src="assets/img/animation/slide1.jpg" alt="First slide">
</div>
Note: I have changed the lines carousel-control-next and -prev. (It was -left and -right before).
Does anyone have a good idea so solve this problem?
I modified the approach outlined in Bass Jobsen's answer for Bootstrap 3.x so that it works for the Bootstrap 4 carousel. IMO, this is a much cleaner approach than hooking into the jQuery events.
It overrides the interval
set for the entire Carousel (this._config.interval
), with intervals set on the individual carousel items (data-interval="..."
):
$.fn.carousel.Constructor.prototype.cycle = function (event) {
if (!event) {
this._isPaused = false;
}
if (this._interval) {
clearInterval(this._interval)
this._interval = null;
}
if (this._config.interval && !this._isPaused) {
var $ele = $('.carousel-item-next');
var newInterval = $ele.data('interval') || this._config.interval;
this._interval = setInterval(
(document.visibilityState ? this.nextWhenVisible : this.next).bind(this),
newInterval
);
}
};
来源:https://stackoverflow.com/questions/50968181/bootstrap-4-carousel-individual-data-interval-on-each-slide