Read More/Less Content Toggle Plugin For jQuery

Read More/Less Content Toggle Plugin For jQuery
File Size: 4.2 KB
Views Total:
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   

Yet another jQuery content toggle/character limit plugin(script) that allows the visitor to expand and contract long text with Read More and Read Less links.

How it works:

  1. Truncate the long text by the number of characters you specify.
  2. Wrap the overflowing text in a hidden <span> element.
  3. Make the <span> element visibile on click.

How to use it:

1. Insert your long text into a <span> element with the CSS class of .more.

<span class="more">
  Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</span>

2. Insert the latest jQuery JavaScript library into the HTML document.

<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" 
        integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" 
        crossorigin="anonymous">
</script>

3. Specify how many characters are shown by default.

var showChar = 100;

4. Customize the ellipsis character.

var ellipsestext = "...";

5. Customize the Read More and Read Less text.

var moretext = "Show more >";
var lesstext = "Show less";

6. The main functions to activate the text truncation functionality.

$('.more').each(function() {
  var content = $(this).html();

  if(content.length > showChar) {

      var c = content.substr(0, showChar);
      var h = content.substr(showChar, content.length - showChar);

      var html = c + '<span class="moreellipses">' + ellipsestext+ '&nbsp;</span><span class="morecontent"><span>' + h + '</span>&nbsp;&nbsp;<a href="" class="morelink">' + moretext + '</a></span>';

      $(this).html(html);
  }

});

$(".morelink").click(function(){
  if($(this).hasClass("less")) {
      $(this).removeClass("less");
      $(this).html(moretext);
  } else {
      $(this).addClass("less");
      $(this).html(lesstext);
  }
  $(this).parent().prev().toggle();
  $(this).prev().toggle();
  return false;
});

7. Hide the overflowing text.

.morecontent span {
  display: none;
}

8. Make the Read More link visible.

.morelink {
  display: block;
}

This awesome jQuery plugin is developed by thanhtuyenit. For more Advanced Usages, please check the demo page or visit the official website.