简体   繁体   中英

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

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?

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

Using the Intersection observer would probably be the right approach.

Code Description: What the code below is doing here is - changing the CSS display property of the element with ID buttonID to none when the element with ID topSectionID is 100% visible on the screen.

const topSection = document.getElementById("topSectionID");
let options = {
    root: null,
    rootMargin: "0px",
    threshold: 1.0,
};

let callback = (entries, observer) => {
    entries.forEach((entry) => {
        if (entry.isIntersecting) {
            document.getElementById("buttonID").style.display = 'none'
        } else {
            document.getElementById("buttonID").style.display = 'block';
        }
    });
};

let observer = new IntersectionObserver(callback, options);
observer.observe(topSection);

Here threshold: 1.0 means - execute the intersection observer when 100% of the topSectionID is visible

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM