Created
April 9, 2013 22:48
-
-
Save codexico/5350093 to your computer and use it in GitHub Desktop.
Crop string by width and word and append " ...".
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
// http://stackoverflow.com/questions/118241/calculate-text-width-with-javascript | |
function stringWidth(s, className) { | |
var c = className || "", | |
o = $('<div class="' + c + '">' + s + '</div>') | |
.css({'position': 'absolute', 'float': 'left', 'white-space': 'nowrap', 'visibility': 'hidden'}) | |
.appendTo($('body')), | |
w = o.width(); | |
o.remove(); | |
return w; | |
} | |
function cortaNome(nome) { | |
if (!nome) { | |
return ""; | |
} | |
var nomeW = stringWidth(nome); | |
var lastIndex; | |
var containerW = $('.page-ranking .nome:first').width() || 224; | |
if (nomeW < containerW) { // tamanho da td | |
return nome; | |
} | |
while (nomeW >= containerW) { | |
lastIndex = nome.lastIndexOf(" "); | |
nome = nome.substring(0, lastIndex); | |
nomeW = stringWidth( nome + " ..."); | |
} | |
return nome + " ..."; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment