Skip to content

Instantly share code, notes, and snippets.

@appden
Forked from nw/Element.truncate.js
Created May 25, 2009 05:27
Show Gist options
  • Save appden/117394 to your computer and use it in GitHub Desktop.
Save appden/117394 to your computer and use it in GitHub Desktop.
Element.implement({
// truncates element text to fit its width
truncate: function(trail){
var text = this.get('text').trim();
if (!text) return;
trail = trail || '...';
var style = this.style;
var styles = { overflow: style.overflow, 'white-space': style.whiteSpace, padding: style.padding, margin: style.margin };
this.setStyles({ overflow: 'hidden', 'white-space': 'nowrap', padding: 0, margin: style.padding });
var width = this.clientWidth;
if (this.scrollWidth > width){
text = text.split(/\s+/);
var words = [];
for (var i = 0; i < text.length; i++){
words[i] = text[i];
this.set('text', words.join(' ') + '_' + trail);
if (this.scrollWidth > width) break;
}
words.pop();
this.set('text', words.join(' ').replace(/[^A-z0-9]+$/, '') + trail);
}
return this.setStyles(styles);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment