michaelmcgurk michaelmcgurk - 2 months ago 11
jQuery Question

Reveal All list items - using jQuery

I am working on a simple piece of code to hide then display list items.

Currently, I have it working so it reveals more each time I click

Load more
. It loads it in batches of 5, however, I'd like to reveal all the list items in the unordered list when I click
Load more
.

How do I achieve this with my current code?

Demo: http://jsfiddle.net/jtg7n4wj/



$(document).ready(function () {
size_li = $("#myList li").size();
x=3;
$('#myList li:lt('+x+')').show();
$('#loadMore').click(function () {
x= (x+5 <= size_li) ? x+5 : size_li;
$('#myList li:lt('+x+')').show();
$('#showLess').show();
if(x == size_li){
$('#loadMore').hide();
}
});
$('#showLess').click(function () {
x=(x-5<0) ? 3 : x-5;
$('#myList li').not(':lt('+x+')').hide();
$('#loadMore').show();
$('#showLess').show();
if(x == 3){
$('#showLess').hide();
}
});
});

#myList li{ display:none;
}
#loadMore {
color:green;
cursor:pointer;
}
#loadMore:hover {
color:black;
}
#showLess {
color:red;
cursor:pointer;
display:none;
}
#showLess:hover {
color:black;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="myList">
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>
<li>Five</li>
<li>Six</li>
<li>Seven</li>
<li>Eight</li>
<li>Nine</li>
<li>Ten</li>
<li>Eleven</li>
<li>Twelve</li>
<li>Thirteen</li>
<li>Fourteen</li>
<li>Fifteen</li>
<li>Sixteen</li>
<li>Seventeen</li>
<li>Eighteen</li>
<li>Nineteen</li>
<li>Twenty one</li>
<li>Twenty two</li>
<li>Twenty three</li>
<li>Twenty four</li>
<li>Twenty five</li>
</ul>
<div id="loadMore">Load more</div>
<div id="showLess">Show less</div>




Answer

Use this

   size_li = $("#myList li").size();
  x = 3;
  $('#myList li:lt(' + x + ')').show();
  $('#loadMore').click(function() {
    $('#myList li,#showLess').show();
    $('#loadMore').hide();
  });
  $('#showLess').click(function() {
    $('#myList li:gt(' + x + '),#showLess').hide();
    $('#loadMore').show();
  });

http://jsfiddle.net/5y002xzc/

Comments