Skip to content
Advertisement

Show more/less without stripping Html tags in JavaScript/jQuery

I want to implement readmore/less feature. i.e I will be having html content and I am going to show first few characters from that content and there will be a read more link in front of it. I am currently using this code :

    var txtToHide= input.substring(length);
    var textToShow= input.substring(0, length);
    var html = textToShow+ '<span class="readmore">&nbsp;&hellip;&nbsp;</span>' 
+ ('<span class="readmore">' + txtToHide+ '</span>');
    html = html + '<a id="read-more" title="More" href="#">More</a>';

Above input is the input string and length is the length of string to be displayed initially. There is an issue with this code, suppose if I want to strip 20 characters from this string: "Hello <a href='#'>test</a> output", the html tags are coming between and it will mess up the page if strip it partially. What I want here is that if html tags are falling between the range it should cover the full tag i.e I need the output here to be "Hello <a href='#'>test</a>" . How can I do this

Advertisement

Answer

Instead of doing too much manually, I prefer you to go with following jQuery plugin.

http://plugins.learningjquery.com/expander/index.html#getting-started

It will expand and collapse your text for Read more options, Also provide you much customization.

Hope this will help.

Thanks!

Hussain

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement