Try 'magnetic button'
View code

Specification

Catalogue
No. 76 of 110
Interaction
Drag, Feedback
Element
Button
Preview
Live component
Imports
react 19.3.1, framer-motion 12.40.0
Added

Notes

Push the handle across the track to pay. Only the very end commits; let go anywhere short of it and the handle springs home. At the end the handle unfurls leftward to fill the track, its arrow becomes a tick, and after a moment it resets.

Payments, bookings and other final steps on a phone, where a tap can be accidental and a slide cannot. It does the job of hold to confirm with a different gesture, and it has a keyboard path: Enter or Space confirms, and the arrow keys move the handle.

The handle follows the pointer one to one and swells to 1.03 while held. The commit spring is critically damped (stiffness 580, mass 0.9); the return is under-damped at 62% of critical, so the handle settles home with a little give. The label fades over the first 55% of the travel. On commit the track dips to 0.974 and back over 420ms, peaking 62% of the way through, cubic-bezier(.33, .55, .2, 1) after 100ms, and the tick fades and scales up from 0.7 in 160ms. The result stands for 1.5s. The handle is a 48px button. Instant under reduced motion.

The booking and price are sample content, and paying is simulated.

Code

React and plain CSS
"use client";

import { useEffect, useId, useRef, useState, type KeyboardEvent, type PointerEvent as ReactPointerEvent } from "react";
import { animate, motion, useMotionValue, useTransform } from "framer-motion";
import type { LivePreviewProps } from "@/components/live/types";
import { tourDrag } from "@/components/pieces/kit/tour-drag";
import { useSafeReducedMotion } from "@/components/pieces/kit/use-safe-reduced-motion";
import { PieceStage } from "@/components/pieces/stage/PieceStage";
import type { Tour } from "@/components/pieces/stage/tour";
import "./slide-to-confirm.css";

const TRACK = 300;
const PAD = 4;
const HANDLE = 48;
const MAX = TRACK - PAD * 2 - HANDLE;
const STAND_MS = 1500;
/** Commit spring: stiffness 580, mass 0.9, critically damped. */
const COMMIT = { type: "spring" as const, stiffness: 580, mass: 0.9, damping: 2 * Math.sqrt(580 * 0.9) };
/** The return is under-damped (62% of critical), so the handle settles home with a little give. */
const RETURN = { type: "spring" as const, stiffness: 580, mass: 0.9, damping: 0.62 * 2 * Math.sqrt(580 * 0.9) };

type Phase = "idle" | "dragging" | "done";

