Ryan
Ryan

Reputation: 15270

How can I truncate an unordered list and allow users to click to show all?

I have a long unordered list that I'd like to hide all but the first 3 on load, and then expand to all on click.

Here's my jQuery so far:

$('#myList').find('li:gt(3)').addClass('togglr').hide().end().append(
    $('<li class="show_more_btn">Read more »</li>').click(function(){
        $(this).siblings('.togglr').toggle();
        if ($(this).hasClass('expanded')){
            $(this).text('View All');
            $(this).removeClass('expanded');
        } else{
            $(this).text('View Less');
            $(this).addClass('expanded');
        }
    });

And my html:

<ul id="myList">
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
    <li>Item 4</li>
    <li>Item 5</li>
    <li>Item 6</li>
    <li>Item 7</li>
    <li>Item 8</li>
</ul>

Here's a jsFiddle: http://jsfiddle.net/t2jrZ/

Where am I going wrong?

Upvotes: 0

Views: 590

Answers (1)

Shannon Hochkins
Shannon Hochkins

Reputation: 12175

You were almost there! Maybe just thinking too much ;)

The prob with your current code is the last }); at the end of your current script, replace that with }));

HTML

<ul id="info">
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
    <li>Item 4</li>
    <li>Item 5</li>
    <li>Item 6</li>
    <li>Item 7</li>
    <li>Item 8</li>
</ul>
<button type="button" onclick="showAll();">Show All</button>

Javascript:

var limit = 3;
$('#info li:lt(' + limit + ')').show();
$('button').click(function(){
     $('#info li').show();
});

http://jsfiddle.net/t2jrZ/2/

Upvotes: 2

Related Questions