How to add read more toggle for html string?

If your content is too long and it not looks good than you can try read more toggle option. I tried it in one of my client HTML based website and it works fine. Like you want to display just first 100 words to your visitors after that "read more" link comes automatically and when visitor click on read more than it will show more content. 

So basically the content is not removed it's just hide and show effect.   

You can add read more toggle in your HTML file by using little bit of jQuery code please check the below code:

HOW YOU CAN IMPLEMENT IT PLEASE CHECK BELOW EXAMPLE:

HTML CODE:

<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>
<br><br>
<div class="more">
  Morbi placerat imperdiet risus quis blandit. Ut lobortis elit luctus, feugiat erat vitae, interdum diam. Nam sit amet arcu vitae justo lacinia ultricies nec eget tellus. Curabitur id sapien massa. In hac <a href="#">habitasse</a> platea dictumst. Integer tristique leo consectetur libero pretium pretium. Nunc sed mauris magna. Praesent varius purus id turpis iaculis iaculis. Nulla <em>convallis magna nunc</em>, id rhoncus massa ornare in. Donec et feugiat sem, ac rhoncus mauris. Quisque eget tempor massa.
</div>
________________________________________________________________________________

JQUERY CODE:

$(document).ready(function() {
  var showChar = 100;
  var ellipsestext = "...";
  var moretext = "Show more >";
  var lesstext = "Show less";

  $('.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;
});
});

_________________________________________________________________________________

CSS CODE:

.morecontent span {
  display: none;
}
.morelink {
  display: block;
}

Output:

Read More


Read Less


Post a comment

0 Comments