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

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

Asked on November 2, 2018 in jQuery.
Add Comment


  • 1 Answer(s)

      Use the JavaScript substring() method in addition 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.

      In the following example,trim the paragrah and add more link at the end.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>
    
    Answered on November 2, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.