Cloudboy22
Cloudboy22

Reputation: 1514

how to stop .next() going off list of li's

i am working on a gallery where i navigate previous and next list items using arrow keys. now using .next() and .prev() i am able to navigate really nice but the problem starts when the last List Item is there and the jquery goes to .Next().

How can i stop a process that it won't go after last li Item.

i mean the next() function dosent apply after last Li. Here is my sample code

  var ul = $('#thumbsList');
ul.find('li').first().addClass('current');

This one adds a class.

    $(document).ready(function () {
    $('#nextHandler').click(function () {

        var nextListItem = ul.find('li.current').next();

        ul.find('li.current').removeClass('current');
        nextListItem.addClass('current');
        var imagePath = ul.find('li.current').children('img').data("fullsrc");
        // Setting Image Path to Current Next Image path
        $("#fullImagePlaceholder").attr("src", imagePath);


    });
});

This does the job. But the problem starts when it jumps of the last LI. How to stop it. thanks.

Upvotes: 2

Views: 171

Answers (3)

designerNProgrammer
designerNProgrammer

Reputation: 2701

You can always check with .length is greater than 0 if it still has items. this way you can navigate and find elements in any object.

Upvotes: -1

Snake Eyes
Snake Eyes

Reputation: 16764

you have this

 var nextListItem = ul.find('li.current').next();

you may check

if (nextListItem.length) {
// .. do the job
}

Upvotes: 1

Liam
Liam

Reputation: 29654

You need to test if there is a next using if (nextListItem.length > 0) like explained here:

 var nextListItem = ul.find('li.current').next();

    if (nextListItem.length > 0)
    {
      ul.find('li.current').removeClass('current');
      nextListItem.addClass('current');
      var imagePath = ul.find('li.current').children('img').data("fullsrc");
      // Setting Image Path to Current Next Image path
      $("#fullImagePlaceholder").attr("src", imagePath);
    }

Upvotes: 1

Related Questions