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.

How to add Read More/Read Less button next to a too long HTML element.

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

How to add “Read More” link to a HTML element with a slide animation

Jquery provides a series of functions in order to animate, slide in, slide out certain HTML elements, so we don’t need to create an animation from scratch, in the code I will use the method “animate” in order to create the slide effect, please have a look at the official documentation for future reference.

The first thing to do in this case will be to reduce the text height if the text is longer than a certain amount of pixel, for instance, let’s say that I want my text to be a maximum of 200px. I get the HTML element by class (I will use the class ‘slide-read-more‘), I check if the element height is greater than 200px, if the element is too long I will set the height of the text to 200px, then I will display the “Read More” button, which I previously hid on the bottom of the ‘slide-read-more‘ text.

To get the current height of the text I will use the JQuery function .innerHeight() which gets the current computed inner height (including padding but not border) for the first element in the set of matched elements or set the inner height of every matched element. Here is the documentation.

Then I will create a JQuery function based on the click of ‘.slide-read-more-button’. When the button is clicked, I check the height of ‘slide-read-more’, if the text is 200px I remove the height of 200px that I previously added and I run animate to display a slide animation. If the text is longer than 200px, I will set the height of the text to 200px and I run the animate function. This approach seems more simple than the previous and the result is more interactive. Here is the Javascript code:

jQuery(function ($) {
   // resize the slide-read-more Div
   var box = $(".slide-read-more");
   var minimumHeight = 200; // max height in pixels
   var initialHeight = box.innerHeight();
   // reduce the text if it's longer than 200px
   if (initialHeight > minimumHeight) {
      box.css('height', minimumHeight);
      $(".slide-read-more-button").show();
   }

   SliderReadMore();

   function SliderReadMore() {
      $(".slide-read-more-button").on('click', function () {
         // get current height
         var currentHeight = box.innerHeight();

         // get height with auto applied
         var autoHeight = box.css('height', 'auto').innerHeight();

         // reset height and revert to original if current and auto are equal
         var newHeight = (currentHeight | 0) === (autoHeight | 0) ? minimumHeight : autoHeight;

         box.css('height', currentHeight).animate({
            height: (newHeight)
         })
         $('html, body').animate({
            scrollTop: box.offset().top
         });
      });
   }
});

In order to keep my code a bit more standard I set a couple of variables, minimumHeight contains the number of pixels that the text will be initially, box is the JQuery element (or elements) with class ‘slide-read-more’, currentHeight is the current height of box, initialHeight contain the current computed inner height of box.

Now I just need to add some CSS in order to hide the extra text that I don’t want to display and in order to style the ‘Read More’ button. Here is the CSS code:

.slide-read-more{
     overflow:hidden;
 }
 .slide-read-more-button{
     cursor: pointer;
     text-align: right;
     margin-top: 8px;
     color: #488A8A;
     display: none;
 }

Here is an example to how to use the code explained above:

<p class="slide-read-more">
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.
 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>
<div class="slide-read-more-button">Read More</div>

And here is the final 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.
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.

Read More

As usual, I have created a code sample in codepen, so you can play around with it, here is the link:
https://codepen.io/webmarcello8080/pen/MWOaKzV

Click to Leave a Comment

You May Like

woocommerce-min-max-checkout-plugin

Woocommerce Min Max Checkout is a plugin that extends your Woocommerce e-commerce in order to give you the possibility to set the minimum or maximum checkout amount or in order to set a minimum or maximum order quantity on the cart or checkout pages. With Woocommerce Min Max Checkout you can also set e customizable […]

February 12, 2022
Read More...

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...