I'm kind of stumped. :) I'm new to Javascript, but have typically found lots of great help on the net when I Googled. The best help I could come up with this time was here, but the docs said it was better to post a new question than sidetrack the original post. So, here's my question: I'm using Bootstrap3's carousel I'm trying to pick a random starting image, and then continue with random images after that. I've figured out how to pick the first slide, but can't figure out how to pick the next slide. As it stands, it just continues to cycle through the show.
<div id="myCarousel" class="carousel slide" data-wrap="true" data-ride="carousel">
<!-- Slider Content (Wrapper for slides )-->
<div class="carousel-inner">
<div class="item">
<img src="images/slides/AAA.jpg" alt="AAA" />
</div>
<div class="item">
<img src="images/slides/BBB.jpg" alt="BBB" />
</div>
<div class="item">
<img src="images/slides/CCC.jpg" alt="CCC" />
</div>
<div class="item">
<img src="images/slides/DDD.jpg" alt="DDD" />
</div>
<div class="active item">
<img src="images/slides/EEE.jpg" alt="EEE" />
</div>
</div>
</div>
<script src="js/bootstrap.js"></script>
<script type='text/javascript'>
$(document).ready(function() {
/* Pick a random number and apply it to the first slide in the slideshow item */
$('.item').eq(Math.floor((Math.random() * $('.item').length))).addClass("active");
/* Pick random next slide */
$('#myCarousel').carousel(Math.floor((Math.random() * $('.item').length))));
});
</script>
Thanks. :)
jQuery
var currentSlide;
var rand;
$(document).ready(function() {
currentSlide = Math.floor((Math.random() * $('.item').length));
rand = currentSlide;
$('#myCarousel').carousel(currentSlide);
$('#myCarousel').fadeIn(1000);
setInterval(function(){
while(rand == currentSlide){
rand = Math.floor((Math.random() * $('.item').length));
}
currentSlide = rand;
$('#myCarousel').carousel(rand);
},3000);
});
CSS
#myCarousel {
display:none;
}
HTML
<div id="myCarousel" class="carousel slide" data-wrap="true">
....
Well here is an example of how I would do it... I also accounted for the possibility of it randomly changing to the same slide.
http://www.bootply.com/99052
You will notice however that depending on which slide is chosen the carousel will transition either left or right.. The bootstrap carousel was designed to display linear images. There may be a way to manipulate the order of the items using jQuery so that it always slides the same way. If you are looking for that it could be done but would take some work and would probably be best handled in another question.
Als you can remove the data-ride="carousel"
from you html and that will make it so the carousel will initialize without cycling.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With