I am trying to create a jQuery function that will take a string and a fixed width as input, and then through a binary search method (for efficiency) "compresses" this piece of text so that it does not exceed a 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) {
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;
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 terminates in my browser. Firebug points to jquery.js line 1131 (version 1.3.2), which is the "unique" jQuery utility, as the culprit. However, I do not use the “unique” option.
What am I doing wrong here?
Simon source
share