Hide all li elements and show the first 2 and toggle them by button

14,229

Solution 1

this 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 :

$('ul li').hide().filter(':lt(2)').show();
$('ul').append('<li>more</li>').find('li:last').click(function() {
  $(this).siblings(':gt(1)').toggle();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
</ul>


Update to add changing text from more to less ..

$('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();
    });

needs a css rule of .less{display:none}

demo :

$('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();
  });
.less {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
</ul>

Solution 2

Is this something like you're looking for?

 $('li').hide()
        .slice(0,1)
        .addClass('fixed')
        .show();
 $('<li class="toggle">more</li>')
        .appendTo('ul')
        .click( function() {
             $('li:not(.toggle,.fixed)').toggle();
         });
Share:
14,229
Mostafa Elkady
Author by

Mostafa Elkady

free open source php scripts

Updated on June 16, 2022

Comments

  • Mostafa Elkady
    Mostafa Elkady over 1 year

    Assume I have

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

    I want jQuery code to hide all <li> then show the fist and the second one then append() an additional <li>more</li> that is used to toggle the hidden li.