Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery show first X elements with More and Less links

I am trying to find a jQuery solution to show the first 3 items on each menu in a left-hand navigation filter with a 'Show more' and 'Show less' link enabling users to expand the list.

I have searched for a solution but most expand/collapse scripts completley hide the layer whilst others show an Expand (Show more) link but do not toggle to show a Collapse (Show less) link.

My menus are coded as follows.

<div id="menu1">
<ul class="term-list">
<li class="term-item ">Item 1</li>
<li class="term-item ">Item 2</li>
<li class="term-item ">Item 3</li>
<li class="term-item ">Item 4</li>
</ul>
</div>
<div id="menu2">
<ul class="term-list">
<li class="term-item ">Item 1</li>
<li class="term-item ">Item 2</li>
<li class="term-item ">Item 3</li>
<li class="term-item ">Item 4</li>
</ul>
</div>
like image 962
sr83 Avatar asked Jun 17 '12 16:06

sr83


2 Answers

jsBin demo

Here is just a basic example:

$('ul.term-list').each(function(){
  
  var LiN = $(this).find('li').length;
  
  if( LiN > 3){    
    $('li', this).eq(2).nextAll().hide().addClass('toggleable');
    $(this).append('<li class="more">More...</li>');    
  }
  
});


$('ul.term-list').on('click','.more', function(){
  
  if( $(this).hasClass('less') ){    
    $(this).text('More...').removeClass('less');    
  }else{
    $(this).text('Less...').addClass('less'); 
  }
  
  $(this).siblings('li.toggleable').slideToggle();
    
}); 

Or a more compact version.

like image 131
Roko C. Buljan Avatar answered Nov 11 '22 22:11

Roko C. Buljan


DEMO: http://jsfiddle.net/DQKyT/

$(function(){
    /* add button, hide extra items*/      
    $('.term-list').each(function() {
        var $list = $(this);
        $list.before('<button class="more_less">More</button>')
       $list.find('.term-item:gt(2)').hide();
    });

    /* button click handler*/
    $('.more_less').click(function() {
        var $btn = $(this)
        $btn.next().find('.term-item:gt(2)').slideToggle();    
        $btn.text($btn.text() == 'More' ? 'Less' : 'More');   
    });
})
like image 21
charlietfl Avatar answered Nov 11 '22 22:11

charlietfl