ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

How-To: 50+ Real-World Developer Recipes• 5 min read

How To: Smooth Scroll to Top Button

Create a floating "Back to Top" button that only appears after scrolling down 300px and smoothly scrolls back to the top.

Tracking Scroll Position & Triggering Smooth Scroll

Use window.addEventListener("scroll") with a threshold check (e.g. window.scrollY > 300) to toggle the button visibility.

When clicked, call window.scrollTo({ top: 0, behavior: "smooth" }) for a cinematic glide back to the header.

Floating Scroll to Top Implementation
const scrollBtn = document.getElementById('scrollToTopBtn');

window.addEventListener('scroll', () => {
  if (window.scrollY > 300) {
    scrollBtn.classList.add('visible');
  } else {
    scrollBtn.classList.remove('visible');
  }
});

scrollBtn.addEventListener('click', () => {
  window.scrollTo({
    top: 0,
    behavior: 'smooth'
  });
});
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

Which options object passed to window.scrollTo() enables smooth animated scrolling?