Show more / less
by csornmo
HTML
<div class="show-more">
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
<li>8</li>
<li>9</li>
</ul>
<button href="#" class="ShowMore-btn">SHOW MORE</button>
<button href="#" class="ShowLess-btn">SHOW LESS</button>
</div>
<div class="show-more">
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
<li>8</li>
<li>9</li>
</ul>
<button href="#" class="ShowMore-btn">SHOW MORE</button>
<button href="#" class="ShowLess-btn">SHOW LESS</button>
</div>
CSS
/* CSS NOT NEEDED */
.show-more {
padding: 20px;
background: #eee;
margin-bottom: 30px;
}
ul {
padding: 0;
margin: 0;
list-style: none;
}
/* CSS IS NEEDED */
li:nth-child(n+4) {
display: none;
}
.ShowLess-btn {
display: none;
}
JavaScript
$('.ShowMore-btn').click(function() {
$(this).closest('.show-more').find('li:not(:visible):lt(3)').show();
var item = $(this).closest('.show-more').find('li').length;
var allItems = $(this).closest('.show-more').find('li:visible').length;
if (item === allItems) {
$(this).hide();
$(this).closest('.show-more').find('.ShowLess-btn').show();
}
});
$('.ShowLess-btn').click(function() {
$(this).closest('.show-more').find('li:gt(2)').hide();
$(this).hide();
$(this).closest('.show-more').find('.ShowMore-btn').show();
});