I\'m trying to use jquery to write a fast function that calculates the pixel width of a string on a html page, then truncates the string until it reaches an ideal pixel widt
The function takes the text to check, the ideal_width in pixel and the class name for the css. If the ideal_width is less than the text width it truncs and adds the hellip otherwise it returns the text unmodified. Simple and works! :-)
function constrain(text, ideal_width, className){
var temp_item = ('');
$(temp_item).appendTo('body');
var item_width = $('span.'+className+'_hide').width();
var ideal = parseInt(ideal_width);
var smaller_text = text;
if (item_width>ideal_width){
while (item_width > ideal) {
smaller_text = smaller_text.substr(0, (smaller_text.length-1));
$('.'+className+'_hide').html(smaller_text);
item_width = $('span.'+className+'_hide').width();
}
smaller_text = smaller_text + '…'
}
$('span.'+className+'_hide').remove();
return smaller_text;
}