Reputation: 31
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.
Upvotes: 3
Views: 237
Reputation: 31
This is the complete working code for a Back-to-top button.
<style type="text/css">
#gototop{display:none;position:fixed;right:28px;bottom:10px;z-index:100;}
#gototop a{font-size:14px;font-weight:bold;display:block;padding:5px;text-decoration:none;color:#fff;background:#000;opacity:0.5;border:1px solid #aaa;}
#gototop a:hover{color: #000;text-decoration:underline;background-color:#fff;border: 2px solid #aaa;opacity:0.5;}
</style>
<script type="text/javascript" language="javascript">
// document.documentElement.scrollTop makes it work in Chrome and IE
// 400 is the point from which the button starts showing, you can change it to your needs
gototop = document.getElementById("gototop");
window.onscroll = function(){
if (window.scrollY < 400 || document.documentElement.scrollTop < 400) {
gototop.style.display = 'none';
}
if (window.scrollY > 400 || document.documentElement.scrollTop > 400)
gototop.style.display = 'block';
}
var timeOut;
function scrollToTop() {
if (document.body.scrollTop!=0 || document.documentElement.scrollTop!=0){
window.scrollBy(0,-50);
timeOut=setTimeout('scrollToTop()',10);
}
else clearTimeout(timeOut);
}
</script>
<div id="gototop"><a href="#header" onclick="scrollToTop();return false">Back to Top</a></div>
Upvotes: 0
Reputation: 12693
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';
}
Upvotes: 2