var headPos = window.scrollY;
window.onscroll = function(){
headPos = window.scrollY;
}
window.onscroll = visi;
function visi(){
if(headPos < 1300){
document.getElementById("goBackUp").style.visibility = "hidden";
}
else if(headPos > 1301){
document.getElementById("goBackUp").style.visibility = "visible";
}
}
Hello, so I wanted to have the ability to show this scrollToTop button on my html page using scroll position but it doesn't seem to work correctly.
CodePudding user response:
So several things, specifically your doubled onscroll
. See simplified example below.
const btn = document.getElementById("goBackUp");
handleScroll = () => btn.style.display = (window.scrollY < 1300) ? 'none' : 'block';
document.addEventListener('scroll', handleScroll);
#goBackUp {
position: fixed;
right: 1rem;
bottom: 1rem;
background-color: #0f0;
color: #fff;
padding: 1rem;
display: none;
}
<div id="goBackUp">GO BACK UP</div>
<br><br><br>
Now Scroll down....
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
CodePudding user response:
I think you owerwrote the assigned function to window onscroll every time you assigned a new function.
Use one function instead, like this:
If you comment out the console log, you can see the scrollY value, on every scroll event.
window.onscroll = visi;
function visi(){
headPos = window.scrollY;
//console.log(headPos);
if(headPos < 1300){
document.getElementById("goBackUp").style.visibility = "hidden";
}
else if(headPos > 1300){
document.getElementById("goBackUp").style.visibility = "visible";
}
}
<div style="background-color:black;height:1800px"></div>
<div id="goBackUp">Go back up</div>