Dynamically shortened Text with “Show More” link using jQuery

Update: The plugin is now on GitHub: https://github.com/viralpatel/jquery.shorten Facebook user updates has a great functionality. If the comment text is larger than few characters, the extra words are hide and a show more link is presented to user. This way you can keep long text out of the view to user and stop the cluttering of page. Also interested users can click on more link and see the full content. Here is a simple tutorial to achieve this using jQuery / Javascript.

The HTML

Below is the sample text. Each text is wrapped in a DIV tag. Note that we have added a class “more” in each div. This class will decide if a text needs to be shortened and show more link showed or not.
<div class="comment more"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum laoreet, nunc eget laoreet sagittis, quam ligula sodales orci, congue imperdiet eros tortor ac lectus. Duis eget nisl orci. Aliquam mattis purus non mauris blandit id luctus felis convallis. Integer varius egestas vestibulum. Nullam a dolor arcu, ac tempor elit. Donec. </div> <div class="comment more"> Duis nisl nibh, egestas at fermentum at, viverra et purus. Maecenas lobortis odio id sapien facilisis elementum. Curabitur et magna justo, et gravida augue. Sed tristique pellentesque arcu quis tempor. </div> <div class="comment more"> consectetur adipiscing elit. Proin blandit nunc sed sem dictum id feugiat quam blandit. Donec nec sem sed arcu interdum commodo ac ac diam. Donec consequat semper rutrum. Vestibulum et mauris elit. Vestibulum mauris lacus, ultricies. </div>
Code language: HTML, XML (xml)

The CSS

