Search code examples
jqueryloopsjquery-selectors

jQuery looping prev next


I found this bit of code whist searching for a basic slider and its near enough does what I want but I would like it to loop once it got to the last li, i.e if last li and next button is clicked loop to 1st and continue,

all help is appreciated and as always thanks in advance.

$('.udtalelse').addClass("passiv");
ctrlKunder(0);

$('#prev').click(function() {
    var index = getActive();
    if (index == 0) return;
    index--;
    ctrlKunder(index);
})
$('#next').click(function() {
    var index = getActive();
    if (index == $('.udtalelse').length - 1) return;
    index++;
    ctrlKunder(index);
})

function ctrlKunder(ele) {
    $('.udtalelse').removeClass("active").addClass("passiv");
    $('.udtalelse').eq(ele).removeClass("passiv").addClass("active");
}

function getActive() {
    var index;
    $('.udtalelse').each(function(i) {
        if ($(this).hasClass("active")) index = i;
    })
    return index;
}

<ul class="kunder">
    <li><span class="udtalelse">Indhold 1</span></li>
    <li><span class="udtalelse">Indhold 2</span></li>
    <li><span class="udtalelse">Indhold 3</span></li>
</ul>
<span class="kunderpagination">
    <a href="#" id="prev">« Previous</a> |
    <a href="#" id="next">Next »</a>
</span>

Solution

  • Your code can be greatly simplified like this:

    var all = $('.udtalelse').addClass("passiv");
    
    var i = -1;
    
    $('#prev').click(function() {
        ctrlKunder( i = !i ? all.length - 1 : --i );
    });
    $('#next').click(function() {
        ctrlKunder( i = ++i % all.length );
    }).click();
    
    function ctrlKunder(ele) {
        all.removeClass("active").addClass("passiv");
        all.eq(ele).removeClass("passiv").addClass("active");
    }
    

    Also more efficient because the .udtalelse elements are cached.

    Example: http://jsfiddle.net/3z9uc/


    EDIT: I forgot to update the answer with the revision that's in the fiddle. Fixed.