Here is the code I have written:
$(document).ready(function () {
$('<button class="btn more">View More</button>')
.appendTo(".listing-item-container")
.click(function() {
$(this).closest(".listing-item-container").removeClass("collapsed");
});
$('<button class="btn less">View Less</button>')
.appendTo(".listing-item-container")
.click(function() {
$(this).closest(".listing-item-container").addClass("collapsed");
});
});
.listing-item-container.collapsed > :nth-of-type(n+3) {
display:none;
}
.listing-item-container > .more {
display:none;
}
.listing-item-container > .less {
display:block;
}
.listing-item-container.collapsed > .more {
display:block;
}
.listing-item-container.collapsed > .less {
display:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="listing-item-container collapsed">
<div class="listing-item">
<p>FEATURES</p>
<ul class="no-list-style">
<li>list content</li>
<li>list content</li>
<li>list content</li>
<li>list content</li>
</ul>
</div>
<div class="listing-item">
<p>FEATURES</p>
<ul class="no-list-style">
<li>list content</li>
<li>list content</li>
<li>list content</li>
<li>list content</li>
</ul>
</div>
<div class="listing-item">
<p>FEATURES</p>
<ul class="no-list-style">
<li>list content</li>
<li>list content</li>
<li>list content</li>
<li>list content</li>
</ul>
</div><div class="listing-item">
<p>FEATURES</p>
<ul class="no-list-style">
<li>list content</li>
<li>list content</li>
<li>list content</li>
<li>list content</li>
</ul>
</div>
<!-- Remaining listing-item divs here -->
</div>
In the code above, clicking on view more
will expand all remaining 'listing item' divs
, while clicking on view less
collapses all the divs
to display only 2.
I want the functionality to show only the next 2 'listing item' divs
when I click view more
, along with the corresponding button. This pattern should repeat for all the remaining 'listing item' divs
, and end with a view less
button displayed. Clicking view less
should collapse the last 2 'listing item' divs
each time.
What changes can I make to my code to achieve this desired output?