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.
To show and hide div on mouse click using jQuery, use the toggle() method. On mouse click, the div is visible and on again clicking the div, it hides.
To display or hide a <div> by a <button> click, you can add the onclick event listener to the <button> element. The onclick listener for the button will have a function that will change the display attribute of the <div> from the default value (which is block ) to none .
You can specify either 'hidden' (without value) or 'hidden="hidden"'. Both are valid. A hidden <button> is not visible, but maintains its position on the page.
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>
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();
});
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