Categories
JavaScript Answers

How to determine if an HTML element’s content overflows with JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *