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>
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.
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');
});
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With