Reputation: 345
I have two instances of a bootstrap carousel on my page. I am using the code below to randomize the slides on page refresh for the first carousel.
//randomize the slider on page load
var $item = $('.carousel .item');
$item.eq(0).addClass('active');
var $numberofSlides = $('.item').length;
var $currentSlide = Math.floor((Math.random() * $numberofSlides));
$('.carousel-indicators li').each(function(){
var $slideValue = $(this).attr('data-slide-to');
if($currentSlide == $slideValue) {
$(this).addClass('active');
$item.eq($slideValue).addClass('active');
} else {
$(this).removeClass('active');
$item.eq($slideValue).removeClass('active');
}
});
However, since I have two carousels on the page. This code is causing one of them to not always load when refreshing the page. How can i only target one carousel using the code above? Can i add an ID to one of them and incorporate that somehow?
Upvotes: 0
Views: 299
Reputation: 10752
There are some simple changes you can make to your script to do this for EACH carousel:
//Do this for each .carousel
$(".carousel").each(function () {
//randomize the slider on page load
//Find .item within the current .carousel
var $item = $(this).find('.item');
$item.eq(0).addClass('active');
//Find .item within the current .carousel
var $numberofSlides = $(this).find('.item').length;
var $currentSlide = Math.floor((Math.random() * $numberofSlides));
//Find .carousel-indicators li within the current .carousel
$(this).find('.carousel-indicators li').each(function(){
var $slideValue = $(this).attr('data-slide-to');
if($currentSlide == $slideValue) {
$(this).addClass('active');
$item.eq($slideValue).addClass('active');
} else {
$(this).removeClass('active');
$item.eq($slideValue).removeClass('active');
}
});
});
(I've added some comments before the lines I have added and changed)
If you just want to do this for one carousel, then yes you should give it an ID so you can target it.
//randomize the slider on page load
var $item = $('#carouselid .item');
$item.eq(0).addClass('active');
var $numberofSlides = $('#carouselid .item').length;
var $currentSlide = Math.floor((Math.random() * $numberofSlides));
$('#carouselid .carousel-indicators li').each(function(){
var $slideValue = $(this).attr('data-slide-to');
if($currentSlide == $slideValue) {
$(this).addClass('active');
$item.eq($slideValue).addClass('active');
} else {
$(this).removeClass('active');
$item.eq($slideValue).removeClass('active');
}
});
In the three places I have typed carouselid
, you would replace this with the ID you assign the carousel.
Upvotes: 1