What's the easiest way to detect if an element has been overflowed?
My use case is, I want to limit a certain content box to have a height of 300px. If the inner content is taller than that, I cut it off with an overflow. But if it is overflowed I want to show a 'more' button, but if not I don't want to show that button.
Is there an easy way to detect overflow, or is there a better method?
In CSS, overflow refers to any content that is too big for an element's box. This occurs when a block element has a specified height that's too small for the content it contains. You can use the CSS overflow property to control what happens to the overflow.
The element may be overflown vertically, horizontally or both. This function will return you a boolean value if the DOM element is overflown:
function isOverflown(element) {
return element.scrollHeight > element.clientHeight || element.scrollWidth > element.clientWidth;
}
function isOverflown(element) {
return element.scrollHeight > element.clientHeight || element.scrollWidth > element.clientWidth;
}
var els = document.getElementsByClassName('demos');
for (var i = 0; i < els.length; i++) {
var el = els[i];
el.style.borderColor = (isOverflown(el) ? 'red' : 'green');
console.log("Element #" + i + " is " + (isOverflown(el) ? '' : 'not ') + "overflown.");
}
.demos {
white-space: nowrap;
overflow: hidden;
width: 120px;
border: 3px solid black;
}
<div class='demos'>This is some text inside the div which we are testing</div>
<div class='demos'>This is text.</div>
ES6 example:
const isOverflown = ({ clientWidth, clientHeight, scrollWidth, scrollHeight }) => {
return scrollHeight > clientHeight || scrollWidth > clientWidth;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With