Hide all li elements and show the first 2 and switch them with the button

Let's pretend that

<ul>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
</ul>

I need jQuery code to hide everything <li>, and then show the fist, and the second then the append()extra one <li>more</li>, which is used to switch whether it is hidden.

+5
source share
2 answers

it should do it.

// hide all li and then show the first two
$('ul li').hide().filter(':lt(2)').show(); 

// append a li with text more that on click will show the rest
$('ul').append('<li>more</li>').find('li:last').click(function(){
    $(this).siblings(':gt(1)').toggle();
});

demo at : http://jsfiddle.net/gaby/tNGxN/2/


Refresh to add changing text from larger to smaller ..

$('ul li')
    .hide()
    .filter(':lt(2)')
    .show();

$('ul')
    .append('<li><span>more</span><span class="less">less</span></li>')
    .find('li:last')
    .click(function(){
        $(this)
            .siblings(':gt(1)')
            .toggle()
            .end()
            .find('span')
            .toggle();
    });

css rule required .less{display:none}

demo : http://jsfiddle.net/gaby/tNGxN/3/

+18
source

Is this something like what you are looking for?

 $('li').hide()
        .slice(0,1)
        .addClass('fixed')
        .show();
 $('<li class="toggle">more</li>')
        .appendTo('ul')
        .click( function() {
             $('li:not(.toggle,.fixed)').toggle();
         });
+5
source

All Articles