user141621
user141621

Reputation:

Prev Next with jquery

I need to go through elements with previuous and next buttons but am having trouble working out how to do it. Can you help. The prev/next should also loop continuously ie. when you get to the last item it goes to the first and when you get to the first item through prev the next click will take you to the last item and so forth.

<ul>
<li>Number 1 item</li>
<li>Number 2 item</li>
<li>Number 3 item</li>
<li>Number 4 item</li>
</ul>

Many thanks, C

Upvotes: 0

Views: 1054

Answers (2)

Josiah Ruddell
Josiah Ruddell

Reputation: 29831

This should get you started: fiddle

Html:

<ul>
  <li>Number 1 item</li>
  <li>Number 2 item</li>
  <li>Number 3 item</li>
  <li>Number 4 item</li>
</ul>
<input type="button" class="next" value=">" />
<input type="button" class="prev" value="<" />

Javascript:

(function(){
    var $lis = $('ul li');
    var index = 0, lastIndex = 0;

    start(); // activate first, add event listeners to buttons

    function next(){
        lastIndex = index;
        if(++index == $lis.length) index = 0; // if next is out of bounds go to first
        $lis.eq(index).addClass('active');
        $lis.eq(lastIndex).removeClass('active');
    };

    function prev(){
        lastIndex = index;
        if(--index < 0) index = ($lis.length - 1); // if prev is less than first to to last
        $lis.eq(index).addClass('active');
        $lis.eq(lastIndex).removeClass('active');
    };
    function start(){
        $lis.eq(0).addClass('active');
        $('.next').click(next);
        $('.prev').click(prev);
    }
})();

Upvotes: 1

Zevan
Zevan

Reputation: 10235

Here is another example that you can use - posted on jsFiddle

Upvotes: 0

Related Questions