Show read more link if the text exceeds a certain length using jQuery

Topic: JavaScript / jQuery« Prev|Next »

Answer: Use the JavaScript substring() method

You can use the JavaScript substring() method in combination with the jQuery append() and html() method to add read more link at the end of paragraphs if the number of characters inside a paragraph exceeds a certain length.

The following example 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 type="text/javascript">
  • $(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 type="text/css">
  •     .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:

 
Close

Your Feedback:

 

We would love to hear from you! Please say something.