1

Here is my code:

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; // For Safari
    document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera
}
Blue
  • 22,608
  • 7
  • 62
  • 92
  • That's because you are simply setting the scrollTop to 0. If you want a transition/animation you have to define it yourself, or use one of the many libraries out there that will help you do it such as jQuery. For example, https://stackoverflow.com/questions/5580350/jquery-cross-browser-scroll-to-top-with-animation – David Meza Aug 02 '18 at 15:05
  • Next time please use the search. There are many questions about this (and they actually contain a question and not just a statement and code block), for example this one with 30+ answers, many of them also explaining how to get smooth scrolling: https://stackoverflow.com/questions/1144805/scroll-to-the-top-of-the-page-using-javascript-jquery – Capricorn Aug 02 '18 at 15:12
  • @david meza is there an alternative using only pure javascript? –  Aug 02 '18 at 15:13

0 Answers0