Mike Vierwind
Mike Vierwind

Reputation: 1520

Get the index of the ul in a carousel

I have a carousel with different lists. And i have a button next. When i click on the button, the carousel move 200 pixels to left. Than you can see the other images. But i have a problem with this custom made carousel.

I put the script on Jsfiddle: http://jsfiddle.net/kwdMP/2/

I would like to get the .index of the carousel. But the carousel is not working with .index. Who can help me, to fix this carousel? Thank you help guys!

This is my js code:

$(document).ready(function() {
    // Add width en height to the container - wrapper
    var ul = $('.list-thumbnails');
    var lengthUL = $('.list-thumbnails').length + 1;
    var containerWidth = $(ul).outerWidth() * lengthUL;

    $('.container-list-thumbnails').css({
        width: containerWidth
    });


    // Buttons for next and previous
    $('.container-thumbnails').append('<div class="buttons"><a href="#" title="Ga naar de vorige" class="previous">Vorige</a><a href="#" title="Ga naar de volgende" class="next">Volgende</a></div>')
    var buttonPrevious = $('.container-thumbnails .previous');
    var buttonNext = $('.container-thumbnails .next');

    buttonNext.click(function(e) {
        e.preventDefault();

        if (this.ignoreButtons) {
            return;
        }

        var section = $('.container-list-thumbnails');
        var sectionIndex = section.index();

        var x = -300 * (sectionIndex + 1);

        console.log(x);

        this.ignoreButtons = true;

        $('.container-list-thumbnails').animate({
            left: x,
        }, function() {
            this.ignoreButtons = false;
        }.bind(this));
    }.bind(this));
});
​

Upvotes: 0

Views: 151

Answers (1)

charlietfl
charlietfl

Reputation: 171669

I modified your slider to use one click handler for both buttons and to store sectionIndex in the parent element buttons using jQuery data('sectionIndex'). You will need to refine it a bit more so it can't go below zero or beyond the length of thumb lists

$('.buttons').data('sectionIndex', 0);
var section = $('.container-list-thumbnails');
$('.buttons a').click(function(e) {
    e.preventDefault();
    var isNext = $(this).is('.next');
    var $parent = $(this).parent();

    //if (this.ignoreButtons) {
        //return;
    //}
    var currIndex = $parent.data('sectionIndex');

    var sectionIndex = isNext ? currIndex + 1 : currIndex - 1;

    $parent.data('sectionIndex', sectionIndex);

    var x = -300 * sectionIndex;

    console.log(x);

    // this.ignoreButtons = true;
    $('.container-list-thumbnails').animate({
        left: x,
    }, function() {
        this.ignoreButtons = false;
    });
});

DEMO: http://jsfiddle.net/kwdMP/3/

Upvotes: 1

Related Questions