JQuery shows the first X elements with more or less links

I am trying to find a jQuery solution to display the first 3 items in each menu in the left navigation filter using the "Show more" and "Show less" links, which allows users to expand the list.

I was looking for a solution, but most expand / collapse scripts finish hiding the layer, while others show the Expand link (Show more), but do not switch to show the Collapse (Show less) link.

My menus are encoded 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> 
+7
source share
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 .

+13
source

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'); }); }) 
+4
source

All Articles