Interested in purchasing one of the best wordpress themes in town? check out Cult on themeforest »

tuncatable

I wrote an article a while ago called “the anatomy of a jQuery plugin“, since then I have written a few jQuery plugins of my own, which I would now like to share with you. The first in the series is called ‘truncatable‘. Simply put truncatable is a lightweight truncation plugin for jQuery. Designed for users who want to be able to hide and expand text on a page. This plugin is very SEO friendly, and ideal for environments where it is not possible to use PHP.

demo jQuery truncatable plugin

download

Usage

To use the plugin simply add an id or class to the text that you would like to truncate:

<p class="myClass">
 Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Etiam fringilla, purus a ultrices blandit,
 odio ante scelerisque neque, vitae imperdiet odio velit ac nisl. Sed tortor metus, placerat condimentum,
 feugiat in, feugiat adipiscing, mi. Donec pulvinar sem vitae leo. eget lectus et ligula hendrerit
</p>

You will need to  call the plugin in the head of your document. Please note that you will will need to include jQuery before you call the plugin:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script type="text/javascript" src="jquery.truncatable.js"></script>

To initate the plugin simply call it on your class like so:

$(function {
  $(".myClass").truncatable();
});

Options for truncatable

truncatable enables the user to define the limit of letters to be displayed on the truncatable plugin. As a default 100 words will be display unless you specify otherwise like so:

$(".myClass").truncatable({limit: 200});

Demo

To see the plugin in action why not check out the demo. I have tested the plugin and can confirm that it runs on the lastest version on jQuery(V1.3.2) and works on IE Safari and Firefox. Happy coding!

Version History

05/08/2009 – Version 1.0

20/08/2009 – Version 1.2

Since I recieved so much  great feedback I have updated my plugin with a few of additional features and fixes. currently at 1.1. You can now:

  • Display a link to hide the text once you have expanded it. As well as defining what that text says.
  • Intelligent truncation, The plugin now completes the last word before truncation commences.

To apply these new features simply download the latest version of the plugin above and apply these additional parameters:

