substring()
methodYou 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.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Add Read More Link</title>
<script src="https://code.jquery.com/jquery-1.12.4.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>
Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]
Laravel Pluck Method Example
Sometimes, you may want only one column...How to Secure File in Laravel Only Allow to Access Authenticated User
In this article, i will share with you h...How to loop through an array in JavaScript
Use the JavaScript for Loop...How to get the value of a textarea in jQuery
Use the jQuery val() method You can u...PHP Find Request Type
When working with external services, lik...