Button to scroll up on the page is giving an unnecessary load

Asked

Viewed 17 times

0

Good afternoon, I created a button to scroll up the page every time the user scrolls but every time I click the button it gives a strange load.

This is my script:

<script>
    // 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) {
            document.getElementById("myBtn").style.display = "block";
        } else {
            document.getElementById("myBtn").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;
    }
</script>

My button:

<button onclick="topFunction()" id="myBtn" title="Go to top"><i class="fas fa-chevron-up"></i></button>
  • What is "odd load"?

  • When I click the button the page gives load, my intention is to make the button just scroll to the top of the page without any load.

  • An anchor would not be more effective?

  • 1

    Make sure the button is inside a form. Place type="button" in it. Indeed, if it is within a form, it is wrong. It should be outside.

  • Thanks Sam that solved :)

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.