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?
Can you hook up a javascript debugger and check where it crashes? Use Firebug with Firefox or MSVS with IE. If it blows up so hard the debugger dies, step through the function and see how far it gets.
Update based on last comments: I think you need to step through your code and see how far it gets. I would be suspicious of a few things:
Maybe the width of the object hasn't been recalculated yet (or has become invalid) after setting the new inner text. It could be that the updated width is not available until later, when the UI does a readjustment.
This loop in theory should always terminate, but its possible (especially if the browser is not recalculating the width correctly) the loop could go on forever.
You could be splitting an HTML tag when you split the inner text, causing your code to insert malformed HTML perhaps causing the page layout to break.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With