I have a webpage with an elastic layout that changes its width if the browser window is resized.
In this layout there are headlines (h2
) that will have a variable length (actually being headlines from blogposts that I don't have control over). Currently - if they are wider than the window - they are broken into two lines.
Is there an elegant, tested (cross-browser) solution - for example with jQuery - that shortens the innerHTML of that headline tag and adds "..." if the text would be too wide to fit into one line at the current screen/container width?
trunk8 jQuery plugin supports multiple lines, and can use any html, not just ellipsis characters, for the truncation suffix: https://github.com/rviscomi/trunk8
Demo here: http://jrvis.com/trunk8/
Just in case y'all end up here in 2013 - here is a pure css approach I found here: http://css-tricks.com/snippets/css/truncate-string-with-ellipsis/
It works well.
I'd done something similar for a client recently. Here's a version of what I did for them (example tested in all latest browser versions on Win Vista). Not perfect all around the board, but could be tweaked pretty easily.
Demo: http://enobrev.info/ellipsis/
Code:
I was a bit surprised by the behavior of the css though.
Unless I provided the width to the control to which i needed to bind the ellipsis didn't suppost my cause. Is width a must property to be added ??? Please put your thoughts.
My answer only supports single line text. Check out gfullam's comment below for the multi-line fork, it looks pretty promising.
I rewrote the code from the first answer a few times, and I think this should be the fastest.
It first finds an "Estimated" text length, and then adds or removes a character until the width is correct.
The logic it uses is shown below:
After an "estimated" text length is found, characters are added or removed until the desired width is reached.
I'm sure it needs some tweaking, but here's the code: