Explain Codes LogoExplain Codes Logo

Html text-overflow ellipsis detection

html
responsive-design
performance
best-practices
Nikita BarsukovbyNikita BarsukovยทJan 12, 2025
โšกTLDR

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:

/* Catch me if you can. Or rather... catch ellipsis if you can! */ const isTruncated = (elem) => elem.scrollWidth > elem.clientWidth;

Check the truncation status using:

console.log(isTruncated(document.getElementById('yourEllipsisElement')));

In case you're looking to find out if an ellipsis is present because of the overflow, a function named isEllipsisActive can help you:

/* function name sounds like a trendy startup, isn't it? ๐Ÿ˜… */ const isEllipsisActive = (e) => { return (e.offsetWidth < e.scrollWidth); }

And to keep your HTML as responsive as your design:

/* Fresh as a daisy */ const freshEllipsisCheck = () => { document.querySelectorAll('.ellipsisText').forEach((elem) => { elem.title = isEllipsisActive(elem) ? elem.textContent : null; // For mouse hover }); }; // Call the function when the window resizes or the text changes dynamically window.addEventListener('resize', freshEllipsisCheck);

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:

/* The secret ingredient is tolerance... both in coding and life! ๐Ÿ•Š๏ธ */ const isTruncatedWithTolerance = (elem, tolerance = 1) => { return elem.scrollWidth - elem.clientWidth > tolerance; }

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:

$.expr[':'].truncated = function (el) { return $(el).prop('scrollWidth') > $(el).prop('clientWidth'); }; // Usage $('.some-class:truncated').each(function () { // Your logic goes here });

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:

const isTextOverflowing = (el) => { const doppelganger = el.cloneNode(true); // Whoa! Got myself a twin doppelganger.style.display = 'inline'; doppelganger.style.width = 'auto'; doppelganger.style.visibility = 'hidden'; doppelganger.textContent = '...'; el.parentNode.appendChild(doppelganger); // Welcome twin to the family const isOverflowing = doppelganger.clientWidth < el.clientWidth; doppelganger.parentNode.removeChild(doppelganger); // Oh well, twins not always needed return isOverflowing; };

Overflow Detective at Work!

A handy trick while debugging is to log the influences of offsetWidth and scrollWidth:

/* Dear console, reveal thy secrets... */ console.log('Offset Width:', element.offsetWidth, 'Scroll Width:', element.scrollWidth);

Tooltips: Now You See Me!

To display tooltips for elements with text overflow, assign the title attribute on mouseenter:

/* Why so serious? Let's hover on ellipsis! */ document.querySelectorAll('.ellipsis').forEach((el) => { el.addEventListener('mouseenter', function () { if (isEllipsisActive(this)) { this.setAttribute('title', this.textContent); } }); });