tags:

views:

22

answers:

4

I think i kind off miss some logical insight. It seems so easy, but i just don't see it..

I have a list and want to see if there are list items before and/or after the clicked item. Here's the code


<script>
[..]
$("a").click(function(event){
 var parentEl = $(this).closest("ul");
 var currPosition = $(this).parent().prevAll().length + 1;
 var totalItems = $("#"+$(parentEl).attr("id")+" li").length;

 if(currPosition == totalItems){ alert("Previous and Next"); }
 if(currPosition <= totalItems){ alert("Next"); }
 if(currPosition >= totalItems){ alert("Previous"); } 
[..]
</script>

[..]

<ul id="listOne">
 <li><a>Text 1</a></li>
 <li><a>Text 2</a></li>
 <li><a>Text 3</a></li>
 <li><a>Text 4</a></li>
</ul>

The code above almost works only one i click the last item, everything gets alerted.. I just want to know if there is a previous, next or both opions on the list-items that's clicked

A: 

You can check using .nextAll(), .prevAll() and .length, like this:

$("a").click(function(event){
  var pCount = $(this).closest('li').prevAll().length, //how many previous
      nCount = $(this).closest('li').nextAll().length; //how many after
  if(pCount > 0 && nCount > 0){ alert("Previous and Next"); }
  else if(nCount > 0){ alert("Next"); }
  else if(pCount > 0){ alert("Previous"); } 
});

You can give it a try here, of course you can make this much shorter, but trying to illustrate where the counts are coming from, this method can tell you not only if there are previous/following elements like .prev() and .next() would, but how many, if that matters at all.

Nick Craver
+1  A: 

Make your life a little easier and use index() to find something's current position.

$("a").click(function() {
  var li = $(this).closest("li");
  var items = li.parent().children();
  var currPosition = items.index(li);
  var totalItems = items.length();
  if (currPosition == 0) {
    // first
  } else if (currPosition == totalItems.length - 1) {
    // last
  } else {
    // middle
  }
});

Alternatively, you can do tests like this:

if (li.is(":first-child")) {
  // first
} else if (li.is(":last-child")) {
  // last
} else {
  // in the middle
}
cletus
Could also do `li.index()` (assuming jQuery 1.4 or later).
patrick dw
A: 

Quick fix:

if(currPosition == totalItems){ 
  alert("Previous"); 
} else if(currPosition == 1){ 
  alert("Next"); 
} else {
  alert("Previous and Next");
}
RC
Simple as hell! I knew it! Thanks!
Maurice
A: 

Simply a case of checking if their are items before or after the parent li.

$("a").click(function(){
      var itemsBefore = ($(this).parent().prev().length>0)
      var itemsAfter = ($(this).parent().next().length>0)
      if(itemsBefore && itemsAfter) alert("Previous and next");
      else if(itemsBefore) alert("Previous");
      else alert("Next");
  });

Working fiddle here --> http://jsfiddle.net/wmgvB/

Jamiec