2

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();
        }
    } );
} );
3

My approach (take it as such) would be simply generating a unique ID which will differentiate each slider.
That's anyway a good practice when the same functionality can potentially be displayed multiple times on the same page.

First, find a way to generate an incremental $id to use in your template. Maybe an instanciation ID... This really depends on the way you've implemented your solution, I can't say more from the supplied info.

Then, in your template, add a section's id attribute:

echo '<section id="slider_' . $id . '" class="slider">';

Then, in your JS script:

Get the parent <section>'s id attribute of the hovered button, let's call it $section_id.

Then change your selector to:

$("#$section_id .next").click(function () {});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.