Skip to content

Instantly share code, notes, and snippets.

@gfrison
Created May 10, 2012 13:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gfrison/2653014 to your computer and use it in GitHub Desktop.
Save gfrison/2653014 to your computer and use it in GitHub Desktop.
truncating a string in javascript according to the REAL length of chars and tooltip the full-size string in the element
//just to avoid 'string ...' with spaces
//trim a string http://stackoverflow.com/a/498995
String.prototype.trim=function(){return this.replace(/^\s\s*/, '').replace(/\s\s*$/, '');};
//improvement of this: http://blog.mastykarz.nl/measuring-the-length-of-a-string-in-pixels-using-javascript/
var visualLength = function(str){
var ruler = document.createElement('span');
ruler.style.visibility = 'hidden';
ruler.style['white-space'] = 'nowrap';
document.body.appendChild(ruler);
ruler.innerHTML = str;
var l =ruler.offsetWidth;
document.body.removeChild(ruler);
return l;
};
var trunc = function(n, element){
var str = element.innerHTML;
if(visualLength(str)>n){
do{
str = str.substr(0,str.length-1).trim();
}while(visualLength(str)>n);
element.title = element.innerHTML;
element.innerHTML=str + '…';
}
};
//usage (http://jsfiddle.net/B3QDd/)
trunc(100, $("foo"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment