Reputation: 106
So, im building a website right now, and ive setup a button which when you scroll down a short distance it should appear, and when you click it, it sends you to the top of the page. But for some reason, the button is visible at all times, even when im at the top, here is my code:
document.getElementById("scrollButton").onclick = goToTop();
window.onscroll = function() {
"use strict";
scrollFunction();
};
function scrollFunction() {
"use strict";
if ((document.body.scrollTop > 20) || (document.documentElement.scrollTop > 20)) {
document.getElementById("scrollButton").style.display = "block";
} else {
document.getElementById("scrollButton").style.display = "none";
}
}
function goToTop() {
"use strict";
document.body.scrollTop = 0;
document.documentElement.scrollTop = 0;
}
.scrollButton {
position: fixed;
bottom: 20px;
right: 30px;
z-index: 99;
font-size: 18px;
border: none;
outline: none;
background-color: red;
color: white;
cursor: pointer;
padding: 15px;
border-radius: 4px;
}
.scrollButton:hover {
background-color: #555;
}
#fill {
height: 150vh
}
<div id='fill'></div>
<button onclick="goToTop();" class="scrollButton" id="scrollButton" title="Go to top">Top</button>
Im not sure what is wrong, on the "scrollFunction()" in javascript, it says when i scroll down, it should make it appear, but when im at the top, it should dissapear, but it doesnt. Anyone know why?
Upvotes: 1
Views: 75
Reputation: 1646
You need to set display:none
by default.
document.addEventListener('DOMContentLoaded', function() {
scrollFunction();
})
document.getElementById("scrollButton").onclick = goToTop;
window.onscroll = function() {
"use strict";
scrollFunction();
};
function scrollFunction() {
"use strict";
if ((document.body.scrollTop > 20) || (document.documentElement.scrollTop > 20)) {
document.getElementById("scrollButton").style.display = "block";
} else {
document.getElementById("scrollButton").style.display = "none";
}
}
function goToTop() {
"use strict";
document.body.scrollTop = 0;
document.documentElement.scrollTop = 0;
}
.scrollButton {
position: fixed;
bottom: 20px;
right: 30px;
z-index: 99;
font-size: 18px;
border: none;
outline: none;
background-color: red;
color: white;
cursor: pointer;
padding: 15px;
border-radius: 4px;
}
.scrollButton:hover {
background-color: #555;
}
#fill {
height: 150vh
}
<div id='fill'></div>
<button onclick="goToTop();" class="scrollButton" id="scrollButton" title="Go to top">Top</button>
Upvotes: 2