To determine if the window has scrolled vertically to its top position, you can check the value of window.scrollY
(the number of pixels scrolled vertically) against 0
. If you need to ascertain whether the window has been scrolled to the leftmost position, you can compare window.scrollX
(the number of pixels scrolled horizontally) with 0
. By combining these conditions, you ensure that the window is at the position (0,0).
if(window.scrollY==0){
//user has scrolled to the top of the page
}
if(window.scrollX==0){
//user has scrolled to the leftmost part of the page
}
if(window.scrollY==0&&window.scrollX==0){
//user has scrolled to the leftmost part of the top of the page—reaching position (0, 0)
}
Check out the demo:
var goToTop = document.querySelector('#backToTop');
goToTop.addEventListener("click", function(e){
window.scroll({top: 0, left: 0, behavior: 'smooth'});
//scroll smoothly back to the top of the page
});
window.addEventListener("scroll", function(){
if(window.scrollY==0){
//user is at the top of the page; no need to show the back to top button
goToTop.style.display = "";
} else {
goToTop.style.display = "block";
}
});
body,html{height:3000px;position:relative;margin:0}#footer{position:absolute;width:100%;bottom:0;left:0;right:0;background-color:#1e90ff;text-align:center}#backToTop{position:fixed;right:0;bottom:0;display:none;z-index:1}#header{position:absolute;width:100%;top:0;left:0;right:0;background-color:#1e90ff;text-align:center}
<div id="header">Header</div>
<button id="backToTop">Back To Top</button>
<div id="footer">Footer</div>
For improved browser compatibility, utilize window.pageYOffset
in place of window.scrollY
, and window.pageXOffset
as a replacement for window.scrollX
.
The following code snippet is useful for scenarios where full browser compatibility is essential (e.g., IE < 9):
var x = (window.pageXOffset !== undefined)
? window.pageXOffset
: (document.documentElement || document.body.parentNode || document.body).scrollLeft;
//number of pixels scrolled horizontally (use this value instead of window.scrollX or window.pageXOffset)
var y = (window.pageYOffset !== undefined)
? window.pageYOffset
: (document.documentElement || document.body.parentNode || document.body).scrollTop;
//number of pixels scrolled vertically (work with this value instead of window.scrollY or window.pageYOffset)