Home > OS >  How can I make a button that scrolls back to the top of the page when you click on it
How can I make a button that scrolls back to the top of the page when you click on it

Time:10-06

but when your fully at the top it disappears and when you scroll down a but it stays there.

Here is the Javascript for it


btnScrollToTop.addEventListener("click", function() {
    
    window.scrollTo({
        top: 0,
        left: 0,
        behavior: "smooth"
    });

});

The arrow button scrolls to the top of the page when you press on it.

Here is the top of the page

What I want to do is so when your at the top of the page the button disappears but when you scroll a little it comes back so you can press it. Is there any simple way to do that?

CodePudding user response:

First, add an event listener on the page scroll. In the event handler, change the button display accordingly to scroll position.

Then, set your button display to none by default.

Beware: if the user comes back on the page, without scrolling, the button won't be shown even if the page is scrolled. To prevent this, call the event handler on page load.

const scrollHandler = () => {
  const scrollPosition = window.scrollY 
  if ( scrollPosition > 0) {
    btnScrollTop.style.display = 'block'
  } else {
    btnScrollTop.style.display = 'none'
  }
}

document.addEventListener('scroll', scrollHandler)
window.onload = scrollHandler

CodePudding user response:

You can use the scrollY property in the window. And then, check if it has reached a certain offset, and then do actions on it.

window.addEventListener("scroll", (event) => {
    let scroll = this.scrollY;
    console.log(scroll);
    // do something here with y offset
});
  • Related