Skip to content

Instantly share code, notes, and snippets.

@marcelotten
Last active December 15, 2015 23:59
Show Gist options
  • Save marcelotten/5344522 to your computer and use it in GitHub Desktop.
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.
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);
}
}
@marcelotten
Copy link
Author

Example:

<span class="title">summerholidays2012_IMG_3232</span>
<script>
    truncate($('.title'), 100)
</script>

Result:

<span>summerhol...IMG_3232</span>

@fhemberger
Copy link

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