Skip to content

Instantly share code, notes, and snippets.

@codexico
Created April 9, 2013 22:48
Show Gist options
  • Save codexico/5350093 to your computer and use it in GitHub Desktop.
Save codexico/5350093 to your computer and use it in GitHub Desktop.
Crop string by width and word and append " ...".
// 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