Skip to content

Instantly share code, notes, and snippets.

@craigmj
Created November 28, 2019 16:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save craigmj/402f97f5b43c701aec52d444045f7bef to your computer and use it in GitHub Desktop.
Save craigmj/402f97f5b43c701aec52d444045f7bef to your computer and use it in GitHub Desktop.
Javascript method to find an element in html that causes a page to horizontally scroll. See console output for element tree - last element is the culprit.
<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
</head>
<body>
<div id="outer">
<div id="inner">
<div id="third" style="width: 2500px;">
This is probably the issue.
</div>
</div>
</div>
<script>
function find_element_causing_hscroll(el, depth=0) {
if (!el) {
el = document.querySelector("body");
}
if (!depth) {
depth = 0;
}
for (var i in el.children) {
if (document.body.scrollWidth > window.innerWidth) {
var c = el.children[i];
if (1==c.nodeType) {
var d = c.style.display;
c.style.display = 'none';
var fixed = (document.body.scrollWidth <= window.innerWidth);
c.style.display = d;
if (fixed) {
console.log('Element causing hscroll: ', c);
find_element_causing_hscroll(c, depth+1);
}
}
}
}
}
window.addEventListener('load', function() {
find_element_causing_hscroll();
});
</script>
</body></html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment