constBUTTON_ID='topBtn';constDURATION_NAME='--fade-duration';constSHOW_BUTTON='topBtn';constSCROLL_DURATION=300;constSCROLL_CYCLE=15;functioninitialize(_event){constbutton=document.getElementById(BUTTON_ID);constshowButton=(_event)=>{if(window.scrollY>40)button.classList.add(SHOW_BUTTON);elsebutton.classList.remove(SHOW_BUTTON);};constscrollTarget=window;constscrollToTop=(event)=>{lety=window.scrollY;constx=window.scrollX;conststep=Math.floor((y*SCROLL_CYCLE)/SCROLL_DURATION);constnextStep=()=>{y=step<y?y-step:0;window.scrollTo(x,y);if(y>0){setTimeout(nextStep,SCROLL_CYCLE);return;}scrollTarget.focus();};event.target.blur();nextStep();};// Enable animation after everything is loadedconstrootStyle=getComputedStyle(document.documentElement);constduration=rootStyle.getPropertyValue(DURATION_NAME);button.style.setProperty(DURATION_NAME,duration);document.addEventListener('scroll',showButton);button.addEventListener('click',scrollToTop);}if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',initialize);elseinitialize();
Another stab at vanilla:
Modify:
Modify:
Replace: