Created
November 28, 2019 16:34
-
-
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.
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
<!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