Layout

Scroll to top

Button that appears after scrolling down.

Preview
Live demo coming - the component is in the registry below.
Install
npx shadcn@latest add https://ui.thjsecurity.tech/r/scroll-top.json

Pulls the component into components/ui/scroll-top.tsx and its token dependencies. The app owns the copy from then on.

Dependencies
@tabler/icons-react
Source
"use client"

import * as React from "react"
import { IconArrowUp } from "@tabler/icons-react"

import { cn } from "@/lib/utils"

/* A round glass button at the bottom right that appears once the page has
   scrolled a screen's worth, and takes you back to the top. */

export function ScrollTop() {
  const [shown, setShown] = React.useState(false)
  React.useEffect(() => {
    const onScroll = () => setShown(window.scrollY > 480)
    onScroll()
    window.addEventListener("scroll", onScroll, { passive: true })
    return () => window.removeEventListener("scroll", onScroll)
  }, [])
  return (
    <button
      type="button"
      aria-label="Back to top"
      tabIndex={shown ? 0 : -1}
      onClick={() => window.scrollTo({ top: 0, behavior: "smooth" })}
      className={cn(
        "fixed bottom-6 right-6 z-30 grid h-11 w-11 place-items-center rounded-full border border-glass-border bg-ink-1 text-paper-dim shadow-lg transition-all duration-200",
        "hover:border-rule-hot hover:text-paper-strong",
        shown ? "translate-y-0 opacity-100" : "pointer-events-none translate-y-3 opacity-0",
      )}
    >
      <IconArrowUp className="size-[19px]" />
    </button>
  )
}