$('.myClass').truncatable({    limit: 200, more: '.....', less: true, hideText: '[hide]' });

    About the author

    My name is Philip Beel. I have four years commercial experience in front end web development. My disciplines include XHTML, CSS, PHP, MYSQL, Smarty and javascript. I am also a keen advocate of the jQuery framework.

    Read more posts by


    64 Comments on Truncatable – A jQuery plugin

    1. Paul Ashton

      Looks useful. Much better than my .net hack I had to produce last year! Will be using. Is there any way for it to round whole words only?

      « Reply


    2. philipbeel

      Thanks Paul, its definitely something I can look into doing! Watch this space

      « Reply


    3. Rick Ratayczak

      It would also be nice if.. within a tolerance, it would stop at the previous period (end of a sentence) too.

      « Reply


    4. Jesse

      It would be great if you could also show less of it after expanding the text, your demo doesn’t seem to be able to do that

      « Reply


    5. Beau Smith

      Great start, but there are two important things missing:

      1. This plugin needs to trim the string as all spaces before and after the string are counted.

      2. If there is any html in the string, this will duplicate part of the html string if the truncation occurs within an html tag block.

      « Reply


    6. philipbeel

      Thanks for all the suggestions guys! I’m prototyping a new version which will offer more features and functionality. I will update this post when its launched!

      « Reply


    7. Graham Sanders

      Just what I was looking for. Thank you.

      « Reply


    8. Ashraf

      Hi, Thanks for the plugin it is working just fine and it is the only one I found that I can apply to multiple classes across the same HTML. I have one question though, can you make an option to disable the expansion of the text?? in other word what ever I choose for the more option, just shows but not as a link? I want to use the plug in on a site I’m coding now where I will use it on the archive listing pages where I want to truncate the titles and descriptions of the different articles and I do not want to show the hidden text (though want to keep hidden on the page for SE) if the user chooses to know more he will then have to click the title (even if truncated) to go the article page.
      I’m new to JQuery plugins development – still finding my way around – and would need your help to customize the plugin to act as I stated above.

      Thanks again for the plugin and awaiting your reply.

      « Reply

      philipbeel Reply:

      @Ashraf – Thanks for your comment. You could bypass your problem by wrapping your individual truncated text elements in an anchor links. this might be a more usable way to navigate to pages. Alternatively you could modify the plugin, but it would need to be dynamic enough that it would know what page your link needed to go to. However I am afraid this would take it out of scope for a general release. I hope this helps.

      « Reply


    9. Mikael

      Excellent! I only have one problem with it. I’m using this for the tags below each post on a blog. The tags are surrounded by elements. Truncatable counts the chars in the tags which makes it hard to calculate after how many chars it should clip the content. If I set the char limit so that it clips right inside an element (this happens in some posts as the tags bound to a post differs from post to post) it prints out unformatted html, like: rel=”tag”>
      http://henrik.nyh.se/2008/02/jquery-html-truncate doesn’t do this but instead it doesn’t recognize words like Truncatable and clips them hard. Perhaps you could borrow some code from Henrik Nyh.

      « Reply


    10. Mikael

      WordPress seems to have messed with the formatting of my comment. Here it is in better shape: http://pastebin.com/f11c7d3e0

      « Reply

      philipbeel Reply:

      @Mikeal – Thanks for the heads up I will look into fixing this in the next release! Much appreciated!

      « Reply


    11. mike

      If the truncatable is used on a string that looks like:

      Hello World

      and if the limit is set to 20, would I get

      Hello

      or

      Hello <a href="

      « Reply


    12. Mikael

      @philipbeel – Sounds great :)

      « Reply


    13. Ramin

      Hi, first of all, very nice plugin. However, your onclick handler for the ‘more’ link doesn’t return false, so the page scrolls up when you click on it. I would suggest returning false, just like you do for the ‘less’. Also, your code is missing a few semicolons here and there. I would suggest running it through jslint to make sure it is error free. Thank you and good luck!

      « Reply

      Vic Swift Reply:

      @Ramin, any chance you can tell me where to put the return false to stop the page scrolling?

      « Reply

      Ramin Reply:

      @Vic Swift, here are the errors found when I run it through jslint.com:
      http://gist.github.com/457242

      And here’s the code with the errors and warnings removed and the return false statement in the right place. The code formatting was removed when I downloaded it, so I had to run it through this first: http://jsbeautifier.org/

      http://gist.github.com/457245

      « Reply

      Vic Swift Reply:

      @Ramin, I worked it out in the end but wouldn’t have spotted the other stuff so big thanks for this.

      philipbeel Reply:

      Hi Guys, I am going to be updating the plugin soon so thanks for all the feedback it will make bug tracking a lot easier!


    14. Sallaboy

      Hi Philip,

      thanks for the great plugin. I’ve tried it for my site and then I realized that it didn’t work, I’ve started to troubleshoot and then find out that it wasn’t working because my “tags” were dynamically loaded.

      I solved it by changing the “bind” in your source to “live”.

      hope that I helped :-)

      « Reply

      philipbeel Reply:

      @Sallaboy, thank you for your feedback much appreciated, I will look at adding this revision into the next release, Thanks!

      « Reply


    15. Miz

      Is it possible to replace the text instead of expanding it ? I’m developing a fixed height website. None of the jquery plugins seem to be capable of this :(

      « Reply

      philipbeel Reply:

      @Miz, I’m afraid not, that feature would be out of the scope of the plugin. By all means you can try modifying the plugin to achieve this ends.

      « Reply


    16. Yahel

      Heloo, great script indeed! But it’s not compatible with other scripts like ddacordion (jquery) or like icarousel (mootools), right? Please let me know your answer and maybe your help on this one. Thank You

      « Reply


    17. Gareth Trufitt

      Great plugin, cheers! One thing that I noticed was the line: $(‘.hide_’ + num).empty(); should probably be changed to $(‘.hide_’ + num).remove(); to prevent multiple elements being output every time someone opens and closes a description.
      Ta!

      « Reply


    18. Yahel

      Hey mate,

      Sorry for my last message, now it’s ok and working perfectly. But I would need please (!) the original version of the script, because I don’t need that ‘intelligent truncation’.

      It would be very nice to answer me, as it’s for a professional use.

      Thank You
      Yahel

      « Reply

      philipbeel Reply:

      @Yahel, Im afraid version 1 is no longer available, it was not cross browser compatible so was updated and removed from general release, however please feel free to modify the code from the latest download to use as per your request.

      « Reply

      Yahel Reply:

      @philipbeel, Ok thank you for your answer. I hope you can answer to my next message which is my current master problem. ;)

      « Reply


    19. Yahel

      Or maybe to help me out on how not getting truncate after a space, inside an ‘a’ elements?

      « Reply


    20. tony

      Hi, this is great and just what i was looking but i dont know how its possible to add in a sinlge.php file in wordpress?
      Can you help please? Thanks!

      « Reply


    21. Simon Miller

      Hi there,

      I added on a tiny extra piece of functionality that made this plugin just a little better – JQuery UI effects.

      1. At the var defaults declaration, add a new parameter “show: ”, ”
      2. Find $(‘span.hiddenText_’+num).show() and add “defaults.show” in the () after .show

      Now you can have transition effects for the click event:

      .truncatable({ limit: 100, more: ‘… read more‘, less: false, show: ‘fast’ })

      I also found you can happily chain on to the end of the function so that you can show other panels when the click occurs:

      .truncatable({ limit: 100, more: ‘… read more‘, less: false, show: ‘fast’ }).click(function () {
      $(this).parent().find(“div.comments”).show();
      });

      « Reply

      philipbeel Reply:

      @Simon Miller, Thanks for sharing this, do you have a link to where you have implimented this code? It would be great to see!

      « Reply


    22. Phil

      this is great – but is there a way of it not expanding to show more – I’m using it in a div that is designed for a certain size.
      Love it though – and keep on chopping!

      « Reply

      philipbeel Reply:

      @Phil, If you dont need to use the expansion aspect of this plugin I would highly recommend using a PHP function as this will be much quicker.

      « Reply


    23. Paul Ashton

      Hi again,
      I added this to a ‘news’ page a while back… Worked great. I’m now looking for something to add an intro sentence on a home page for SEO (click to read more, expand text)… But I noticed that this (and other show/hide plugins) all use display:none. I was just wondering what you meant by ‘SEO friendly’ as Google would ignore that hidden text? Just trying to figure out if I can do this without display:none.

      Cheers though. And love the new site design. Haven’t been here in a while.

      « Reply

      philipbeel Reply:

      @Paul Ashton, Good point on the display none issue, Thats not something I had considered. I suppose you could do something with overflow:hidden; if you knew the exact height of the content you want to truncate. I will have to play around with this on git when I get my code up there.

      « Reply


    24. alex

      very nice script! works perfectly for me. thank you for your effort!

      the only ‘problem’ i am having is that the “[read more]” (or whatever you might change it to) displays right after the aforeput text – while it would look much nicer with a space in between. i have worked around this by changing the tooltext to ” [read more]“, however, like this i have the space before the [] underlined (i.e. marked as a link) as well.

      is there any elegant way to solve this?

      i have used it on this work in progress: http://www.alexbrunner.com/blog.

      cheers from austria

      « Reply

      alex Reply:

      @alex,

      i have now removed the truncatable plugin and solved the problem quite dufferently – but i would still be curious if there is an elegant way to solve this issue.

      best

      « Reply


    25. alex

      i should add that this is relevant for some (e.g. chrome) but not for all browsers. firefox e.g. does not underline spaces.

      « Reply


    26. vito

      Hi,

      I’m using your plugin, but there is still problem with scrolling the page to the top if I click on read more link. Can this be fixed, or is it fixed?

      p.s. This is just the plugin I need, but the problem with jumping to the top of the page makes it useless to me.

      Please help me with this problem,

      Thanks

      -Vito-

      « Reply


    27. vito

      Nevermind, problem solved :)

      « Reply

      nadz Reply:

      @vito, ahh…. how’d you solve it??

      « Reply

      nadz Reply:

      @nadz, thanks anyway, here it is from above – https://gist.github.com/457245

      « Reply


    28. web designing uae

      Awesome.I got a site with plenty of content.Hope to use it for my site.Thanks for the share.

      « Reply


    29. web designing

      Nice article! Very good list of web designing. Saves us some work in trying to find them.

      « Reply


    30. Geoff

      Hi guys,

      This script is awesome and just what i needed but wanted something else than … after the text as it also comes underlined which i didnt want, so i replaced the … and [hide text] with images which is also just as nice, here is the script modified to show images however you need an expand image and a collapse image –

      $(function () {
      $(‘.text’).truncatable({ limit: 200, more: ”, less: true, hideText: ” });
      });

      Hope this helps as well and hope i havent caused any dramas with the developer re this :)

      Cheeers

      Geoff

      « Reply

      Geoff Reply:

      @Geoff,

      Sorry guys the html took out the code will try again -


      $(function () {
      $(‘.text’).truncatable({ limit: 250, more: ”, less: true, hideText: ” });
      });

      « Reply

      Geoff Reply:

      Bugger lol, ok am not having much luck here, email me at – danztroniclive@hotmail.com.au if you want the code, sorry guys

      Cheers

      Geoff

      « Reply


    31. Amit Yadav

      Hello! It was a really nice post, but one thing I would like to ask…When I click on “read more..”, it takes the page to the top no matter where i am in my page. What I want is that when I click “read more…”, it must not move any bit on top, Please tell me how to do that?

      « Reply

      Amit yadav Reply:

      The problem is solved, i have to update the trunctable.js file.

      « Reply


    32. Mesothelioma

      I have tested the plugin and can confirm that it runs on the lastest version on jQuery(V1.3.2) and works on IE Safari and Firefox. Happy coding!

      « Reply


    Leave a comment


    This pretty much personifies me - http://t.co/glu8rD8j #cycling

    Follow me