Show read more link if the text exceeds a certain length using jQuery
Topic: JavaScript / jQueryPrev|Next
Answer: Use the JavaScript substring()
method
You can use the JavaScript substring()
method in combination with the jQuery append()
and html()
methods to truncate the paragraphs of a text and add read more link at the end, if the number of characters inside a paragraph exceeds a certain length.
The jQuery code in following example will simply trim the paragraph and add read more link at the end. You can view the trimmed content by clicking the read more link.
Example
Try this code »<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Add Read More Link</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
var maxLength = 300;
$(".show-read-more").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(){
$(this).siblings(".more-text").contents().unwrap();
$(this).remove();
});
});
</script>
<style>
.show-read-more .more-text{
display: none;
}
</style>
</head>
<body>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<p class="show-read-more">This is a very long paragraph...</p>
</body>
</html>
Related FAQ
Here are some more FAQ related to this topic: