Check if an element’s content is overflowing?

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;
}

Leave a Comment