I am pulling paragraph content from the database and displaying only 300 characters on the screen, with a "read more" option for the user to see the rest of the content.
However, I am facing an issue where I also need to include a "less" option for the user to revert back to the truncated version of the content after clicking on "read more." I have attempted the following code snippet:
$(document).ready(function() {
var maxLength = 300;
$(".countParawords").each(function() {
var myStr = $(this).text();
if ($.trim(myStr).length > maxLength) {
var newStr = myStr.substring(0, maxLength);
var removedStr = myStr.substring(maxLength, $.trim(myStr).length);
$(this).empty().html(newStr);
$(this).append(' <a href="javascript:void(0);" class="read-more">...READ MORE</a>');
$(this).append('<span class="more-text">' + removedStr + '</span>');
}
});
$(".read-more").click(function() {
$('.less').show();
$(this).append(' <a href="javascript:void(0);" class="less">LESS</a>');
$(this).siblings(".more-text").contents().unwrap();
$(this).remove();
});
$(".less").click(function() {
$(this).siblings(".more-text").contents().wrap();
$(this).remove();
});
});
.box {
width: 500px;
margin: auto;
}
.box .more-text {
display: none;
}
.box .less {
display: none;
}
<div class="box">
<p class="countParawords">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing
elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit essecillum
dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</p>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>