Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect CSS text-overflow ellipsis with jQuery

Here is a fiddle

CSS:

div{
    width:160px;
    text-overflow:ellipsis;
    overflow:hidden;
    white-space:nowrap;
    text-transform: uppercase;
}

I edited a fiddle created by someone else who meant to answer this question.

This solution works well, BUT in one case does not work correctly. If the text should be 100% of the box ellipsis, it is hiding the last few letters and adding "...". However, when you manipulate the CSS and remove the overflow statement, then the size fits.

So this way is not 100% reliable, but I need a 100% working one.

Does anyone have a proper solution?

like image 743
Mephiztopheles Avatar asked Oct 29 '14 11:10

Mephiztopheles


People also ask

How do you know if text is overflowing CSS?

Check its style. overflow property, if it is 'visible' then the element is hidden. Also, check if its clientWidth is less then scrollWidth or clientHeight is less then scrollHeight then the element is overflowed.

What is text overflow ellipsis in CSS?

The text-overflow property specifies how overflowed content that is not displayed should be signaled to the user. It can be clipped, display an ellipsis (...), or display a custom string.


2 Answers

There can be a difference between how the page looks in the browser and the calculations used to determine if the text will overflow. The box model doesn't always behave as we want. That said, you can compare the innerwidth with the scrollwidth.

Here is a simple example that should correspond to the ellipse showing if true:

if ($('#div')[0].scrollWidth >  $('#div').innerWidth()) {
    //ellipse should be showing because the text is in overflow
}

I updated your fiddle and it works as I expect. Your syntax for scrollwidth wasn't correct.

e.scrollWidth vs. $(e)[0].scrollWidth

Updated link to the new fiddle:

http://jsfiddle.net/whipdancer/67upsqq8/1/

like image 126
whipdancer Avatar answered Sep 24 '22 22:09

whipdancer


I forgot to post my solution.

Now i'm using el.scrollWidth > el.clientWidth; and it's working well.
Note that el in this case is not jquery wrapped.

like image 30
Mephiztopheles Avatar answered Sep 24 '22 22:09

Mephiztopheles