Skip to content

Instantly share code, notes, and snippets.

@ternus
Created November 4, 2010 16:28
Show Gist options
  • Save ternus/662737 to your computer and use it in GitHub Desktop.
Save ternus/662737 to your computer and use it in GitHub Desktop.
Fits a string to a given pixel size
function fitString(str, size, strclass) {
// Fits a string to a given pixel size
// Based on a solution from stackoverflow.com
var nstr = str;
var tmp = document.createElement("span");
tmp.className = strclass;
tmp.style.visibility = "hidden";
tmp.style.padding = "0px";
document.body.appendChild(tmp);
tmp.innerHTML = nstr;
// we use a binary search to determine the appropriate size
if (tmp.offsetWidth > size) {
var minLength = 0;
var maxLength = str.length;
var curLength;
while(true){
curLength = minLength + Math.floor((maxLength - minLength) / 2);
tmp.innerHTML = str.substring(0, curLength) + '…';
console.debug("size:" + size + ", min: " + minLength + ", max: " + maxLength + ", cur: " + curLength + " width: " + tmp.offsetWidth);
if (curLength == maxLength || curLength == minLength) {
break;
} else if (tmp.offsetWidth > size) {
maxLength = curLength;
} else {
minLength = curLength;
}
};
nstr = str.substring(0, curLength) + '…';
}
document.body.removeChild(tmp);
return nstr;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment