1

I created a database to display information to my user. I decided to put a "To the top of the page" button to help my users scroll to the very top of the page. It worked fine when I used <script> tags but I decided to clean it up (hoping to code like the pros) and create an external js folder, but it stopped working when I did so. I could no longer see the button when I scrolled down the page. I have very little experience with scripts, so any help is much appreciated.

<head>
        <link rel="stylesheet" href="styles.css">
        <script src="/js/top.js"></script>    
   
</head>
<body>
<button onclick="topFunction()" id="myBtn" title="Go to top">Return to Top</button>

js external file - top.js

//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;
        }
    
Joe904
  • 39
  • 9
  • Seems to me like the old problem, where a script is executed before the document is loaded completely. You might go for that: https://stackoverflow.com/questions/807878/how-to-make-javascript-execute-after-page-load – Mister Henson Sep 02 '20 at 23:00

2 Answers2

2

You include the script before myButton is in the DOM so your call to document.getElementById("myBtn"); returns undefined. You should include your <script> tag at the end of the page (just before </html>, so all the of the DOM is loaded before you try to do any operations.

There are other methods to this as well for instance

document.addEventListener('DOMContentLoaded', function() { 
// your code here
})

would only run your code after the DOM content is loaded.

Victory
  • 5,811
  • 2
  • 26
  • 45
1

I kept playing with it and took the suggestions mentioned (thanks). It is working now. I moved the <button> and <script> tags before the </body tag.

<button onclick="topFunction()" id="myBtn" title="Go to top">Return to Top</button>
<script src="js/top.js" defer></script>
Joe904
  • 39
  • 9