Truncate text with jQuery based on pixel width
<p>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 width...</p>

<p>However it's not working (the text doesn't truncate)...</p>

<p>Here is the code I have:</p>

<pre><code>    function constrain(text, original, ideal_width){

 var temp_item = ('&lt;span class="temp_item" style="display:none;"&gt;'+ text +'&lt;/span&gt;');
 $(temp_item).appendTo('body');
 var item_width = $('span.temp_item').width();
 var ideal = parseInt(ideal_width);
 var smaller_text = text;

 while (item_width &gt; ideal) {
  smaller_text = smaller_text.substr(0, (smaller_text-1));
  $('.temp_item').html(text);
  item_width = $('span.temp_item').width();
 }

 var final_length = smaller_text.length;

 if (final_length != original) {
  return (smaller_text + '&amp;hellip;');
 } else {
     return text;
 }
}
</code></pre>

<p>Here's how I'm calling it from the page:</p>

<pre><code>    $('.service_link span:odd').each(function(){
 var item_text = $(this).text();
 var original_length = item_text.length;
 var constrained = constrain(item_text, original_length,175);
 $(this).html(constrained);
});
</code></pre>

<p>Any ideas on what I'm doing wrong? If there is a way to do it faster (ie bubble sort), that would be great too.</p>

<p>Thanks!</p>
