Add a title property to elements with text-overflow: ellipsis

Issue

I am not sure if this is easily possible, but I thought I would ask just in case:

I am using the following CSS rules on a list of text:

{ 
    width: 100px;
    overflow: hidden;
    text-overflow: ellipsis;
}

As expected, any text that goes outside the list will be truncated and have an ellipsis placed on the end.

I want to have an active title property for only those list items that trigger the text-overflow rule on the list. So you can hover the mouse over any text that is truncated and see a tooltip of its full text.

Something tells me this is difficult, if not impossible, to do. However I would love to be proven wrong. I am preferably looking for a solution that uses as little JavaScript as possible.

Solution

We use a similar, more generic ellipsify, which works perfectly for most cases. We also apply the title attribute (for all elements). Only applying the title if the element ellipsifies, is indeed difficult. The example below assumes that, if the element has the same width as the parent, we should set the title. Without the if statement it would always apply the title.

document.querySelectorAll('.ellipsify').forEach(function (elem) {
  if (parseFloat(window.getComputedStyle(elem).width) === parseFloat(window.getComputedStyle(elem.parentElement).width)) {
    elem.setAttribute('title', elem.textContent);
  }
});
.ellipsify {
    text-overflow: ellipsis;
    overflow: hidden;
    white-space: nowrap;
    max-width: 100%;
    display: inline-block;  
}

div {
  width: 100px;
}
<div>
  <span class="ellipsify">dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna</span>
  <span class="ellipsify">dolor sit amet</span>
</div>

Answered By – SVSchmidt

Answer Checked By – Senaida (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.