I need to go through elements with previuous and next buttons. Here is
HTML :
<ul>
<li><a href="#">Number 1 item</a></li>
<li><a href="#">Number 2 item</a></li>
<li><a href="#">Number 3 item</a></li>
<li><a href="#">Number 4 item</a></li>
</ul>
<input type="button" class="next" value=">" />
<input type="button" class="prev" value="<" />
JS :
(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);
}
})();
This plugin works perfect, Here is Fiddle
But I want to extend its functionality. I also want to enable clicking on list directly & remember its index.
What I mean is : Say, I reached till item no.3 while clicking on next button, & if I directly click on
<li><a href="#">Number 1 item</a></li> (item no:1) then I want to remember my this position as current index & when I click on next button, I should move to item no.2
same thing also goes with previous button.
How can I extend this functionality ?
Here is an updated version of your JSFiddle: http://jsfiddle.net/Rtmdj/15/
Also it doesn’t look like you really need the
lastIndexvariable, you can just remove theactiveclass, change theindex, then add theactiveclass to the newindex: