Sam Skirrow
Sam Skirrow

Reputation: 3697

jQuery add class to next list item one at a time AND loop back to beginning

I have created a jQuery circular carousel that loops through x amounts of slides. I have been adding pagination to this slider. Each point is a list item that relates to each slide. When slide number one is visible, li number one has the class current. When you click next, the class is removed from li number one and added to li number 2.

The issue I have is that once I have gone through all of the list items, I want the class "current" to be added back to the first list item - the oppsite also needs to happen when the previous button is clicked.

Here is my jQuery code for the pagination:

window.next = function() {
var li = jQuery("li.current");
if (li.length)
    li.removeClass("current").next().addClass("current");
else
    jQuery("li").first().addClass("current");
}
window.prev = function() {
var li = jQuery("li.current");
if (li.length)
    li.removeClass("current").prev().addClass("current");
else
    jQuery("li").last().addClass("current");
}
}

and my html markup:

<ul>
<li class="current"></li>
<li></li>
<li></li>
</ul>

Can anyone tell me how I get this to loop around? You can see my work here http://www.samskirrow.com/projects/carousel

Upvotes: 2

Views: 2038

Answers (2)

James Montagne
James Montagne

Reputation: 78650

You can simply check if next exists, and if it doesn't, you must be at the end, so pick the first:

if (li.length){

    var $next = li.next();

    if($next.length == 0) $next = $("li").first();

    li.removeClass("current");
    $next.addClass("current");
}

And similarly for prev.

Upvotes: 3

Try this:

window.next = function() {
   var li = jQuery("li.current");
   if (li.length && li.next().length)
       li.removeClass("current").next().addClass("current");
   else {
       li.removeClass("current");
       jQuery("li").first().addClass("current");
   }
}

window.prev = function() {
   var li = jQuery("li.current");
   if (li.length && li.prev().length)
       li.removeClass("current").prev().addClass("current");
   else {
       li.removeClass("current");
       jQuery("li").last().addClass("current");
   }
}

Upvotes: 0

Related Questions