views:

81

answers:

4

Hey Guys,

Say I have an unordered list, like so:

<ul>
   <li>One</li>
   <li>Two</li>
   <li>Three</li>
   <li>Four</li>
   <li>Five</li>
</ul>

How would I, using JQuery, hide the last 2 list items and have a 'show more' link there, so when clicked upon, the last 2 list items would appear?

<ul>
   <li>One</li>
   <li>Two</li>
   <li>Three</li>
   <li style="display:none;">Four</li>
   <li style="display:none;">Five</li>
   <li>Show More</li>
</ul>
+6  A: 

Try

$('ul li:gt(4)').hide();
$('.show_button').click(function() {
  $('ul li:gt(4)').show();
});
pex
@pex: Would the index not be 3 rather than 4 as javascript is zero index based?
Brian Scott
@Brian: You're totally right!
pex
+1  A: 

Hi Keith,

I'm assuming that you are starting with the UL as per your example code.

I would find the UL and hide items greater than the index of the last item you'd like to initially display. Then I would add a new item to act as a hook for displaying the rest. Finally, I'd hide the show more option as it was no longer needed.

See the following:

$('ul li:gt(3)')
.hide()
.parent()
.append('<li onclick="$(this).parent().find(''li:gt(3)'').show();$(this).hide();">Show more</li>');
Brian Scott
+3  A: 

For fun, here's a roundabout way to do it in one chain:

$('ul')
  .find('li:gt(3)')
  .hide()
  .end()
  .append(
    $('<li>Show More...</li>').click( function(){
      $(this).siblings(':hidden').show().end().remove();
    })
);
Ken Redler
@Ken: nice. I was trying the same for myself. I'm typing on a mobile though so can't test but like your approach as well.
Brian Scott
@Ken: your siblings(':hidden') approach is a nice one
pex
@Brian, what's frustrating is when you're trying to answer a question on an iPad. No backtick symbol on the keyboard...
Ken Redler
A: 

It would be more like this. You would have to hide the children greater than 2, because Three is indexed as 2. Also, if you wanted to put the Show More in an LI tag, you would need to include :not(:last-child) in your selector. Like so:

<script src="http://code.jquery.com/jquery-latest.min.js"&gt;&lt;/script&gt;
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li><a href=# class=show>Show More</a></li>
</ul>
<script>$("li:gt(2):not(:last-child)").hide();
$('.show').click(function(){
$("li:gt(2)").show();
});
</script>
bozdoz