Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if an element's content is overflowing?

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?

like image 721
Harry Avatar asked Sep 30 '22 11:09

Harry


People also ask

What is element overflow?

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.


1 Answers

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;
}
like image 335
micnic Avatar answered Oct 09 '22 15:10

micnic