Add “Read More/Read Less” to any text in Javascript and JQuery

Blog Problem Solving Tutorial

Javascript and JQuery tutorial how to add "read more" and "read less" at the end of the text after a certain number of characters.

This tutorial will take you through how to display a certain number of rows of an HTML element and hide the rest of it, then we will see how to read a clickable “Read More” element at the end of the text in order to display/hide the rest of the text.

The challenge here is, I would like to keep a part of the text always visible and display a text “…read more” after it, eventually, when the text is fully visible, I want to add a new element called “read less” in order to hide the second part of the text. I want to apply this logic to any HTML element just adding a CSS class to it. I also want to have the possibility to decide how many characters of the text I want to display before hiding the second part.

First of all, I need a CSS class to recognize the HTML element that I want to play with, let’s say that the CSS class will be ‘.add-read-more‘, initially, I want to detect if the text is completely displayed or if part of the text is hidden, so I will add another CSS class to the HTML element called “.show-less-content“. Now I can get the text of the HTML through JQuery and I check if the text is long enough, for example, I will check if the text is greater than 300 characters, if the text is less than 300 characters I won’t change anything of it, if the text is greater than 300 characters I will split the text into two sections and through CSS I will hide the second part.

Now I just need to add the “read more/read less” section at the end of the visible text, I will use an HTML <span></span> to do that, this HTML element will contain the two buttons “read more” and “read less”. The last thing to do is create a JQuery function that detected the click on the “read more/read less” section and it will open or close the second part of the text.

Here is the whole Javascript code of the login explained above:

jQuery(function ($) {
   function AddReadMore() {
      //This limit you can set after how much characters you want to show Read More.
      var carLmt = 300;
      // Text to show when text is collapsed
      var readMoreTxt = " ...read more";
      // Text to show when text is expanded
      var readLessTxt = " read less";


      //Traverse all selectors with this class and manupulate HTML part to show Read More
      $(".add-read-more").each(function () {
         if ($(this).find(".first-section").length)
            return;

         var allstr = $(this).text();
         if (allstr.length > carLmt) {
            var firstSet = allstr.substring(0, carLmt);
            var secdHalf = allstr.substring(carLmt, allstr.length);
            var strtoadd = firstSet + "<span class='second-section'>" + secdHalf + "</span><span class='read-more'  title='Click to Show More'>" + readMoreTxt + "</span><span class='read-less' title='Click to Show Less'>" + readLessTxt + "</span>";
            $(this).html(strtoadd);
         }
      });

      //Read More and Read Less Click Event binding
      $(document).on("click", ".read-more,.read-less", function () {
         $(this).closest(".add-read-more").toggleClass("show-less-content show-more-content");
      });
   }

   AddReadMore();
});

In order to make the code a bit more standard, I will use variables to manage the number of characters and the Text to show when text is collapsed/expanded. Please see the variables called “carLmt, readMoreTxt, readLessTxt” on the code above.

Now I will include the CSS in the code, here is the style:

.add-read-more.show-less-content .second-section,
.add-read-more.show-less-content .read-less {
   display: none;
}

.add-read-more.show-more-content .read-more {
   display: none;
}

.add-read-more .read-more,
.add-read-more .read-less {
   font-weight: bold;
   margin-left: 2px;
   color: blue;
   cursor: pointer;
}

The last thing to do is add the mentioned CSS classes to the element that we want to modify, here is the HTML code for it:

<p class="add-read-more show-less-content">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</p> 

And this is all I think, here is the result:

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry’s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum

To see the whole code in action, please have a look at this task on CodePen at this link: https://codepen.io/webmarcello8080/pen/oNGmGWL

You May Like

Today we try to analyze the error that appears on the browser inspector and that is a bit tricky to fix and we try to understand what is causing the error, the error is called “Failed to load resource: net::ERR_BLOCKED_BY_CLIENT“. This error is always followed by an URL, this URL is the link that has […]

May 28, 2021
Read More...
how to freeze the first row and the first column of an HTML table

I was working on an HTML table that displays a list of users and user permission, the first row displays the permission names and the first column displays the name of the users involved. I have noticed that when I strolled toward the right I couldn’t see the user names and scrolling toward the bottom […]

May 28, 2021
Read More...

The Fullscreen Any Element Plugin uses the Javascript Fullscreen API in order to make any chosen HTML element on your website in fullscreen. The Fullscreen API adds methods to present a specific Element (and its descendants) in full-screen mode, and to exit full-screen mode once it is no longer needed. This makes it possible to […]

May 24, 2021
Read More...

Click to Leave a Comment