I’ve finally finished and released a coding side-project of mine that has gone neglected for 3 years.
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:
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.