Detect Overflows in JavaScript Using this Function
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) {
console.log(element);
element.style.border = '1px solid red';
}
});
};
// Execute findOverflows to find overflows on the page.
findOverflows();
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 theif
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, usinggetBoundingClientRect
. This returns itstop
,left
, andbottom
,right
coordinates that we can use to determine if the element overflows. - In the
if
statement, we check if the element'sleft
position is less than 0, which means it overflows to the left. If itsright
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.
Rocket Launch Your Career
Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies: