Have made a button when you click it then it sends you at the top of page,but there's a problem with it. I need button Back to Top to appear when the page is scrolled like 100px and if it goes below 100px to dissapear, have tried from my examples but didn't worked.
function animateToTop(e) { e.preventDefault(); let scrollToTop = window.setInterval(function() { let pos = window.pageYOffset; if (pos > 0 && pageYOffset >= 10) { window.scrollTo(0, pos - 20); document.querySelector('.scrolimg').style.visibility = 'visible'; } else { window.clearInterval(scrollToTop); document.querySelector('.scrolimg').style.visibility = 'visible'; } }, 9); } .scrolimg { width: 88px; height: 79px; } .scroll { width: 100px; height: 80px; position: sticky; top: 640px; left: 1350px; transition: 0.2s; z-index: 99; } .scroll:hover { transform: scale(1.2) } body { height: 1400px; background: yellowgreen; margin: 0; padding: 0; } .bg1 { height: 650px; background: red; } <div class="bg1"></div> <div class="scroll"> <img onclick="animateToTop(event)" class="scrolimg" src="https://www.freeiconspng.com/uploads/arrow-icon-clip-art-file-down-arrow-icon-png-balin-icon-arrow-right--32.png"> </div>
pageYOffsetis undefined, so it will never be>= 10(since it gets converted toNaN) 2) I don't understand your JS, it doesn't do anything until you click the button, and then it sets up a timer to fire every 9 ms? So you have to scroll down to the button before anything happens. 3) You're setting thevisibilityproperty tovisible, but this is the default and you haven't set it tohiddento start withpos(which you've set towindow.pageYOffset). (Actually, I just realised thatpageYOffsetby default will find the global of that name, so my first comment wasn't actually accurate. But this code is still redundant, at best.)