Hi,
I'm trying to take a text string, (e.g. the word "testing") and calculating if the string, when displayed on screen, will exceed a certain width. I do this by putting it in a element and using width().
Now, the thing is I want to reduce the text string by a character at a time, and then determining the width. If the width is within say "130px", then i'll return that truncated string. I have the following recursive function, but I'm quite new to Js/jQuery and am unsure what I did wrong. If the string is determined to require truncating, the function returns undefined.
Any help is greatly appreciated. Thanks a lot!
function fitWidth(str) {
var width = $('span.width').html(str).width();
if (width > '130') {
strlength = str.length-1;
str = str.substr(0,strlength);
fitWidth(str);
} else {
return str; // something wrong here?
}
}
var testStr = 'Lorem Ipsum';
alert(fitWidth(testStr)); // returns undefined if it was truncated
if str requires truncating, fitWidth() will return "undefined"