I am trying to create a dynamic show-more and less content option using jquery. The problem is my results are coming from a for loop, so how can I force jquery that on page load to load only 20 results and then load the rest when I click show more button. Also the button should change to "show less" when the list is expanded and clicking on it will return to show just first 20 results. Below is my code
HTML
echo html_writer::start_tag('div', array('id' => 'establishment'));
echo html_writer::start_tag('h5');
echo get_string('institutions', 'block_solr');
echo html_writer::end_tag('h5');
echo html_writer::end_tag('div');
jQuery
var institutionList = $.getJSON({'url': location.protocol + '//' + location.host + currentdirpath + '/establishment.json', 'async': false});
institutionList = JSON.parse(institutionList.responseText);
console.log(institutionList);
for (var i = 0; i < institutionList.data.length; i++) {
$('#establishment').append('<div class="form-check"> <input class="form-check-input size-filter-check" type="checkbox" value="'+ institutionList.data[i].altname +'" id="est-check" data-size="">\n' +
' <label class="form-check-label" for="size-check">\n' + institutionList.data[i].fullname +
' </label> </div>');
}
$('#establishment').append('<a href="#" class="show-more">Show More</a>');
If you want to query for specific amount that data source should be prepared for it. If you don't mind over fetching you can just hide/show that additional records on FE side.
// keeping some state would help
let listExpanded = false;
// wrapping all rendering procedure in one function too
function renderInstitutionList() {
//here you clear previous render
$('#establishment').empty()
// you can trim your array to certain size with code below
//[...] syntax is to avoid mutating original list
[...institutionList.data].splice(0, limit)
// and here you do your thing with the loop
}
There are tons of other solutions though. You could probably do that just with html/css