I want to make a long list short by hiding some elements in long sub-lists without adding extra processing on the server side. The problem is that the markup that comes from the server is not controlled by me and is not designed in a way to make my job easy. here is the code
<ul id="long-list">
<li class="item"></li>
<li class="item"></li>
<li class="item"></li>
<li class="header"></li>
<li class="item"></li>
<li class="item"></li>
<li class="item"></li>
<li class="item"></li>
<li class="item"></li>
<li class="header"></li>
<li class="item"></li>
.
.
.
</ul>
As you’ve notices the headers are sibling to the items. Now, I want to have a jQuery code that shows only 3 items after each header and hide the rest to make the list shorter and more usable.
Here is my try which is not working:
$('#long-list li.header ~ li.item:gt(3)').hide();
$('#long-list li.header ~ li.item:lt(3)').show();
$('#long-list li.header').show();
The extra feature is adding a node at bottom of each section that has hidden items, saying how many items has been hidden, say “5 more…”
This is how I’ve implemented it. Note that it has some other features like adding a node at the end of sub lists that have hidden items, saying x items are hidden and bind an onclick event to toggle hidden items.
It’s basically based on what svinto said above. I still look for a better performance. Anyhow, right now I’m happy with the results.
Initiating i with -1000 ensures that we’ll not hide items at the top of the list that do not have any header. as soon as we reach a header we’ll set the i to zero and start counting.