Knockout Truncate bindinghandler

Truncate multi-line text and add an ellipsis.

by genereddick

HTML

<script src="https://github.com/SteveSanderson/knockout/raw/master/build/output/knockout-latest.debug.js"></script>
<div style="width:300px;height:58px;border:1px solid black;margin-bottom:30px">
    <p><b>Truncate this</b></p>    
    <p style="display:block;" data-bind="truncate: description"></p>
</div>


<div style="width:200px;height:58px;border:1px solid black">
    <p><b>And truncate this</b></p>    
    <p style="display:block;" data-bind="truncate: description"></p>
</div>

CSS

}

JavaScript

ko.bindingHandlers.truncate = {
    update: function(element, valueAccessor, allBindingsAccessor, context) {
        var value = valueAccessor();
        var $element = $(element);
        var divh = $element.parent().height();
        $element.text(value());
        while ($element.outerHeight() > divh) {
            $element.text(function(index, text) {
                return text.replace(/\W*\s(\S)*$/, '...');
            });
        }
    }
};

var ViewModel = function() {
    var self = this;
    self.description = ko.observable("Here is some incredibly long text which I would like to truncate and end it with an ellipsis. Did it work? Let's find out, shall we?");

};


ko.applyBindings(new ViewModel());