Sometimes, we want to determine if an HTML element’s content overflows with JavaScript.
In this article, we’ll look at how to determine if an HTML element’s content overflows with JavaScript.
How to determine if an HTML element’s content overflows with JavaScript?
To determine if an HTML element’s content overflows with JavaScript, we can compare if the child element’s width is longer than the parent element’s width.
For instance, we write
const checkOverflow = (elem) => {
const elemWidth = elem.getBoundingClientRect().width;
const parentWidth = elem.parentElement.getBoundingClientRect().width;
return elemWidth > parentWidth;
};
to get the elem
element’s width with
elem.getBoundingClientRect().width
Then we get elem
‘s parent’s width with
elem.parentElement.getBoundingClientRect().width;
Both widths are in pixels.
And if elemWidth
is bigger than parentWidth
, elem
overflows the parent container.
Conclusion
To determine if an HTML element’s content overflows with JavaScript, we can compare if the child element’s width is longer than the parent element’s width.