I am trying to create a jQuery function that will take a string and a fixed width as an input, then through a binary search method (for efficiency) "shrink" that piece of text so it's no longer than the fixed width.
This is what I have so far:
function constrain(text, ideal_width){
var temp = $('.temp_item');
temp.html(text);
var item_width = temp.width();
var ideal = parseInt(ideal_width);
var text_len_lower = 0;
var smaller_text = text;
var text_len_higher = text.length;
while (true) {
if (item_width > ideal) {
// make smaller to the mean of "lower" and this
text_len_higher = smaller_text.length;
smaller_text = text.substr(0, ((text_len_higher + text_len_lower)/2));
} else {
if (smaller_text.length >= text_len_higher) break;
// make larger to the mean of "higher" and this
text_len_lower = smaller_text.length;
smaller_text = text.substr(0, ((smaller_text.length + text_len_higher)/2));
}
temp.html(smaller_text);
item_width = temp.width();
}
var new_text = smaller_text + '…'
return new_text;
}
Unfortunately this causes a "slow script" that never completes in my browser. Firebug points to line 1131 of jquery.js (version 1.3.2), which is the "unique" jQuery utility, as the culprit. I'm not using "unique" anywhere however.
What am I doing wrong here?