jQuery load first 3 elements, click "load more" to display next 5 elements

JV10 picture JV10 · Jul 19, 2013 · Viewed 151k times · Source

I have an unordered list:

<ul id="myList"></ul>
<div id="loadMore">Load more</div>

I wish to populate this list with list items from another HTML file:

<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>

I want to load the first 3 list items, then show the next 5 items when the user clicks the "load more" div:

$(document).ready(function () {
    // Load the first 3 list items from another HTML file
    //$('#myList').load('externalList.html li:lt(3)');
    $('#myList li:lt(3)').show();
    $('#loadMore').click(function () {
        $('#myList li:lt(10)').show();
    });
    $('#showLess').click(function () {
        $('#myList li').not(':lt(3)').hide();
    });
});

I need help though, as I would like the "load more" to show the next 5 list items, but if there are more list items within the HTML file, to again display the "load more" div and allow users to display the next 5 items, repeating this until the entire list is displayed.

How can I best achieve this?

I have created the following jsfiddle: http://jsfiddle.net/nFd7C/

Answer

WARNING: size() was deprecated in jQuery 1.8 and removed in jQuery 3.0, use .length instead

Working Demo: http://jsfiddle.net/cse_tushar/6FzSb/

$(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').click(function () {
        x=(x-5<0) ? 3 : x-5;
        $('#myList li').not(':lt('+x+')').hide();
    });
});


New JS to show or hide load more and show less

$(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();
        }
    });
});

CSS

#showLess {
    color:red;
    cursor:pointer;
    display:none;
}

Working Demo: http://jsfiddle.net/cse_tushar/6FzSb/2/