Detect Overflows in JavaScript Using this Function

Detect Overflows in JavaScript Using this Function

Easily finding overflowing elements on the page
Ferenc Almasi β€’ πŸ”„ 2022 July 06 β€’ πŸ“– 2 min read

Did it happen to you before that a horizontal scrollbar appeared on your page for smaller screen sizes? This happens because an element overflows the page when it doesn't suppose to. The real issue comes when you need to find that element.

It is not always as obvious as scrolling through the page and spotting the overflown content. Especially when you have multiple of these elements.

To detect overflowing elements on your page, you can copy and paste the following code snippet into your app.

const findOverflows = () => {
    const documentWidth = document.documentElement.offsetWidth;

    document.querySelectorAll('*').forEach(element => {
        const box = element.getBoundingClientRect();

        if (box.left < 0 || box.right > documentWidth) {
   = '1px solid red';

// Execute findOverflows to find overflows on the page.
Copied to clipboard!
Looking to improve your skills? Check out our interactive course to master JavaScript from start to finish.
Master JavaScript

How this function works

Let's break this code down line-by-line so we fully understand how does it work:

  • On line:2, we start off by getting the width of the page and storing it in the documentWidth variable. We will use this inside the if statement later on.
  • Then we select every DOM element, using the wildcard star selector, and inside a forEach loop, we get the current element's position, using getBoundingClientRect. This returns its top, left, and bottom, right coordinates that we can use to determine if the element overflows.
  • In the if statement, we check if the element's left position is less than 0, which means it overflows to the left. If its right is greater than the width of the document, it overflows to the right.
  • Inside the if, we can then log the element to the console so we can quickly navigate to it, and we also add a 1px red border, so it's easier to spot.

Execute the above function inside your console to immediately add red borders around overflowing elements on your page. This way you can easily spot them.

How to Find Overflowing Elements With JavaScript
If you would like to see more Webtips, follow @flowforfrank

50 JavaScript Interview Questions
Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Unlimited access to hundred of tutorials
  • check Access to exclusive interactive lessons
  • check Remove ads to learn without distractions
Become a Pro