// When the user scrolls, show or hide the button with fade-in effect window.onscroll = function() { scrollFunction(); }; function scrollFunction() { var scrollTop = document.documentElement.scrollTop || document.body.scrollTop; var scrollHeight = document.documentElement.scrollHeight - document.documentElement.clientHeight; var scrollPercentage = (scrollTop / scrollHeight) * 100; // Show the button when the user has scrolled 5% down the page if (scrollTop > 500 || scrollPercentage > 5) { document.getElementById("myBtn").classList.add("show"); } else { document.getElementById("myBtn").classList.remove("show"); } } // 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 }