3

in my angularjs/ionic mobile application I have implemented a list of messages. Now I want to modify it, so that if the message text is wider than the div container it should cut the string and adds 3 dots.

My message list looks like this:

<ion-list ng-repeat="message in messages">
        <ion-item can-swipe="true" class="item-icon-left item-icon-right">

          <i class="icon ion-email-unread"></i>

          <div class="row">
            <span class="col col-50">
              <h2>{{message.title}}</h2>
            </span>
            <span class="col col-50 content-right text-small">
              {{message.dateString}}
            </span>
          </div>

          <div class="row">
            <span class="col text-small">
              {{message.text}}
            </span>
          </div>

          <i class="icon ion-chevron-right"></i>

          <ion-option-button class="button-dark">
            More
          </ion-option-button>
          <ion-option-button class="button-assertive">
            Delete
          </ion-option-button>
        </ion-item>

      </ion-list>

How can I do this dynamically, so that it really depends on the width of the device/container?

Kingalione
  • 4,237
  • 6
  • 49
  • 84

2 Answers2

10

You don't do that with JS.

Simply use CSS's overflow and text-overflow properties:

div {
  width: 50px;
  overflow: hidden;
  text-overflow: ellipsis;
}
<div>1234567890123456789012345678901234567890</div>
Cerbrus
  • 70,800
  • 18
  • 132
  • 147
  • This only works with a fixed width, which collides with flowing text in a responsive design – dube Sep 05 '16 at 12:42
  • @dube: `overflow: hidden; text-overflow: ellipsis;` works just fine on elements with a dynamic width. __[Example](https://jsfiddle.net/hbzg3q7c/).__ – Cerbrus Sep 05 '16 at 12:50
  • Apologies for my short comment. Your sample works because the text is a single, big word. It works with real text too, if you add "white-space:nowrap". However, that's no fun with multi-line text (which was not asked for here). [Updated Example](https://jsfiddle.net/hbzg3q7c/2/) – dube Sep 05 '16 at 13:11
  • 1
    Hm, in that case, [the answer here](http://stackoverflow.com/questions/16229828/using-text-overflowellipsis-only-when-reaching-3-lines-in-a-div) can be of help, @dube. – Cerbrus Sep 05 '16 at 13:16
2

You can achieve this easily by using CSS and specifying a width for your content and adding a text-overflow style with the value of elipsis.

#crop-text {
  /* essential */
  text-overflow: ellipsis;
  width: 160px;
  white-space: nowrap;
  overflow: hidden;
  
  /* for good looks */
  padding: 10px;
  
  border: 1px #000 solid;
}
<div id="crop-text">Hello, this is a really long text string.</div>

This tutorial explains what you need to do. http://davidwalsh.name/css-ellipsis

Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132