You can check if window.scrollY
(the number of pixels the window has scrolled vertically) is equal to 0
. If you want to check if the window has been scrolled to its leftermost, you can check if window.scrollX
(the number of pixels the window has scrolled horizontally) is equal to 0
. If you combine the two, it will ensure the window is at (0,0) position.
if(window.scrollY==0){
//user scrolled to the top of the page
}
if(window.scrollX==0){
//user scrolled to the leftmost part of the page
}
if(window.scrollY==0&&window.scrollX==0){
//user scrolled to the leftmost part of the top of the page—i.e., they are at position (0, 0)
}
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 better browser compatibility, use window.pageYOffset
instead of window.scrollY
and window.pageXOffset
instead of window.scrollX
.
The following code can be used in cases when full browser compatability is necessary (i.e., IE < 9):
var x = (window.pageXOffset !== undefined)
? window.pageXOffset
: (document.documentElement || document.body.parentNode || document.body).scrollLeft;
//number of pixels scrolled horizontally (work with 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)