I want to create an Image Slider using jQuery/JavaScript. I’m catching the images from the backend where I’ve created galleries in my own post type.
The problem: I want to use this slider more than once on the same site. If I use it twice, it runs through the first gallery AND it runs through the next(second) gallery with the same navigation buttons. Each slider should only work with its own navigation buttons.
My template looks like this:
echo '<section class="slider"><div class="cont">';
$galleryImages = get_post_gallery_images();
$gallaryLength = count( $galleryImages );
for( $i = 0; $i < $gallaryLength; $i++ ) {
echo "<div>";
echo "<img src="" . $galleryImages[ $i ] . "">";
echo "</div>";
}
echo '</div></section>';
I’m catching an array within the gallery images and show them in the frontend with an echo. On the bottom there are my buttons for the slider navigation.
Here’s my CSS for the slider:
.cont {
float: right;
position: relative;
text-align: center;
max-width: 200px;
background-color: black;
}
.cont div {
display: none;
width: 100%;
background-color: white;
}
.cont img {
width: 100%;
height: auto;
}
Here’s my jQuery/JavaScript file:
$( document ).ready( function() {
var currentIndex = 0;
var items = $( '.cont div' );
var itemAmt = items.length;
function slideItems() {
var item = items.eq( currentIndex );
items.hide();
item.css( 'display', 'inline-block' );
}
$( '.next' ).click( function() {
currentIndex += 1;
if( currentIndex > itemAmt - 1 ) {
currentIndex = 0;
}
for( var k = 0; k < items.length; k++ ) {
slideItems();
}
} );
$( '.prev' ).click( function () {
currentIndex -= 1;
if( currentIndex < 0 ) {
currentIndex = itemAmt - 1;
}
for( var x = 0; x < items.length; x++ ) {
slideItems();
}
} );
} );