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

by Ritesh Kashyap

HTML

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

CSS

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

JavaScript

$(document).ready(function () {
    var $items =  $("#myList li");
    $items.filter(':lt(3)').show()
    
    $('#loadMore,#showLess').click(function () {
       var more = $(this).is('#loadMore');
        var first= $items.filter(':visible:first').index();
        var start = more ? ++first : --first;
        if(start >-1 && start <= $items.length - 3)
        $items.hide().slice(start, start+3).show()
    });
    
});