22 March 2012

Short text contents by size on client side

This time I bring code that can help you with working with text.
The following code is the client side (javascript - jquery) and receive text and shortens it. Finally, it adds three dots (...)

// -- Fix width size, add "..." if the size is big --
// Example:
// Before:
// <p id='MyID'>text text text text</p>
// ...
// var el = $('#MyID'); 
// FixWidthSize(el, 10);
// ...
// After: 
// <p id='MyID'>text text ...</p>
function FixWidthSize(el, size) {
    var originalText = el.html();
    var w = el.width();
    var text = originalText;
    while (text.length > 0 && size < el.width()) {
        text = text.substr(0, text.length - 1);
        el.html(text + "...");
    }
}

So it seems, before and after

Yours,
Roi

No comments:

Post a Comment