Skip to content

Instantly share code, notes, and snippets.

@julianklotz
Last active April 8, 2020 13:26
Show Gist options
  • Save julianklotz/285a19033b47f5a6990304ac1d209ec1 to your computer and use it in GitHub Desktop.
Save julianklotz/285a19033b47f5a6990304ac1d209ec1 to your computer and use it in GitHub Desktop.
This code snippet checks a web page for elements that (may) exceed the browser’s viewport width.
/*global
window, document, console
*/
/**
* This code snippet checks a web page for elements that (may) exceed the browser’s viewport width.
*
* You’ve built a HTML page and for some reason, there’s a vertical scrollbar.
* It scrolls just a tiny bit, but when ever you scroll down, the page glitches right and left slightly.
* This piece of JavaScript loops all DOM nodes and nodes that are wider than the window’s viewport.
* You’ll get a list of nodes that may cause the vertical scrolling.
*
* Usage: Copy and paste this to your browser’s console and hit <Enter>.
*
* Copyright 2020 Julian Klotz
* Date 2020-04-08
* Released under the MIT License.
*/
const viewportWidth = window.innerWidth;
let walkDocumentNodes;
let callback;
let getElementWidth;
walkDocumentNodes = function walk(node, callback) {
callback(node);
node = node.firstChild;
while (node) {
walk(node, callback);
node = node.nextSibling;
}
};
getElementWidth = function (node) {
let style;
try {
style = window.getComputedStyle(node);
} catch (ignore) {
return;
}
let width = node.offsetWidth;
let margin = parseFloat(style.marginLeft) + parseFloat(style.marginRight);
return (width + margin);
};
callback = function (node) {
let nodeWidth = getElementWidth(node);
if (nodeWidth > viewportWidth) {
console.log("---");
console.log("Node exceeds viewport size:");
console.log(" Node:", node);
console.log(" Viewport width:", viewportWidth);
console.log(" Element width:", nodeWidth);
}
};
walkDocumentNodes(document, callback);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment