How to add ellipsis to the overflowing part of text?

Tags: ellipsis, text overflow, div, multi-line

How to add ellipsis to the overflowing part of text? How to break by word? How to break on N lines of text and add the ellipsis?

While researching the ellipsis there are fundamentally three approaches to fixing this problem:

  1. Truncate the text on the server
  2. Use CSS to add the ellipsis
  3. Use JavaScript to add the ellipsis


Truncate the text on the server

Truncating the text on server presents the following two challenges:

  • you do not know how many characters to truncate to. that especially applies if you have a responsive mobile friendly web site.
  • you might be dealing with html. Stripping out the html tags is one aspect of this problem. Possibly having to maintain the formatting adds a whole new level of complexity to this problem.


Use CSS to add the ellipsis

This is a wishful thinking solution. Ideally you could just use the CSS class text-overflow: ellipsis;

div {
     text-overflow: ellipsis;
} 

But this doesn't work properly in all browsers. Also does not break by word. Only supports one line.

There are also a few more advanced CSS solutions which ultimately have undesired limitations. To name a few:

http://www.mobify.com/blog/multiline-ellipsis-in-pure-css/

image

http://salzerdesign.com/blog/?p=453

image

Quite possibly in a few years this will work properly in all browsers.


Use JavaScript to add the ellipsis

There are a few available JavaScript libraries truncate text or add ellipsis. To mention a few:


The jQuery dotdotdot has the most number of features and works nice with angular:

(function (angular) {
angular.module('app')
    .directive('appEllipsis', [
        "$log", "$timeout", function ($log, $timeout) {
            return {
                restrict: 'A',
                scope: false,
                link: function (scope, element, attrs) {

                    // let the angular data binding run first
                    $timeout(function() {
                        element.dotdotdot({
                            watch: "window"
                        });
                    });
                }
            }

        }
    ]);
})(window.angular);


The corresponding markup would be:


<p app-ellipsis>{{ selectedItem.Description }}</p>

No Comments

Add a Comment