I’ve finally finished and released a coding side-project of mine that has gone neglected for 3 years.
About Truncator.js
So here’s what it does:
- Truncates nested html content (not just flat text) to fit within a fixed height (or max-height) div
- Allows more / less links to expand and restore truncated text
- Runs automatically on all elements with the “truncate” class or Truncator.wrapClass
- Can be run manually with Truncator.truncate()
- Allows custom truncation characters (default is … / … )
- Wraps long words using ­
- Uses the jQuery Library
It can be run automatically on divs like this:
Or run manually in Javascript with this function call:
Download the source: svn | zip
jQuery Plugin Page
Why it Took 3 Years to Finish
I first created the clumsy ancestor of Truncator.js 4 years ago at my first job. It started off as a way to achieve cross browser word-wrap for a web-based instant messenger and ended up working similar to Hyphenator.js. It was based off a gem of found code written in Portugese and a lot of trial-and-error. The whole class was a terrible mess and a ton of work for functionality that CSS3 word-wrap would fix anyway, but it didn’t take long to realize that the code could be adapted to dynamically truncate text to fit within a div; a much more elegant solution than server-side truncation.
After leaving my job I re-wrote the class in my spare time and added improvements like a binary search algorithm; but it wasn’t until I revisited the project this past month that I managed to add the finishing touch of DOM navigation to allow truncation of HTML content. At this point I’ve tested the truncation on my blog and the included test.html and it works pretty well even with a large amount of text. There are probably still some quirks related to certain HTML elements. I can’t promise how responsive bug-fixes to the code will be, consider this alpha-stage code; but if it finds use out there I’ll try and keep it up to date let me know if you have any issues.
E-mail: contact@malcolmp.com
A good “truncator” truncates based on context and language rules. That’s what distinguishes men from boys.
From your example: “tellus, ac l…” << this makes no sense, even though this is "lorem ipsum" text.
Ya I suppose it’d make sense to truncate to the last whole word. I actually thought about applying the algorithm to search-result truncation where it shows a portion of the text surrounding the search terms as well. The next step is to modularize the truncation logic separating it from the overflow detection (after I test that out a bit more). That’d allow for more varied truncation behavior. So for now I’ve just got it truncating to overflow.
Pingback: 10 New jQuery Plugins for August 2011 | jQuery4u
You made something that’s very simple, very complex. You could do this in 1/5th the amount of code you used.
Good Job Dud!!!
Thank you, it helped me!