I am trying to make a gototop button with javascript (not jQuery). I want this button to have a delay effect which I achieve by:
var timeOut;
function scrollToTop() {
if (document.body.scrollTop!=0 || document.documentElement.scrollTop!=0){
window.scrollBy(0,-50);
timeOut=setTimeout('scrollToTop()',10);
}
else clearTimeout(timeOut);
}
The html is a simple:
<div id="gototop"><a href="#header" onclick="scrollToTop();return false">Back to top</a></div>
I am not able to make to button show/hide depending on scroll height. As far as I have been able to find out, the following should hide the button from view until the page has been scrolled down 600px, but this does not work:
var posit = window.scrollTop();
if (posit < 900) {
document.getElementById("gototop").style.display = 'none';
}
Why does this styling not take effect?
The complete code I am using is:
var posit = window.scrollTop();
if (posit < 900) {
document.getElementById("gototop").style.display = 'none';
}
var timeOut;
function scrollToTop() {
if (document.body.scrollTop!=0 || document.documentElement.scrollTop!=0){
window.scrollBy(0,-50);
timeOut=setTimeout('scrollToTop()',10);
}
else clearTimeout(timeOut);
}
Thanks for your attention, greetings.
Try putting it into the onscroll event handler, like:
Add style to your gototop element, for example:
<div id="gototop" onclick="scrollToTop()" style="display:none;"> </div>
window.onscroll = function(){
if (window.scrollY < 900) {
document.getElementById("gototop").style.display = 'none';
else
document.getElementById("gototop").style.display = 'block';
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With