Skip to content
Advertisement

Ellipsis in the middle of a text (Mac style)

I need to implement ellipsis ("...") in the middle of a text within a resizable element. Here is what it might look like. So,

"Lorem ipsum dolor sit amet. Ut ornare dignissim ligula sed commodo."

becomes

"Lorem ipsum dolor sit amet ... commodo."

When the element is stretched out to the width of the text, I want the ellipsis to disappear. How can this be done?

Advertisement

Answer

In the HTML, put the full value in a custom data-* attribute like

<span data-original="your string here"></span>

Then assign load and resize event listeners to a JavaScript function which will read the original data attribute and place it in the innerHTML of your span tag. Here is an example of the ellipsis function:

function start_and_end(str) {
  if (str.length > 35) {
    return str.substr(0, 20) + '...' + str.substr(str.length-10, str.length);
  }
  return str;
}

Adjust the values, or if possible, make them dynamic, if necessary for different objects. If you have users from different browsers, you can steal a reference width from a text by the same font and size elsewhere in your dom. Then interpolate to an appropriate amount of characters to use.

A tip is also to have an abbr-tag on the … or who message to make the user be able to get a tooltip with the full string.

<abbr title="simple tool tip">something</abbr>
Advertisement