Lykos Lykos - 1 month ago 13
jQuery Question

Bootstrap - set different interval on each carousel item

Hi I'm having a carousel on Bootstrap and what I'd like to do is to set each item to a different interval, so basically the first item could have a duration of 10 sec, the 2nd 5 sec the 3rd 3sec etc etc ..

Therefore I decided to use a data attribute like this

<!-- Carousel -->
<div id="myCarousel" class="carousel slide" data-ride="carousel">

<!-- Indicators -->
<ol class="carousel-indicators">
<li data-target="#myCarousel" data-slide-to="0" class="active"></li>
<li data-target="#myCarousel" data-slide-to="1" ></li>
<li data-target="#myCarousel" data-slide-to="2" ></li>
</ol>

<!-- Wrapper for slides -->
<div class="carousel-inner">
<div class="item active" data-interval="8000">
<img src="carousel/icon_1.jpg" />
<div class="carousel-caption">
<h2 class="carousel-title">Welcome to My Site</h2>
<p class="carousel-text">Lorem ipsum dolor sit amet</p>
<p class="carousel-text">Lorem ipsum dolor sit amet</p>
</div>
</div><!-- /.item -->


<div class="item" data-interval="4000">
<img src="carousel/icon_2.jpg" />
<div class="carousel-caption">Lorem ipsum dolor sit amet</div>
</div><!-- /.item -->


<div class="item" data-interval="4000">
<img src="carousel/icon_3.jpg" />
<div class="carousel-caption">Lorem ipsum dolor sit amet</div>
</div><!-- /.item -->


</div><!-- /.carousel-inner -->

</div> <!-- Carousel -->

<script type="text/javascript">
$(document).ready(function () {
// more scripts here ...

// the main part
var t;
var start = $('#myCarousel').find('.active').attr('data-interval');
t = setTimeout("$('#myCarousel').carousel({interval: 1000});", start-1000);

$('#myCarousel').on('slid.bs.carousel', function () {
clearTimeout(t);
var duration = $(this).find('.active').attr('data-interval');

$('#myCarousel').carousel('pause');
t = setTimeout("$('#myCarousel').carousel();", duration-1000);
});
});
</script>


in case I might need to change a time interval in future. The problem is that all slides apply the same interval (about 2 or 1 sec). How can I fix this?

Answer

The approach you have followed is correct but you need to capture sliding event of twitter-bootstrap carousel to make it work as below:

DEMO

var t;
var start = $('#myCarousel').find('.active').attr('data-interval');
t = setTimeout(function(){
         $('#myCarousel').carousel({interval: 1000})
    }, start-1000);

$('#myCarousel').on('slid.bs.carousel', function () {   
     clearTimeout(t);  
     var duration = $(this).find('.active').attr('data-interval');

     $('#myCarousel').carousel('pause');
     t = setTimeout("$('#myCarousel').carousel();", duration-1000);
})

$('.carousel-control.right').on('click', function(){
    clearTimeout(t);   
});

$('.carousel-control.left').on('click', function(){
    clearTimeout(t);   
});

For more detailed version visit Original Answer

Comments