Last active
December 15, 2015 23:59
-
-
Save marcelotten/5344522 to your computer and use it in GitHub Desktop.
Truncates the text of an element till the elements fits the given size using jQuery. But instead of just cutting the last characters it takes it from the middle which is more useful in most cases.
This file contains hidden or 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
function truncate(elem, size){ | |
var text = elem.text(), mid = Math.round(text.length/2), i = 0; | |
while(elem.width() > size){ | |
i++; | |
var newText = text.substr(0,mid-1*i)+'…'+text.substr(mid+1*i, text.length); | |
elem.text(newText); | |
} | |
} |
jQuery plug-in style:
// Only works on inline elements!
;(function($) {
$.fn.truncate = function(size) {
return this.each(function () {
var elem = $(this), text = elem.text(), mid = Math.round(text.length/2), i = 0;
while(elem.width() > size) {
i++;
var newText = text.substr(0,mid - 1 * i) + '…' + text.substr(mid + 1 * i, text.length);
elem.text(newText);
}
});
};
})(jQuery);
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example:
Result: