whoabackoff whoabackoff - 6 months ago 13
Javascript Question

How can I hide elements in my list and add a 'show more' feature?

I'm using javascript to build a list of results. I have a for-loop that iterates over some data and creates a mydata div, and adds that to the results div. Let's pretend it looks something like this:

<div id="results">
<div class="mydata">data 1</div>
<div class="mydata">data 2</div>
...
<div class="mydata">data 20</div>
</div>


What I want to do is only display 5 results at a time, and should the user wish to see more, they can click a show next 5 or show more button (or something similar). Any ideas?

Just to clarify, every time the user clicks "show more" I want to 'unhide' the next 5 elements, not ALL the remaining elements. So each click reveals more elements until all are displayed.

Answer

You can use the gt() and lt() selectors along with :visible pretty well here.

The following will show the next 5 results on clicking and removes the link once all items are visible.

$('.mydata:gt(4)').hide().last().after(
    $('<a />').attr('href','#').text('Show more').click(function(){
        var a = this;
        $('.mydata:not(:visible):lt(5)').fadeIn(function(){
         if ($('.mydata:not(:visible)').length == 0) $(a).remove();   
        }); return false;
    })
);

working example: http://jsfiddle.net/niklasvh/nTv7D/

Regardless of what other people are suggesting here, I would not hide the elements using CSS, but do it in JS instead, because if a user has JS disabled and you hide the elements using CSS, he won't get them visible. However, if he has JS disabled, they will never get hidden, nor will that button appear etc, so it has a full noscript fallback in place + search engines don't like hidden content (but they won't know its hidden if you do it on DOM load).