Chrome pageYOffset vs IE6 fixed positioning
2012-02-15
WARNING: This article features ANCIENT code! I'm keeping it online because it's interesting to see what I was thinking 10+ years ago. But you DEFINITELY should not be using this code. Anything you're reading about on this page has changed significantly since this was written.
I spent awhile beating my head on this one today and couldn't find the answer on Google (I know!), so just documenting here for future generations - in Safari and Chrome (so probably anything webkit-based), window.pageYOffset is zero (or something small and unexpected) when you have this in your CSS:
html,body {
height: 100%;
overflow: auto;
}
Those styles are part of a fairly common hack to create fixed positioning in IE6. So they aren't really necessary in the first place.
Firefox has a different behavior, giving the expected scroll height (I dunno which is technically correct standards-wise).
Here's a minimal example demonstrating the difference:
<!DOCTYPE html>
<html>
<head>
<title>Some Title</title>
<style type="text/css">
html,body {
height: 100%;
overflow: auto;
}
</style>
<script type="text/javascript">
// getPageScroll() by quirksmode.com, as seen everywhere
function getPageScroll() {
var xScroll, yScroll;
if (self.pageYOffset) {
yScroll = self.pageYOffset;
xScroll = self.pageXOffset;
} else if (document.documentElement && document.documentElement.scrollTop) {
yScroll = document.documentElement.scrollTop;
xScroll = document.documentElement.scrollLeft;
} else if (document.body) {// all other Explorers
yScroll = document.body.scrollTop;
xScroll = document.body.scrollLeft;
}
return new Array(xScroll,yScroll)
}
</script>
</head>
<body>
<div style="height:1000px"></div>
<a href="#" onclick="console.log(getPageScroll());return false;">Scroll</a>
</body>
</html>
Open this page in Firefox and Chrome (or Safari) and click the button labeled "Scroll" and the computed height will print to the Console.