The HTML element’s scrollWidth
property has the full width of the content in an element.
The HTML element’s scrollHeight
property has the full height of the content in an element.
The HTML element’s clientWidth
property has the width of the content in an element that’s displayed.
The HTML element’s clientHeight
property has the height of the content in an element that’s displayed.
Therefore, we can compare them to see if any content overflows.
If scrollWidth
is bigger than clientWidth
or scrollHeight
is bigger than clientHeight
, then we know content is overflowing.
For instance, if we have the following HTML:
<div style='width: 100px; height: 100px; overflow: auto'>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer efficitur mauris at nisl accumsan suscipit. Aliquam tempus ultrices consectetur.
</div>
Then we can check if the div’s content is overflowing the div by writing:
const checkOverflow = (el) => {
const isOverflowing = el.clientWidth < el.scrollWidth ||
el.clientHeight < el.scrollHeight;
return isOverflowing;
}
const div = document.querySelector('div')
console.log(checkOverflow(div))
We create the checkOverflow
function that takes the el
DOM element object as the parameter.
And return the comparison between clientWidth
and scrollWidth
and clientHeight
and scrollHeight
as we described.
The console log should log true
since the text in the div overflows the height of the div, so el.clientHeight < el.scrollHeight
returns true
.