Skip to content

Instantly share code, notes, and snippets.

@sebmarkbage
Forked from nw/Element.truncate.js
Created May 23, 2009 01:06
Show Gist options
  • Save sebmarkbage/116449 to your computer and use it in GitHub Desktop.
Save sebmarkbage/116449 to your computer and use it in GitHub Desktop.
Element.implement({
/**
truncates element text to fit in element width.
end (bool) defaults false. True = cuts string at end, False = cuts string in middle
str (string) truncation string default : '...'
**/
truncate : function(end,str){
str = str || '...';
var style = this.style;
var originalStyles = { overflow: style.overflow, 'white-space': style.whiteSpace, padding: style.padding };
this.setStyles({ overflow: 'hidden', 'white-space': 'nowrap', padding: 0 });
var width = this.clientWidth;
var txt = this.get('text');
if(end){
var rside = txt.length;
while(this.scrollWidth > width){
rside--;
this.set('text',txt.slice(0,rside)+str);
}
} else {
var mid = lside = Math.floor(txt.length / 2); var rside = lside+1;
while(this.scrollWidth > width){
((mid-lside) < (rside-mid)) ? lside-- : rside++;
this.set('text',txt.slice(0,lside)+str+txt.slice(rside));
}
}
return this.setStyles(originalStyles);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment