By
05/13/2016   Comments Off on Truncate and toggle list elements using jQuery

View all snippets

The jQuery:

// Details: http://jsfiddle.net/ztKUX/2/
$(document).ready(function(){
 
 $('.ShowHideFullLists').click (ShowHideFullLists);
 $('.ShowHideFullLists').click (); //-- Init list displays.
 
 function ShowHideFullLists () {
 var showHideBtn = $(this);
 var bShowEm = showHideBtn.data ('bShowEm') || false;
 
 // Find the list for this button. It is a previous sibling, in the HTML.
 var thisBtnsList = showHideBtn.prev ("ul.truncate-list");
 
 // Show either all or the # from the data-list-items attribute.
 ShowItems (thisBtnsList, bShowEm, thisBtnsList.data ('listItems') );
 
 // Update the show-all flag.
 bShowEm ^= true;
 showHideBtn.data ('bShowEm', bShowEm);
 
 // Update the button text.
 if (bShowEm)
 showHideBtn.text ('Show More');
 else
 showHideBtn.text ('Show Less');
 }
 
 function ShowItems (parentNode, bShowAll, numVisible) {
 
 if (bShowAll)
 parentNode.find ("> li").show ();
 else {
 parentNode.find ("> li:lt(" + numVisible + ")").show ();
 parentNode.find ("> li:gt(" + (numVisible-1) + ")").hide ();
 }
 }
 
});

The HTML

<ul class="truncate-list" data-list-items="3"> 
<li>...</li>
<li>...</li>
<li>...</li>
<li>...</li>
<li>...</li>
<li>...</li>
<li>...</li>
</ul>
<button class="ShowHideFullLists" type="button">View All</button>