Created
May 10, 2012 13:32
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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