Last active
August 17, 2022 08:13
-
-
Save mortenscheel/e6b6bec0860f6dd8cca99d4adf31c805 to your computer and use it in GitHub Desktop.
Find and highlight DOM elements overflowing the viewport width, causing the horizontal scrollbar to appear.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const detectHorizontalOverflow = (root) => { | |
root = root || document; | |
const { offsetWidth } = document.documentElement; | |
let previousOverflowing = null; | |
let overflowingCount = 0; | |
root.querySelectorAll('*').forEach((el) => { | |
const { right } = el.getBoundingClientRect(); | |
if (right > offsetWidth) { | |
// Ignore the children of overflowing elements. The issue is probably their parents. | |
if (previousOverflowing === null || !previousOverflowing.contains(el)) { | |
console.log('Right edge at %dpx, overflowing %dpx', right, right - offsetWidth, el); | |
el.style.opacity = '1'; | |
el.style.visibility = 'visible'; | |
el.style.backGroundColor = 'rgba(255,0,0,.3)'; | |
el.style.outline = '1px solid #f00'; | |
previousOverflowing = el; | |
overflowingCount++; | |
} | |
} | |
}); | |
return overflowingCount; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment