I am currently working on a JavaScript project to determine if text is truncated. While I found a useful solution mentioned here, there is one edge case that needs to be addressed. Despite the visual truncation of the text, the first block on mouse hover incorrectly returns false.
function checkTruncationStatus(element) {
return (element.offsetWidth < element.scrollWidth);
}
function handleMouseHover(element) {
console.log(`Is the text truncated: ${checkTruncationStatus(element)}`);
}
div.red {
margin-bottom: 1em;
background: red;
color: #fff;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
width: 300px;
cursor: pointer;
}
<h6>Hover over the text and check the console for messages.</h6>
<!-- Expected to return true -->
<div class="red" onmouseover="handleMouseHover(this)">
<a>Analytics reports come through garbled. Please check</a>
</div>
<!-- Expected to return true -->
<div class="red" onmouseover="handleMouseHover(this)">
<a>Analytics reports come through garbled. Please check again</a>
</div>
<!-- Expected to return false -->
<div class="red" onmouseover="handleMouseHover(this)">
<a>Normal text</a>
</div>
The solution I am seeking is for the function to accurately detect when text is truncated by CSS.