Veil UI
Components

Back To Top Button

A floating button that appears after scrolling and returns to the top.

Installation

$ npx veil-ui@latest add back-to-top-button

Usage

import { BackToTopButton } from "@/components/ui/back-to-top-button";

<BackToTopButton className="fixed bottom-6 right-6" size="icon" />;

The button renders nothing until the page has been scrolled past threshold. Position it yourself with classes; the component only handles visibility and the scroll action.

Examples

Basic

Outline

Controlled

Pass `visible` to control it in stories and tours.

API reference

PropTypeDefaultDescription
thresholdnumber400Scroll distance in pixels before the button appears.
visibleboolean—Control visibility yourself instead of tracking window scroll.
labelstring"Back to top"Accessible name of the icon button.
onScrollToTop() => void—Called before the smooth scroll to the top begins.
...propsButtonProps—All Button props; use className to position it.

Accessibility

  • Icon-only trigger carries an accessible label.
  • The scroll listener is passive and removed on unmount.
  • Respects the platform's smooth-scroll behavior; users who reduce motion get the default jump.

Vue and plain HTML

This component also ships for Vue (Reka UI) and plain HTML. Install it with npx veil-ui add back-to-top-button --framework vue or switch the framework in components.json.

<script setup lang="ts">
import { ArrowUp } from "lucide-vue-next";
import { computed, onBeforeUnmount, onMounted, ref } from "vue";

import { Button } from "@/components/ui/button";

const props = withDefaults(
  defineProps<{
    /** Scroll distance in pixels before the button appears. */
    threshold?: number;
    label?: string;
    /** Control visibility yourself instead of tracking window scroll. */
    visible?: boolean;
    variant?: "default" | "secondary" | "outline" | "ghost" | "destructive" | "link";
    size?: "sm" | "default" | "lg" | "icon";
    disabled?: boolean;
    type?: "button" | "submit" | "reset";
    class?: string;
  }>(),
  { threshold: 400, label: "Back to top", type: "button" },
);

const emit = defineEmits<{ scrollToTop: [] }>();

const scrolled = ref(false);

function handleScroll() {
  scrolled.value = window.scrollY > props.threshold;
}

onMounted(() => {
  if (props.visible !== undefined) return;
  handleScroll();
  window.addEventListener("scroll", handleScroll, { passive: true });
});

onBeforeUnmount(() => {
  window.removeEventListener("scroll", handleScroll);
});

const shown = computed(() => props.visible ?? scrolled.value);

function handleClick() {
  emit("scrollToTop");
  window.scrollTo({ top: 0, behavior: "smooth" });
}
</script>

<template>
  <Button
    v-if="shown"
    data-slot="back-to-top-button"
    :aria-label="label"
    :variant="variant"
    :size="size"
    :disabled="disabled"
    :type="type"
    :class="props.class"
    @click="handleClick"
  >
    <ArrowUp aria-hidden />
  </Button>
</template>

On this page