I am using JS to create a read more button/read less button on the WooCommerce archive product category description. To hide some of the text into a read-more expandable div
The read more button is working & the read less button is working, but it stops working after both read more and read less button events/functions have been clicked once each:
jQuery( function( $ ) {
$(document).ready(function() {
//Get the current height of the description container
let curHeight = $(".archive-description").height();
//Set the height of the description container
$(".archive-description").css({
"height": "80px",
"overflow": "none",
});
//Add 'Read more button
$(".archive-description").after( "<button class='read-more'>Read more...</button>" );
//Set description container back to its original height
$( ".read-more" ).on( "click", function() {
$(".archive-description").animate({height: curHeight});
$('.read-more').hide();
$(".archive-description").after( "<button class='read-less'>Read less...</button>" );
});
});
$(document).on('click', '.read-less', function () {
$(".archive-description").animate({height: 80});
$('.read-less').hide();
$(".archive-description").after( "<button class='read-more'>Read more...</button>" );
});
});
3
Answers
The reason why you can only target them once is because they are being added after the
DOM
is inready
state.You could instead call them like:
Once read more or read less are clicked, they are getting re-generated by the jQuery code dynamically.
So now they are not the part of initial rendered DOM. To Address them, you need to use the
.on
handler.So convert like this:
I’ve used event delegation to handle the click events for both "Read more" and "Read less" buttons, ensuring that they work correctly for dynamically added buttons. Additionally, I changed the CSS overflow property to "hidden" for the description container to hide the overflowed text when it’s collapsed