Below is the CSS code for our example. Note the class “.morecontent span” is hidden. The extra text from the content is wrapped in this span and is hidden at time of page loading.
a { color: #0254EB } a:visited { color: #0254EB } a.morelink { text-decoration:none; outline: none; } .morecontent span { display: none; } .comment { width: 400px; background-color: #f0f0f0; margin: 10px; }
Code language: CSS (css)

The Javascript

Below is the Javascript code which iterate through each DIV tags with class “more” and split the text in two. First half is showed to user and second is made hidden with a link “more..”. You can change the behaviour by changing following js variables.
  • showChar: Total characters to show to user. If the content is more then showChar, it will be split into two halves and first one will be showed to user.
  • ellipsestext: The text displayed before “more” link. Default is “…”
  • moretext: The text shown in more link. Default is “more”. You can change to “>>”
  • lesstext: The text shown in less link. Default is “less”. You can change to “<<"
$(document).ready(function() { var showChar = 100; var ellipsestext = "..."; var moretext = "more"; var lesstext = "less"; $('.more').each(function() { var content = $(this).html(); if(content.length > showChar) { var c = content.substr(0, showChar); var h = content.substr(showChar-1, 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; }); });
Code language: JavaScript (javascript)

Online Demo

Click here to view demo

Update

The above code is modified into jQuery plugin. Also it has now been enhanced. HTML tags are now parsed properly within text to preserve its uniformity while shorting the text. Please check latest plugin code on GitHub. https://github.com/viralpatel/jquery.shorten

Download Source Code

Click here to download (ZIP, 2KB)

jQuery Plugin

Code

/* * jQuery Shorten plugin 1.0.0 * * Copyright (c) 2013 Viral Patel * //www.viralpatel.net * * Dual licensed under the MIT license: * http://www.opensource.org/licenses/mit-license.php */ (function($) { $.fn.shorten = function (settings) { var config = { showChars: 100, ellipsesText: "...", moreText: "more", lessText: "less" }; if (settings) { $.extend(config, settings); } $(document).off("click", '.morelink'); $(document).on({click: function () { var $this = $(this); if ($this.hasClass('less')) { $this.removeClass('less'); $this.html(config.moreText); } else { $this.addClass('less'); $this.html(config.lessText); } $this.parent().prev().toggle(); $this.prev().toggle(); return false; } }, '.morelink'); return this.each(function () { var $this = $(this); if($this.hasClass("shortened")) return; $this.addClass("shortened"); var content = $this.html(); if (content.length > config.showChars) { var c = content.substr(0, config.showChars); var h = content.substr(config.showChars, content.length - config.showChars); var html = c + '<span class="moreellipses">' + config.ellipsesText + ' </span><span class="morecontent"><span>' + h + '</span> <a href="#" class="morelink">' + config.moreText + '</a></span>'; $this.html(html); $(".morecontent span").hide(); } }); }; })(jQuery);
Code language: JavaScript (javascript)

Download

Click to download jQuery Shorten plugin

Usage

Step 1: Include the jQuery plugin in your HTML
<script type="text/javascript" src="https://www.viralpatel.net/demo/jquery/jquery.shorten.1.0.js"></script>
Code language: HTML, XML (xml)
Step 2: Add the code to shorten any DIV content. In below example we are shortening DIV with class “comment”.
<div class="comment"> This is a long comment text. This is a long comment text. This is a long comment text. This is a long comment text. This is a long comment text. </div> <script type="text/javascript"> $(document).ready(function() { $(".comment").shorten(); }); </script>
Code language: HTML, XML (xml)
You may want to pass the parameters to shorten() method and override the default ones.
$(".comment").shorten({ "showChars" : 200 }); $(".comment").shorten({ "showChars" : 150, "moreText" : "See More", }); $(".comment").shorten({ "showChars" : 50, "moreText" : "See More", "lessText" : "Less", });
Code language: JavaScript (javascript)
Get our Articles via Email. Enter your email address.

You may also like...

152 Comments

  1. Jay says:

    Nice, although maybe you should think about making it a plugin instead to allow reuse and configuration options. Something like http://pastie.org/1416794 (your code as a plugin, with reservations for jQuery-plugin-best-practise-abuse…)

    • @Jay – fantastic :) I will update the post with jQuery plugin information. Thanks for that.

  2. karly says:

    Hi, I noticed that whenever there’s a … and you click “More”, there’s a gap between the character, which would split up a whole word. Is there any way to fix that? Thanks!

    • @karly – wow! thanks for pointing out the space issue. I have updated the script. Thanks again. Have a look :)

  3. What awesome site!!!!!!!!! Help me very much on the form enhancement!! Thanks guys!!!

    • sundar says:

      Yes good

  4. Jason Rastovski says:

    Nice work -> The only change I had to make to this was to make sure that the split doesn’t occur within an HTML tag. For example, if you had some text that was wrapped with a “strong” tag, and the split ends up being in between the “o” and the “n” in the html tag, that tag would be broken. I changed it so that the code looks for a closing bracket (“>”) before an opening bracket (“<") in the 'remainder text'. If it is, it adds one to the number of characters to show & tries again.

    • Steve says:

      Hey Jason any chance you could share your solution for not breaking html? Thanks.

      • Osama Ahmed Momin says:

        I am also facing the same problem, if there are html tags, more link doesn’t show at all. is there any way we can solve this issue. kindly please reply me.

    • Gunita says:

      Hey Jason, could you share that code update with us…facing the same issue!!!

    • gi says:

      Anybody managed to find/write what Jason is talking about?

      Would really appreciate the implemented code. :)

      Thanks.

      g

    • Mehak says:

      Please share code, as I am facing same issue

      Thank you
      Mehak

  5. Steve says:

    Thanks for the code works pretty great for me.

    I was wondering if anyone has/knows the best way to modify the function to hide a previously shown section when a new section has been clicked.

    thanks again for the example!

  6. julie says:

    In your three examples it doubles the letter where the eclipse sits
    so instead of displaying the correct word ‘sagittis’ it display ‘saagittis’.

    Is there a quick way to fix this?

    • julie says:

      move the   and remove the -1 from showChar

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

      var html = c + ”+ellipsestext+” + h + ‘   ‘+moretext+’‘;

  7. julie says:

    Also may I see an example using the plug-in as this does not seem to work for me.
    Great work by the way.

  8. shibbir says:

    Thanks a lot man.

  9. Seyed says:

    nice plugin…

    Is there any option to customize the style of the more/less text with css..

    i don’t the read more or less text as a standard link..

  10. Landi says:

    Patel,
    works great so thank you! I have one possible request: is it possible to save /show the break lines (br) ?? Looking at the source it shows correctly:
    line one
    line two
    line three

    but in display I get: Line one. Line two. Line three.

    Thanks

  11. Jagan says:

    I am not sure, why the plugin isn’t working for me.

    The HTML tutorial works.

    In your html turorial you have included a seperate file called

    jquery-latest.js

    which is not present in the plugin, i think this may be the reason, what do you think

    • @Jagan – This is a JQuery plugin and the file that I have included jquery-latest.js is the jquery javascript. You can include this js file as I have done in the tutorial or you can download it and include it statically in HTML.

  12. Pratheepa says:

    Nice

  13. Michael says:

    Great tutorial, just what I need. However, although it works in shortening my text and adds the ‘…’, the ‘more’ link is not appearing at all. Any ideas why this might be?

    Thanks in advance for any help!

  14. Stephanie says:

    Tutorial is not working for me and not sure why? All text is showing on the page but seems as though the scripting language is not picking up because the more and less are not there and all the text is still showing when I text preview??? Not sure what I am missing?

  15. Hi, I’ve changed the plugin a little to solve the tag cutting problem:

    http://pastebin.com/svRPehJJ

    Hope that helps.

    Cheers,
    Pablo Pazos
    http://code.google.com/p/yupp/

    • gi says:

      Thank you Pablo!
      Most helpful. :)

    • gi says:

      Hi,

      For those who are interested:

      I’ve tweaked Pablo’s code to remove the tags in the shorten text, so that the ‘… Read more’ appears next to the text and not on a new line.

      I also removed extra   spaces that were causing the full text to have a white space and a repeated letter in the breaking point.

      You can find the js code here: http://pastebin.com/ARTYQUuc

      g

      • james says:

        Great work guys! Thank you so much!

    • Patrick says:

      Thanks Pablo! Here is a Coffeescript version in case others also find it useful for maintainability:
      http://pastebin.com/ATBV1KuY

    • Mike says:

      !Gracias tambien¡

    • Pablo,
      Thanks for the changes. This is indeed very useful. I have pushed the plugin to GitHub and with your changes. Hope this will be useful for other users. Please feel free to fork and improve this tiny little plugin.

  16. Yasir says:

    This doesn’t work in a table

  17. Yasir says:

    It turns out that due to some content being loaded through ajax, the .live() function was attaching two events to the ‘show more’ link which fired the click event as soon as the it was clicked. Hence showing and then hiding suddenly, giving impression that it isn’t working.

    Just add this
    $(‘.morelink’).die();

    before
    $(‘.morelink’).live(‘click’, function(){ …..

    • Apu says:

      Thanks Yasir
      I was facing the same issue.

    • serve_this says:

      Thanks Yasir. I spent 2 hours trying to find an answer. Fixed!

  18. Erasmus says:

    I want to know if I may accept that all jQuery Code (Plugins etc) is Open Source and or Free to use for personal or commercial use? Thanks.

  19. Ushang says:

    The above doesnt work if the text comes from database using a php statement. Please help !!

  20. steve says:

    Add animation please

    • Hi Steve, to add animation just replace toggle() method in plugin with toggle("slow"). I will update the plugin code with this change.

  21. Josh says:

    Has anybody figured out a solution for if the content contains HTML like list items or other tags it doesn’t seem to work if it’s not just plain text.

    • Hi Josh, Its working for me! The content can be HTML. I have added a few links, divs and bold tags and it seems to be properly working.

      • Carla says:

        Hi Viral Patel, I have the same problem as Josh, the content contains HTML like list items or other tags and it doesn’t seem to work if it’s not just plain text.

  22. Eric Zipp says:

    Using ‘jquery-1.8.1.min.js’, trying to create the ‘shortening’ (more/less) for text, displaying 115 characters. (also seem to have the same problem with ‘jquery-latest.js’)

    Refer to : http://test.executivecaliber.com/moreless.htm for my test page, you can see at the junction of the displayed vs. no-displayed when you click MORE.

    Paragraph one: “work” becomes “work..”
    Paragraph two: “Moroc…” becomes “Moroc cco” Etc.

    If I should be using a different jquery script… (or some other problem) please let me know.

    Thank you,

    Eric S. Zipp

    • Eric Zipp says:

      May discovered a workaround/fix…. at the bottom of the test page I have changed the script from:
      var h = content.substr(showChar-1, content.length – showChar);
      …to…
      var h = content.substr(showChar, content.length – showChar);
      (this was mentioned in a previous post by Julie)

      …and removed the ” ” from between this
      (see pointer below)
      |
      |
      v
      var html = c +”+ellipsestext+” + h + ‘  ‘+moretext+’‘;
       

      Since I “don’t speak Java”… if I have shot myself in the foot by doing this… someone please let me know.

      thanks

      Eric

  23. Raj says:

    The plugin works like a charm. Thank you :)

    I have one question:
    Why do we need the below line :
    $this.parent().prev().toggle();

    even though I comment this, the plugin works fine.

    Raj

  24. Melissa says:

    This works great except . . . it’s backwards for me! When page is loaded all text shows with “more” link. When I click on “more” it collapses to show only 100 characters and then says “Less”. I’m not using the plugin, as I only need it for a single page. I’m a JS noob – any help?

  25. Blaine says:

    I tried using this on my wordpress site. Is there a way this would work for a single page in wordpress?

  26. Velmurugan says:

    My content also has html tags.. by this code wont work with that..

  27. Can says:

    @Melissa, I’ve been experiencing the same thing.. I was trying to figure out why this is working like that.

  28. Can says:

    @Melissa, ok I’ve just found the reason.. It is working in a div with {display: block; } style, I’ve removed this and now it works!.

    • Raymond Lobo says:

      Can, I have the same problem as Melisa and i dont understand what you mean in your solution.

      Can 1 November, 2012, 16:48
      @Melissa, ok I’ve just found the reason.. It is working in a div with {display: block; } style, I’ve removed this and now it works!.

      anyone care to elaborate or write me a how to?

      thanks.

  29. Vikalp says:

    It does not work when I use it for more than one element on a page. I get more/less links but nothing happens when I click them.

  30. Dennis says:

    Great job man! It workx without damage my SEO because of hidden text. The most scripts work with hidden hover of the hole content … its a good work … thanks a lot of!

  31. Debra says:

    Wish I understood this but it’s way over my head. I was just searching trying to find something to shorten my html or javascript code for affiliate links to use on facebook. I thought at first this might be the answer but I’m so confused at this point and think, instead, you might be talking about something else.! Wish I knew all you know about code, etc. I’m learning through trial and error at this point.
    Debra @ childrenswellbeingblog.com

  32. ross says:

    Hi,

    The css .morecontent isn’t doing what it needs to before the script loads?

    Hope you can help?

    Best,

    Ross

  33. Priyank says:

    Thanks a lot. saved my time :)

  34. David says:

    It looks nice in the demo, but this does not seem to be a solution for multi-heading and multi-paragraph articles–which is what I need to be able to truncate until the user clicks “more”. In my case, the span is applying to the title alone, leaving the rest of the article visible. It’s a start, though, so I might be able to modify this into something that will work.

  35. Iasin says:

    This works great but I would like the text to be viewed by readers, how would the code work with left screen content instead of hidden or something like .visuallyhidden {
    position: absolute;
    overflow: hidden;
    clip: rect(0 0 0 0);
    height: 1px; width: 1px;
    margin: -1px; padding: 0; border: 0;
    }

  36. D says:

    Has anyone given this a go within an asp:BoundField and ItemStyle-CssClass?

    It works but, the other boundfields in the row get thrown off. The text in those fields get dropped to the bottom of the row (almost like vertial-align:bottom) until you click on that cell in the GUI where it fixes itself.

    Thoughts?

  37. Azab says:

    Since live is deprecated in jQuery 1.9 have a look at this >> http://jsfiddle.net/dLRed/2/

    • Thanks Azab. I have updated the plugin code and replaced live() call with on(). Thanks.

  38. Raymond Lobo says:

    This works great except . . . it’s backwards for me! http://www.falconeye.com.my/management.html
    When page is loaded all text shows with “click to hide” link. When I click on “click to hide” it collapses to show only 200 characters and then says “click for more”.
    I’m a JS noob – any help?

  39. Jason says:

    doesn’t work for me if the content is being source from a .xml field. I have a {Complete_Description} that’s being sourced and no go any way to fix this?

    {Complete_Description}

  40. hira says:

    how to implement if I am populating div with mysql query, as jquery run before the div is populated, so its not displaying any content at default,on more link is shows whole content.
    code is like

    <div class="comment more">
    		<?php 
    		foreach($result as $val)
    		{
    		 $cnm = $cn % 5;
    		 if($cnm==0) {echo "</br>";}
    		 //echo $val;
    		?>
    		
    		<a onclick="add_key('<?php echo $val; ?>');" href="#"><?php echo $val.'&nbsp;'; ?></a> 
    		 
    	 	<?php $cn++;
    	 	} ?></div>
    

    • Jason says:

      can you elaborate on how to set this up? I tried to implement but i’m still having issues

  41. Sadly this doesn’t work in jQuery 1.9.1 – as toggle() is depreciated too!

    Can anyone suggest a workaround? I can’t find a replacement for this plugin which is 1.9.1 compatible.
    Thanks, Alex

    • Ken Parker says:

      Try to use slideToggle() instead. It should work.

  42. Sen says:

    It doesn’t work when you have any html tags in it.

  43. Mohiz Tank says:

    There is no perfect solution for the cutted html i think right now.
    what happens if want to add tables or images..????

  44. Mohiz Tank says:

    Best thing to do in case of HTML content is the height base solution.
    Show only fixed height and every thing else will be hidden so cases like images will also get solved.
    The real question is how to detect the height of the HTML content before applying the more-link so that it doesn’t get cut Awkwardly.

  45. Jeremy says:

    Plugin doesn’t work for me… Text gets shortened and show more link appears but nothing happens when you click link. Tried changing toggle to slideToggle as suggested above but still nada.

    tested with
    jQuery 2.0 and 1.72

  46. Smash says:

    Is it only me, that noticed then clicking on the “more” link, you got one or two letters duplicated.

    eget laoreet sa… more
    eget laoreet sa agittis, quam ……………. less
    and should be
    get laoreet sagittis, quam

    As you see there is a space and “a” – so acctually two chars

  47. Smash says:

    I belive I found your error in the code.

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


    Should be

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

    Unneeded  

  48. Priya Sharma says:

    Hi Viral,

    The code you have done has “moretext” in hyperlink format. When I’m trying it to do with button it is not working. I want to add a button beside the text instead of hyperlink and when we click on that button pop up window must open to view the full text. Can you help me on this..

    Thanks

  49. Saurabh says:

    code fails if content is having html tags.
    e.g

    contentText => "A lovely presentation of short stemmed roses in mixed pastel shades (12, OR 24 Please Select) and filler wrapped in cellophane and trimmed with a bow.<i><b> Picture shown contains 12 roses</b></i>."
    


    And now try this.. with following values..

     
        $(".comment").shorten({
                    "showChars": 160,
                    "moreText": "Read More"
                });
    


    it fails.. due to html tags..
    Any suggestion for this??

    Thanks in advance.. ;)

  50. Mark says:

    I also noticed that, in addition to some characters repeating at the split, (which another commenter noted, The code was dropping the last character of the “hidden” text.

    I changed the line

    var h = content.substr(config.showChars , content.length - config.showChars); 

    to

    var h = content.substr(showChar); 

    since javascript will return the rest of the string is no second parameter is passed to the substr() function

  51. Vijay Bharwani says:

    Hi,

    Nice tutorial. There is a problem in your script, that when you are splitting the full content in 2, when we clicking on more, the last letter of the first sub string is getting double.
    I mean before clicking on more, if ‘i’ is the last character , then if we click on more, it is showing 2 ‘i’. Please the 2 sub strings that u have made.
    The suggested behavior is

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


    insted of

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

  52. pradeep says:

    Hi, Nice code but not working in internet explorer version 9

  53. Vali Hutchison says:

    Similar problem for me as reported by others. If I have text in the shortener DIV with paragraph tags then it doesn’t work. It shows the less link with all the text first and then when you click the less link all the text disappears. Removing the tags makes it work – but be good to fix so can have paragraph tags.

  54. Luke says:

    Regarding your latest GitHub plugin, please don’t use off() and on() methods as these don’t work with the HTML5

    <article>

    tags ?

    • Luke says:

      Apologies, the plugin works fine with jQuery 1.8.3, but not v1.3 ;)

  55. Jen says:

    Hi,
    I’m getting some weird behavior with the jquery-1.9.1.min.js. The button appears and then is labeled display:none. Anyone else seen this?

    thanks
    Jen

    • Asd says:

      Yes I am facing the same issue. weird behaviour

  56. Ritu says:

    Hi

    The code is working but I have a problem that it is not working for label declared inside form view. Can any body help me?

    Thanks

  57. Sathish says:

    What if I have some html inside the div. If I have some tags, is it going to cut off. (lets say my 99th character is so as per your example is this going to cut off <i … more?)

  58. shaz says:

    Hi, nice plugin, I want to ask how to add jquery easing effect on clicking ‘more’ ‘less’ Thanx

  59. Chockolate says:

    Yes, nice plugin and good tutorial, but as soon as there’s any markup in the div, it falls apart.

    • JustAGuy says:

      I added a quick hack to only break after a closing tag.

      Something like this: (to only break after a tag)

      poffset = content.substr(config.showChars, content.length – config.showChars).indexOf(“”) + 4;
      var c = content.substr(0, config.showChars + poffset);
      var h = content.substr(config.showChars + poffset, content.length – (config.showChars + poffset));

      • JustAGuy says:

        Trying again with formatting..

        poffset = content.substr(config.showChars, content.length - config.showChars).indexOf("</p>") + 4;
        var c = content.substr(0, config.showChars + poffset);
        var h = content.substr(config.showChars + poffset, content.length - (config.showChars + poffset));
        

  60. Jacques says:

    Too bad this doesn’t work with dynamic data (text) from a database

    • pyretta says:

      Hello Jacques,
      it’s not true, that it doesn’t work with dynamic text taken from a database. If you use a serverside language like php to dynamically create content, the text you want to shorten would be created before any JS is loaded. So it would be no problem to shorten your dynamic text. But I think, if you use clientside language in a synchronous way, it won’t work, because the text you want to shorten can’t be find from the shorten script when it loads. Maybe it works with an asynchronous script, but I didn’t test it. Sorry for my possibly poor English, it’s not my native language, but I hope you can understand it anyway.

      @Viral Patel: Many, many, many thanks for this great script & tutorial!! It is awesome!

  61. heidi says:

    Very nice plugin, but could you add a speed control to this plugin?

  62. Rudy says:

    For me, this plugin only works in IE, not in Mozilla firefox or Chrome
    my jquery version is V1.7.1

    added var J = noconflict()

    any suggestions?

  63. bibil says:

    Hello, Thx for the tutorial!!
    Is it possible to add some animation to the text ? i struggled but couldnt find how…

    Many thx!!

    • Kelvin says:

      Yes. Search for hide() and show() and add “slow” in the brackets. e.g. hide(“slow”)…

  64. How i can shrink entire previous div if i am clicking on more link of
    next div or any div i.e div that is not selected for now should get
    shirked ..
    Thanks in advance

  65. Shawn says:

    I was looking for it since long time as i want to show not full content, since my page has long content. Thanks for sharing this useful resource with us.

  66. Hoffman says:

    Hi,
    I wanted to use the plugin on a wordpress website but it turn out the plugin is not working can you please help me on how i can integrate in to work with wordpress.
    Best regards

  67. Anitha Krishana says:

    I have been trying to develop this as part of my php jquery training assignment with no success. but this tutorial helped me to get the assignment in few minutes. Just to note, i am new to php and jquery. thank you so much for detailed explanation.

    -Anitha

  68. Neil says:

    nice plugin !!!
    but how to change more and less text into image..
    thankx in advance…….

  69. fyeth says:

    Hi there, thanks for a nice plugin. Its working but don’t know how to align “more” to the same line as the elipses like your samples. Mine looks like this.

    some text…
    more

    What I want is

    some text … more

    • SyberKnight says:

      agreed!
      this code is awesome, but i’d really like to figure out a way to have the break occur between words rather than only have one or two characters of the next word show before the ellipse.

      i found this on his/your github site that showed promise…
      https://github.com/lucian-lcr/jquery.shorten/commit/ff76f02ce75bcc122084c0db0745e5319f4b12f4?diff=unified
      …but unfortunately, it does not provide an appropriate fix (for us).

      i’m not very knowledgeable in javascript but will try to play with it & see what i can do. BUT would totally appreciate somebody who is knowledgeable to provide a solution.

      additionally, i was hoping for some jquery animation too, and found the post to change all the…
      show(); and hide();’s to show(“slow”); and hide(“slow”);
      …but when my block is at the bottom of a page, it does something funky & undesirable.

      .peace.

    • SyberKnight says:

      to the moderator… why did you delete my post?
      i replied here just trying to be helpful as well as post my questions.

  70. mohamed says:

    HI there it is possible to make us a video tutorial about Shortened Text With “Show More” Link Using JQuery and html and olso to use asp.net sory for

  71. Sandeep says:

    if there is link in the text, it’s showing the link path

  72. pyretta says:

    Hi there,
    again: Many thanks to Viral Patel for this awesome Plugin!
    If someone wants to use this plugin with more than one HTML-Element to show/hide and don’t want to click on a little button or something, here is my work around.
    The HTML structure:

    <div class="showmore">
        <div class="left_img">
            <img src="someimage.jpg" alt="someimage" title="someimage" />
        </div>
        <div class="shorten_txt">
        	<h1>Lorem ipsum dolor sit amet</h1>
            <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies.</p>
            <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies.</p>
            <ul>
                <li>Lorem ipsum dolor sit amet</li>
                <li>consectetuer adipiscing elit</li>
            </ul>
        </div>
    </div> 

    The jQuery JS:

    var showChar=50;
    	var ellipsestext="[...]";	
    	$('.showmore').each(function(){		
    		$(this).find('.shorten_txt p').addClass('more_p').hide();
    		$(this).find('.shorten_txt p:first').removeClass('more_p').show();
    		$(this).find('.shorten_txt ul').addClass('more_p').hide();
    //you can do this above with every other element
    		var teaser = $(this).find('.shorten_txt p:first').html();
    		var con_length = parseInt(teaser.length);
    		var c = teaser.substr(0, showChar);		
    		var h = teaser.substr(showChar, con_length - showChar);
    		var html = '<span class="teaser_txt">'+c+'<span class="moreelipses">'+ellipsestext+
    		'</span></span><span class="morecontent_txt">'+h
    		+'</span>';				
    		if(con_length > showChar){			
    			$(this).find(".shorten_txt p:first").html(html);
    			$(this).find(".shorten_txt p:first span.morecontent_txt").toggle();			
    		}		
    	});	
    	$(".showmore").click(function(){
    		if($(this).hasClass("less")){
    			$(this).removeClass("less");
    		}else{
    			$(this).addClass("less");
    			}
    		$(this).find('.shorten_txt p:first span.moreelipses').toggle();
    		$(this).find('.shorten_txt p:first span.morecontent_txt').toggle();
    		$(this).find('.shorten_txt .more_p').toggle();
    		return false;
    	});
     

    Now you just have to click on anywhere inside the “showmore” div and the teasertext will be shortened or will be enlarged. This is useful if you want it to use with mobile phones and touchscreens.

    best regards,
    pyretta

    • andy says:

      Pyretta, can you then style the “[…]” so it’s say bold and a colour?

      • andy says:

        Sorry, sorted.
        .moreelipses {
        font-weight:bold;
        color:#FF0000;
        }

  73. Manuel says:

    I´ve just modified your code becuase i had problems with html contents.

    Now instead of cutting and adding what function have cutted, function now cuts and shows this content at first and then when clicking “more” button it shows whole content.

    $(function(){
    	$.fn.shorten = function (settings) {
    	
    		var config = {
    			showChars: 100,
    			ellipsesText: &quot;...&quot;,
    			moreText: &quot;more&quot;,
    			lessText: &quot;less&quot;
    		};
    
    		if (settings) {
    			$.extend(config, settings);
    		}
    		
    		 $(document).on({click: function (){
    		 
    			var $this = $(this);
    				if ($this.hasClass('less')) {
    					$this.removeClass('less');
    					$this.html(config.moreText);
    					$('.morecontent').fadeOut(function(){
    						$('.lesscontent').fadeIn();
    						$('.moreellipses').show();
    					});
    				}else{
    					$this.addClass('less');
    					$this.html(config.lessText);
    					$('.lesscontent').fadeOut(function() {
    						$('.morecontent').fadeIn();
    						$('.moreellipses').hide();
    					});
    				}
    			}
    		}, '.morelink');
    
    		return this.each(function () {
    			var $this = $(this);
    			if($this.hasClass(&quot;shortened&quot;)) return;
    			
    			$this.addClass(&quot;shortened&quot;);
    			var content = $this.html();
    			if (content.length &gt; config.showChars) {
    				var c = content.substr(0, config.showChars);
    				var html = '&lt;span class=&quot;lesscontent&quot;&gt;'+ c + '&lt;/span&gt;&lt;span class=&quot;moreellipses&quot;&gt;' + config.ellipsesText + ' &lt;/span&gt;&lt;span class=&quot;morecontent&quot;&gt;' + content + '&lt;/span&gt; &lt;a href=&quot;#&quot; class=&quot;morelink&quot;&gt;' + config.moreText + '&lt;/a&gt;';
    				$this.html(html);
    				$(&quot;.morecontent&quot;).hide();
    			}
    		});
    		
    	};
    
     });
    

  74. Manuel says:

    IM SORRY didn´t modified the post source code tag XD

    $(function(){
    	$.fn.shorten = function (settings) {
    	
    		var config = {
    			showChars: 100,
    			ellipsesText: &quot;...&quot;,
    			moreText: &quot;more&quot;,
    			lessText: &quot;less&quot;
    		};
    
    		if (settings) {
    			$.extend(config, settings);
    		}
    		
    		 $(document).on({click: function (){
    		 
    			var $this = $(this);
    				if ($this.hasClass('less')) {
    					$this.removeClass('less');
    					$this.html(config.moreText);
    					$('.morecontent').fadeOut(function(){
    						$('.lesscontent').fadeIn();
    						$('.moreellipses').show();
    					});
    				}else{
    					$this.addClass('less');
    					$this.html(config.lessText);
    					$('.lesscontent').fadeOut(function() {
    						$('.morecontent').fadeIn();
    						$('.moreellipses').hide();
    					});
    				}
    			}
    		}, '.morelink');
    
    		return this.each(function () {
    			var $this = $(this);
    			if($this.hasClass(&quot;shortened&quot;)) return;
    			
    			$this.addClass(&quot;shortened&quot;);
    			var content = $this.html();
    			if (content.length &gt; config.showChars) {
    				var c = content.substr(0, config.showChars);
    				var html = '&lt;span class=&quot;lesscontent&quot;&gt;'+ c + '&lt;/span&gt;&lt;span class=&quot;moreellipses&quot;&gt;' + config.ellipsesText + ' &lt;/span&gt;&lt;span class=&quot;morecontent&quot;&gt;' + content + '&lt;/span&gt; &lt;a href=&quot;#&quot; class=&quot;morelink&quot;&gt;' + config.moreText + '&lt;/a&gt;';
    				$this.html(html);
    				$(&quot;.morecontent&quot;).hide();
    			}
    		});
    		
    	};
    
     });
    
    

  75. Krishnakant Bhadoria says:

    Hi ,

    I am using shorten.js in my application for read more feature.However,I want to change the color of ‘Read More’ link after being visited.I tried changing the color for this link using ‘morelink’ class ,but it is not working fine.Can anyone please suggest a solution for this..

  76. Louis says:

    I want to display all the text but have the option of shortening it. How do I call that?

  77. Rhys says:

    I’m having the same issue as another poster where the “Read more” link is showing up on a different line rather than at the end of the text as displayed in the samples.

    Current:
    Lorem ipsum dolor sit amet…
    Read more

    Desired
    Lorem ipsum dolor sit amet… Read more

  78. Natty says:

    This doesn’t work for nested elements. Any fix on that.

  79. Rob says:

    It seems to miss numbered lists from the hidden section.

    It works ok with bulleted lists but not numbered lists.

    Please advice.

  80. bm says:

    it’s not working

  81. imesh says:

    this doesn’t work for any browser.

  82. Roman says:

    It will be better to store separate config for each element, because I use different more and less words on one page, and after expanding/collapsing the more/less text is being override by last configured text

  83. Shravan says:

    This is not working when the text contains anchor tags .please verify the same by adding some anchor tags ,coz apsn tags are been added in anchor tag ,hence making the function not working

  84. Sangram Desai says:

    Need to set height:auto in jquery.shorton.js like below that is height:’0’+’%’ not working properly.so i done like
    $this.parent().prev().animate({‘height’:’auto’}, function () { $this.parent().prev().prev().show(); }).hide(‘fast’);

  85. Sangram Desai says:

    $this.parent().prev().animate({‘height’:’auto’}, function () { $this.parent().prev().prev().show(); }).hide(‘fast’);

  86. Laura says:

    Is there any way to modify the code so that the ‘more’ button shows at the end of a word as apposed to the amount of characters? I can’t have the words being broken up. Any ideas what I would need to change this code to? {var showChar=200;

    Thanks

  87. Dampas says:

    Hi,

    the problem with formatted text is that this code breaks up the container.
    Put this in code, that will resolve the problem for most of the cases:

    var $type = $(this).prop('nodeName');

    And then change this line:

    var html = c + '' + config.ellipsesText + ' ' + h + '' + config.moreText + '';

    Use this code to not break on paragraph tag (copy that to everything else – it will be nice to check up the .html to find out if we are in opening or closing tag and bail out of that, but I don’t have that much time):

    poffset = content.substr(config.showChars, content.length - config.showChars).indexOf("") + 4;
    var c = content.substr(0, config.showChars + poffset);
    var h = content.substr(config.showChars + poffset, content.length - (config.showChars + poffset));

    And use CSS coding for link and ellipses placement (it is at the top – play with it).

  88. Dampas says:

    What is the code tag?!? How can I add code with formatting?

  89. Sigurd says:

    Thank you very much, you save me lot of time!

  90. Adhiraj Mukherji says:

    Hi,

    I added this code to my wordpress site, when i click on more the entire text is disappearing and only the ‘less’ link is showing, any idea why this is happening? any help will be appreciated.

    Thanks.

  91. Andreas says:

    I’ve been trying to get this to work with a pre v 1.7 jQuery (sadly we are using an older version of the UI framework ZK, that comes with jQuery 1.6.4) and found that all that needs to be changed is:

    $(document).off(“click”, ‘.morelink’);

    changes to

    $(‘.morelink’).die(“click”);

    and

    $(document).on({click: function() {…}, ‘.morelink’);

    changes to

    $(‘.morelink’).live({click: function() {…}});

    In case anyone else is stuck with some ancient jQuery ;)

  92. Gabe says:

    Hi
    I have integrated your code to a website and it is working well but the performance are not good: It took 1-2sec to open/close a text. And I notice a small CPU peak when clicking on the more/less link, on Chrome/Windows 7. It should be because of the “animate”
    On the demo link on this page, the action is so much faster, but it doesn’t actually use this library!
    Can we disabled the animation more or less like it is on this demo ?
    Thanks

  93. Schalk says:

    Hi, Thank you so much for this, exactly what I was looking for!
    One change I hope to make though. I would like to place the “more” link where ellipses is.
    Can you put me in the right direction, please.

  94. Ant says:

    Anyone Know how to make it slide up and down slowly ?

  95. Strahinja says:

    Hey guys, Can somebody tell me where can I find some code for this problem but written in angularJS 2? I can’t find any solution similar to this but in angular? Any help would be appreciated. THx

  96. Ben says:

    I wanted the break to occur between words, so I added this to the JavaScript:

    $(document).ready(function() {
    
            var ellipsestext = "...";
            var moretext = "mehr lesen";
            var lesstext = "einklappen";
            $('.more').each(function() {
    var showChar = 250;
    
    
                var content = $(this).html();
    
                if(content.length > showChar) {
    
                    var checkSpace = content.substr(showChar-1, showChar - showChar +1);
                    while (checkSpace != ' '){
                        showChar = showChar+1;
                        checkSpace = content.substr(showChar-1, showChar - showChar +1);
                    }
    
                    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;
            });
        });
    

  97. Manju says:

    HI , I am facing a small issue with this. This piece of code works brilliantly well if we are trying to show more/less in case of texts. But I am trying a show more/less an anchor tag. With this script, the anchor tag is converted into plain text and it isnt a link anymore.

    Could anyone help me on this ?

  98. virender yadav says:

    Its very helpfull site for developer

  99. king khan says:

    Sir, how can we see hidden text like this *************? when we forgot facebook password and then we try to reset password with the help of mobile number. but facebook shows to me only two last digits of my mobile number like this ****************70 so how can we see complet number.plz help me.i shell be very thankful to you

  100. Tobi says:

    Worked well

  101. Wahid says:

    Thanks a lot bro! After 3 years, still does the job ;-)

  102. Khatas says:

    Any help if the text has Ul elements in the html.

  103. test says:

    hi,
    this code works good but we have an issue here, can anyone please help me on this..
    issue is:
    .morecontent span is displaying while page loading and hides after page load
    how can i fix this issue.

    thanks

  104. For a shortened script that works correctly by counting words instead of characters, this is the code, adapted from http://stackoverflow.com/questions/33175833/shortening-long-blocks-of-text-based-on-words-not-characters- To-display-to-read-m ::

    */

    (function($) {
    $.fn.shortenwords = function (settings) {

    var config = {
    maxWords: 100,
    ellipsesText: "...",
    moreText: "more",
    lessText: "less"
    };

    if (settings) {
    $.extend(config, settings);
    }

    $(document).off("click", '.morelink');

    $(document).on({click: function () {

    var $this = $(this);
    if ($this.hasClass('less')) {
    $this.removeClass('less');
    $this.html(config.moreText);
    } else {
    $this.addClass('less');
    $this.html(config.lessText);
    }
    $this.parent().prev().toggle(1200, "linear");
    $this.prev().toggle();
    return false;
    }
    }, '.morelink');

    return this.each(function () {

    var $this = $(this);
    if($this.hasClass("shortened")) return;

    $this.addClass("shortened");
    var words = $(this).text().replace(".", ". ").replace(",", ", ").split(" ").filter(function(a){return a.trim()});

    var arr = [];
    var index = 0;

    for(var i=0;i<words.length && arr.length+1 config.maxWords ) {
    var c = words.slice(0,index).join(" ");
    var h = words.slice(index, words.length).join(" ");
    var html = c + '' + config.ellipsesText + '  ' + h + ' ' + config.moreText + '';
    $this.html(html);
    $(".morewords span").hide();
    }
    });

    };

    })(jQuery);

  105. Tony Solserpiente says:

    Sorry, I forgot it.
    To pass the parameters to new shortenwords function:

    $(selector).shortenwords({
    "maxWords" : 20,
    "moreText" : "more",
    "lessText" : "less",
    "ellipsesText" : "..."
    });

  106. muniyandi says:

    its helpful thanks

  107. Yoftahie Suleiman says:

    Thank you.This is great article except for one minor correction
    in the $(‘.more’).each(function () {, when you assign value to variable h
    var h = content.substr(showChar – 1 , content.length – showChar);
    this duplicates the last character before read more. Eg. instead of “id” it displys iid.
    it can be fixed by code below,
    var h = content.substr(showChar , content.length – showChar);

  108. r k singh says:

    This code is not working on multiple paragraph or div tag.

  109. Simy says:

    Fab work, very impressive.
    Much appreciated.

  110. safari mupe says:

    Sorry for the disturb, I would like to use the script for a dynamic content got from Jquery only. I have a loop on json data from jquery and I display it dynamically by appending to . I would like to use the same script on that data only, I know it might request to embed the entire script in a function and call that function in each li. something like , var prg = ”+functMore(json.data)+”;
    I can;t handle that easily. Can anyone provide an answer.
    this is my full code.
    $.ajax({
    type: ‘GET’,
    url: $(“#baseurl”).val() + “post/getData”,
    success: function (json) {
    $(“#postSec”).html(“”);
    if (json.status) {
    if (json.data.length > 0) {
    for (var rec=0; rec<json.data.length; rec++){

    var exp = '’;

    exp += ”+
    ”+json.data[rec].postContent+”;

    exp =+ ”+
    ”+
    ”;
    $(“#postSec”).append(exp);
    }
    }
    }
    }
    });

  111. safari mupe says:

    the tags are being removed, so I replace with
    if (json.status) {
    if (json.data.length > 0) {
    for (var rec=0; rec<json.data.length; rec++){
    var exp = "”+json.data[rec].postContent+””;
    $(“#postsec”).append(exp);
    }}}

  112. Remy says:

    you made my day

  113. Mehak says:

    Hi

    I am facing issue in this plugin, I have text with html listing tags but it breaks so my load more functionality does not work, can you please help.

    Thank you
    Mehak

  114. Tomasz says:

    How do you put 4 different show-hide on the home page?
    I changed .truncate to .truncate1 etc. – now the content opens for me, but it also hides immediately.

  115. gavi says:

    i made the div element and it works fine when i use normal text, but i tried to add some sql (inside php) to show a value of something in a sql table, but when i load the page it just says “more” and when i click it, it loads the value from the sql, but it is supposed to just shrink the value and then when you click more it is supposed to show the rest instead it shows nothing and then when you click “more” it shows all of it, this is because the sql is only loading after the js has run, trying to find a fix, please email me back, thanks

  116. phptechie says:

    This is very helpful article for me.I have been looking for such a content that helpful to me.

Leave a Reply

Your email address will not be published. Required fields are marked *