I followed w3 schools guide on how to make a scroll back top top button in your html with javascript. When I put the javascript and html where they should be one of the javascript function didn’t work. It got greyed out in vscode and in chrome console it says that the "function is not defined".
This is how it looks in vscode:
I tried rewriteing the code in the html and js but with no luck. I also tried writeing a new function under the "topFunction" function and that also gets greyed out so I don’t know whats seems to be the problem.
And this is the whole javascript with html:
https://jsfiddle.net/md5pf3hx/ a jsfiddle with the whole site
<button onclick="topFunction()" id="myBtn" title="Go to top">Top</button>
//Get the button:
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; // For Safari
document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera
}
2
Answers
You can’t access
topFunction
because it’s declared insideloadScript
function.You need to remove
loadScript
functionIf you want the script run after the page is loaded you can add
defer
parameterYou’re issue is you do not have
topFunction
defined in Global scope. To allow your HTML to have access to invoketopFunction
, you can move it outside of theloadScript
definition.However, you should be using the built-in
defer
attribute of the HTML<script>
element to execute JavaScript after your HTML has finished loading.This way, you can remove the need for
load
event listeners and whole-script function wrappers:Hope this helps.