About this snippet

Improve navigation on long pages with this back-to-top button. It stays hidden until the user scrolls down, and then smoothly animates the page back to the header when clicked.

Size
1.1 KB
Uses
HTML, CSS, JavaScript
Loads
Nothing external
Views
379
<button id="backToTop" aria-label="Back to top">&#8679;</button>
<div style="height: 1500px; padding: 20px;">Scroll down to see the button appear.</div>
#backToTop {
  position: fixed;
  bottom: 30px;
  right: 30px;
  width: 50px;
  height: 50px;
  background: #2563eb;
  color: white;
  border: none;
  border-radius: 50%;
  font-size: 1.5rem;
  cursor: pointer;
  box-shadow: 0 4px 12px rgba(37, 99, 235, 0.4);
  opacity: 0;
  visibility: hidden;
  transition: opacity 0.3s, transform 0.3s, background 0.2s;
  z-index: 999;
  display: flex;
  align-items: center;
  justify-content: center;
}
#backToTop.show {
  opacity: 1;
  visibility: visible;
}
#backToTop:hover {
  transform: translateY(-5px);
  background: #1d4ed8;
}
const btn = document.getElementById("backToTop");

window.onscroll = function() {
  if (document.body.scrollTop > 300 || document.documentElement.scrollTop > 300) {
    btn.classList.add("show");
  } else {
    btn.classList.remove("show");
  }
};

btn.addEventListener("click", function() {
  window.scrollTo({
    top: 0,
    behavior: "smooth"
  });
});
Esc
↑↓ moveEnter select

Start from a template

Open an .html file, or HTML, CSS, JS, Markdown, Less or TypeScript files. You can also drop them here. Styles and scripts go into their panes.

Share

Source

Keyboard shortcuts

Save