Once upon a time, I found myself in need of a solution for detecting truncated text that would work reliably across different browsers. The method I stumbled upon may be considered a bit of a hack, but it consistently delivers the correct result.
The concept involves cloning the element, removing any set width constraints, and comparing the width of the cloned element to the original. If the cloned element is wider than the original, then you can infer that the text has been truncated.
Here's an example using jQuery:
var $element = $('#element-to-test');
var $c = $element
.clone()
.css({display: 'inline', width: 'auto', visibility: 'hidden'})
.appendTo('body');
if( $c.width() > $element.width() ) {
// text was truncated.
// perform necessary actions
}
$c.remove();
I've created a jsFiddle to showcase this technique: http://jsfiddle.net/cgzW8/2/
If preferred, you could even define a custom pseudo-selector for jQuery:
$.expr[':'].truncated = function(obj) {
var $this = $(obj);
var $c = $this
.clone()
.css({display: 'inline', width: 'auto', visibility: 'hidden'})
.appendTo('body');
var c_width = $c.width();
$c.remove();
if ( c_width > $this.width() )
return true;
else
return false;
};
This allows you to easily identify truncated elements with your custom pseudo-selector:
$truncated_elements = $('.my-selector:truncated');
Check out the demo here: http://jsfiddle.net/cgzW8/293/
While somewhat unconventional, I hope this approach proves helpful in handling truncated text effectively.