Reputation: 491
My "back-to-top" button is working correctly. However, the button is being displayed on the top of the page which I want to hide and display after 20 scrolls. I am using the example from w3 schools. This throws error when I use it in my code. How do I fix it?
Error
> (index):115 Uncaught TypeError: Cannot read property 'style' of null
at scrollFunction ((index):115)
at window.onscroll ((index):108)
scrollFunction @ (index):115
window.onscroll @ (index):108
Here's my CSS:
#myBtn {
width: 3rem;
height: 3rem;
align-items:center !important;
}
#myBtn svg {
fill: #000;
display: block !important;margin: auto !important;
}
My Javascript is as below:
/** Scroll back-to-top */
//Get the button
var mybutton = document.getElementById("myBtn");
// When the user scrolls down 20px from the top of the document, show the button
window.onscroll = function() {scrollFunction()};
function scrollFunction() {
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
mybutton.style.display = "block";
} else {
mybutton.style.display = "none";
}
}
// When the user clicks on the button, scroll to the top of the document
function topFunction() {
document.body.scrollTop = 0;
document.documentElement.scrollTop = 0;
}
var url = window.location.href;
var index = url.lastIndexOf("/") + 1;
var filename = url.substr(index);
if (filename == "index.html") {
$("top").hide() ;
};
This is my HTML where I define my button.
<button class="myBtn" type="button" aria-label="Back to Top" style="float:right;" onclick="topFunction()" id="myBtn">
<svg focusable="false" preserveAspectRatio="xMidYMid meet" xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 32 32" aria-hidden="true" style="will-change: transform;">
<path d="M16 14L6 24 7.4 25.4 16 16.8 24.6 25.4 26 24zM4 8H28V10H4z"></path></svg></button>
Upvotes: 0
Views: 297
Reputation: 950
You've defined the variable mybutton
outside of the function scrollFunction()
. Try defining it inside the function, like this:
function scrollFunction() {
var mybutton = document.getElementById("mybtn")
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
mybutton.style.display = "block";
} else {
mybutton.style.display = "none";
}
}
or pass it in as a parameter like this:
function scrollFunction(mybutton) {
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
mybutton.style.display = "block";
} else {
mybutton.style.display = "none";
}
}
Upvotes: 1
Reputation: 206
There is only 1 mistake. Just Change
var mybutton = document.getElementById("top"); to
var mybutton = document.getElementById("myBtn");
Apart from this, add display:none
to the button. So that, it does not display by default.
Upvotes: 1