Html text-overflow ellipsis detection
Detect text-overflow: ellipsis instances by comparing the element.scrollWidth to the element.clientWidth. If scrollWidth is greater than clientWidth, the text is being truncated:
Check the truncation status using:
In case you're looking to find out if an ellipsis is present because of the overflow, a function named isEllipsisActive can help you:
And to keep your HTML as responsive as your design:
Ellipsis? Cross-Browser, Please!
Life's too short for cross-browser CSS inconsistencies. Calculations might vary due to differences in font rendering or zoom levels among browsers. Thus, setting a tolerance based on a fixed pixel value or font size is a good practice:
Go Dynamic or Go Home!
When the content updates dynamically (like in Single Page Applications), the function can listen for changes by attaching to specific events or a mutation observer.
Handling jQuery: Do Not Disturb!
Working with jQuery? Fear not, we can extend jQuery selectors to add a :truncated pseudo-selector:
Cloning: Because Two are Better than One!
While this may sound like a Sci-Fi plot, it is a robust approach to determine if the text fits within its container. Clone the element, use a placeholder text and compare the clientWidth of the cloned and original elements:
Overflow Detective at Work!
A handy trick while debugging is to log the influences of offsetWidth and scrollWidth:
Tooltips: Now You See Me!
To display tooltips for elements with text overflow, assign the title attribute on mouseenter:
Was this article helpful?