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,

JavaScript

becomes

JavaScript

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

JavaScript

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:

JavaScript

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.

JavaScript
Advertisement