function SlideDemo() {
  const reduce = useSafeReducedMotion();
  const uid = useId();
  const [phase, setPhase] = useState<Phase>("idle");
  const x = useMotionValue(0);
  const unfurl = useMotionValue(0);
  // The label fades out over the first 55% of the travel.
  const labelOpacity = useTransform(x, [0, MAX * 0.55], [1, 0]);
  const width = useTransform(unfurl, (u) => HANDLE + u * MAX);
  const left = useTransform([x, unfurl], ([px, u]: number[]) => (px ?? 0) - (u ?? 0) * MAX);
  const track = useRef<HTMLDivElement>(null);
  const handle = useRef<HTMLButtonElement>(null);
  const detach = useRef<(() => void) | null>(null);
  const timer = useRef<number | undefined>(undefined);

  useEffect(
    () => () => {
      detach.current?.();
      window.clearTimeout(timer.current);
    },
    [],
  );

  const commit = () => {
    setPhase("done");
    if (reduce) {
      x.jump(MAX);
      unfurl.jump(1);
    } else {
      void animate(x, MAX, COMMIT);
      // The handle unfurls leftward to fill the track; the track dips and recovers.
      void animate(unfurl, 1, { ...COMMIT, delay: 0.05 });
      track.current?.animate([{ scale: 1 }, { scale: 0.974, offset: 0.62 }, { scale: 1 }], { duration: 420, delay: 100, easing: "cubic-bezier(0.33, 0.55, 0.2, 1)" });
    }
    // Simulated payment. A real build stands the tick only once the server confirms.
    timer.current = window.setTimeout(reset, STAND_MS);
  };
  const reset = () => {
    setPhase("idle");
    if (reduce) {
      x.jump(0);
      unfurl.jump(0);
      return;
    }
    void animate(unfurl, 0, RETURN);
    void animate(x, 0, RETURN);
  };

  const onDown = (e: ReactPointerEvent<HTMLButtonElement>) => {
    if (phase === "done" || e.button !== 0) return;
    e.preventDefault();
    const el = e.currentTarget;
    const scale = el.getBoundingClientRect().width / el.offsetWidth || 1;
    const startX = e.clientX;
    const from = x.get();
    x.stop();
    setPhase("dragging");
    const move = (ev: PointerEvent) => x.set(Math.min(MAX, Math.max(0, from + (ev.clientX - startX) / scale)));
    const up = () => {
      stop();
      // Only the very end commits; anything short of it springs home.
      if (x.get() >= MAX - 0.5) commit();
      else {
        setPhase("idle");
        if (reduce) x.jump(0);
        else void animate(x, 0, RETURN);
      }
    };
    const stop = () => {
      window.removeEventListener("pointermove", move);
      window.removeEventListener("pointerup", up);
      window.removeEventListener("pointercancel", up);
      detach.current = null;
    };
    detach.current?.();
    window.addEventListener("pointermove", move);
    window.addEventListener("pointerup", up);
    window.addEventListener("pointercancel", up);
    detach.current = stop;
  };

  // The keyboard path: Enter or Space confirms; the arrows move the handle, and reaching the end confirms.
  const onKey = (e: KeyboardEvent<HTMLButtonElement>) => {
    if (phase === "done") return;
    if (e.key === "ArrowRight" || e.key === "ArrowLeft") {
      e.preventDefault();
      const next = Math.min(MAX, Math.max(0, x.get() + (e.key === "ArrowRight" ? MAX / 5 : -MAX / 5)));
      if (next >= MAX) commit();
      else if (reduce) x.jump(next);
      else void animate(x, next, COMMIT);
    } else if (e.key === "End") {
      e.preventDefault();
      commit();
    }
  };

  return (
    <div className="dm sc">
      <p className="sc-sum">
        <span>Two places, Saturday wheel class</span>
        <strong>£48</strong>
      </p>
      <motion.div ref={track} className="sc-track" data-phase={phase} style={{ width: TRACK }}>
        <motion.span className="sc-label" style={{ opacity: labelOpacity }} aria-hidden="true">
          Slide to pay £48
        </motion.span>
        <motion.span className="sc-done" aria-hidden="true">
          Paid
        </motion.span>
        <motion.button
          ref={handle}
          type="button"
          className="sc-handle"
          style={{ x: left, width }}
          aria-label="Pay £48"
          aria-describedby={`${uid}-hint`}
          aria-disabled={phase === "done" || undefined}
          onPointerDown={onDown}
          onClick={(e) => {
            // A pointer drag ends in a click too; only a keyboard press confirms from here.
            if (e.detail === 0 && phase !== "done") commit();
          }}
          onKeyDown={onKey}
        >
          <svg className="sc-arrow" viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
            <path d="M5 12h14M13 6l6 6-6 6" />
          </svg>
          <svg className="sc-check" viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
            <path d="M5 12.5l4.5 4.5L19 7.5" />
          </svg>
        </motion.button>
      </motion.div>
      <p id={`${uid}-hint`} className="sc-hint">
        Slide to the end, or press Enter
      </p>
      <p className="sr-only" role="status">
        {phase === "done" ? "Paid. This preview takes no money." : ""}
      </p>
    </div>
  );
}

// What a hovered card shows: the handle pushed all the way across, the track filling, and the tick.
const TOUR: Tour = [
  {
    run: (root) => {
      const h = root.querySelector(".sc-handle");
      const t = root.querySelector(".sc-track");
      if (h && t) tourDrag(h, [0.09, 0.5], [0.99, 0.5], 900, { box: t });
    },
    wait: 2600,
  },
];

export default function SlideToConfirmEntry(props: LivePreviewProps) {
  return (
    <PieceStage {...props} label="Slide to confirm" tour={TOUR} sample>
      <SlideDemo />
    </PieceStage>
  );
}

More like this

Currency swap that trades places

Press, Layout AnimationForms and inputs

Price range over the prices it filters

DragForms and inputs

Delete that asks where you clicked

Press, FeedbackButtons and toggles

Code field that behaves as one input

Type, FeedbackForms and inputs

Hold to confirm

Press, FeedbackButtons and toggles

Save to a collection

FeedbackButtons and toggles