Home > Software design >  Scroll back to top button using JavaScript appears all the time
Scroll back to top button using JavaScript appears all the time

Time:10-06

I created a scroll back to top button, which I would like to appear on the page only after the page was scrolled down a bit. However, the button appears when opening the page for the first time, but after scrolling down and up again it disappears - acting therefore as it should. I looked too much over the code and can't see where the issue is anymore :) How should I change the code below so that the button will appear only after scrolling?

HTML part:

<button onclick="topFunction()" id="button" title="Go to the top">^</button>

JavaScript part:

var myButton = document.getElementById("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";
    }
}

function topFunction() {
    document.body.scrollTop = 0;
    document.documentElement.scrollTop = 0;
}

Thank you for your time!

CodePudding user response:

Hide it by default is probably the best option to avoid glitching/flashing.

<button style="display: none;" onclick="topFunction()" id="button" title="Go to the top">^</button>
  • Related