Truncatable – A jQuery plugin

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]' });
  • Digg
  • StumbleUpon
  • del.icio.us
  • Twitter
  • Google Bookmarks
  • email
  • Facebook
  • RSS

40 Responses to “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


Talk to me