Wednesday, March 14, 2012

Custom Knockout binding for truncating text with an ellipsis

[UPDATE] Added an AMD version at the end. Adapting this JsFiddle I created a custom knockout binding for truncating multi-line text to fit within an available space:


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)*$/, '...');
                });
            }
        }
    };


Both the parent and child need to be block level elements and the parent needs a fixed height I believe.

Of course, if you have just a single line, you can do this easily with pure css (from Twitter Bootstrap)


// Text overflow
// -------------------------
// Requires inline-block or block for proper styling
.text-overflow {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

Here is a JsFiddle showing this in action. [UPDATE] And now here is an AMD version. Where 'jquery' is, of course, jQuery, and 'ko' is knockout.

define(['jquery', 'ko'], function ($, ko) {
   ko.bindingHandlers.truncate = {
       update: function (element, valueAccessor) {
           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)*$/, '...');
               });
           }
       }
   };
});
    

10 comments:

  1. This is great. Thanks for this. I had to change $element.text(value()); to $element.text(value); for my use-case.

    Also if your container is a variable width and changes with window size, you can wrap the while() statement in a $(window).resize() function.

    ReplyDelete
  2. Thanks! This broke for me a couple of KO versions ago so I'll give your changes a go, see if it fixes things for me as well.

    ReplyDelete
  3. It could give intends to kids to work on perusing at home without the guide of a human instructor.text to speech api

    ReplyDelete
  4. Very informative post! There is a lot of information here that can help any business get started with a successful social networking campaign.
    nescafe

    ReplyDelete
  5. TTS or text to speech programming helps enhancing the proficiency at work, learning distinctive dialects, doing viable editing or essentially lessening eye strain because of perusing a great deal.computer voice generator

    ReplyDelete
  6. You may likewise type on your console and not to take a gander at the screen; Speaking Notepad will peruse everything for you. first perused it so anyone might hear can peruse texts for youngsters and grown-ups.notevibes

    ReplyDelete
  7. I went to this website, and I believe that you have a plenty of excellent information, I have saved your site to my bookmarks. spicewood custom pool contractor

    ReplyDelete

  8. really infomative and eduvcative article thanks publisher for sharing this info with us massage gaming chair with footrest
    whatsaup flippzilla

    ReplyDelete
  9. How are things? Team from https://expertpaperwriter.com/samedayessay-com-review/ crafts a capstone project proposal that will satisfy your tutor’s or academic mentor’s demands. It’s a short paper that informs about your topic choice. Here we also add the reason why you selected this very issue, describe in short what you’re going to research and what results to obtain.

    ReplyDelete