Bootstrap Carousel Using Random Images
I have a working carousel, but I would like the images to display in a random order?
I have a working carousel, but I would like the images to display in a random order?
You can do this using php if that is available to you. Assign your images to an array:
<?php
$images = array('lion.jpg', 'elephant.jpg' , 'squirrel.jpg', 'penguin.jpg', 'fox.jpg', 'frog.jpg');
// randomise the images using the shuffle function
shuffle($images);
?>
Then just loop through the images using the php 'for' loop and assign them to the Bootstrap carousel <div>
| <?php for($x = 0; $x <= 5; $x++) { ?> |
<div class="item <?php if($x == 0) { echo 'active'; } ?>">
| <img src="images/<?php echo $images[$x]; ?>" alt=""> | |
| </div> |
<?php } ?>
For anyone that doesnt use php you can also do this using jQuery:
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
$(document).ready(function(){
var images = ['lion.jpg', 'elephant.jpg' , 'squirrel.jpg', 'penguin.jpg', 'fox.jpg', 'frog.jpg'];
// shuffle images function
function shuffle(o){
for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o = o
return o;
}
// shuffle images
shuffle(images);
var x = 0;
while (x < 5) {
if (x > 0) {
var active = "";
}
else {
var active = " active";
}
$('.carousel-inner').append('<div class="item' + active + '"><img src="images/' + images
x++;
}
});
</script>
Already have an account? Login
Enter your E-mail address. We'll send you an e-mail with instructions to reset your password.