# Ripple Button

Button that sends a ripple out from the click point, or from the center when pressed with the keyboard.

- Category: Buttons
- Status: stable
- Registry: https://markas.jenderalcorp.com/r/ripple-button.json
- CLI: `npx markasui@latest add ripple-button`

## When to use

Actions that benefit from tactile feedback, such as add to cart, subscribe, or a submit button.

- Use it like Button, onClick and type behave the same
- Do not mix ripple and plain buttons in the same toolbar
- The ripple takes the text color, so it works on every variant

## Code

### Blade

Save at `resources/views/components/markas/ripple-button.blade.php`. Dependencies: alpinejs.

```blade
@props([
    'variant' => 'primary',
    'size' => 'md',
])

@php
    $base = 'relative isolate inline-flex items-center justify-center gap-2 overflow-hidden font-medium whitespace-nowrap transition-colors duration-150 ease-out focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:pointer-events-none disabled:opacity-50 motion-reduce:transition-none';
    $variants = [
        'primary' => 'bg-primary text-on-primary hover:bg-primary-strong',
        'secondary' => 'border border-line bg-surface text-ink hover:bg-subtle',
        'ghost' => 'text-ink hover:bg-subtle',
        'danger' => 'bg-danger text-on-primary hover:bg-danger/90',
    ];
    $sizes = [
        'sm' => 'h-8 rounded-md px-3 text-sm',
        'md' => 'h-10 rounded-lg px-4 text-sm',
        'lg' => 'h-12 rounded-lg px-6 text-base',
    ];
    $layer = 'pointer-events-none absolute inset-0 -z-10';
    $wave = 'absolute rounded-full bg-current opacity-0';
@endphp

{{-- Each click adds one wave, from the pointer or from the center for keyboard clicks. --}}
<button
    x-data="{
        ripple(event) {
            if (window.matchMedia?.('(prefers-reduced-motion: reduce)').matches) return;
            const rect = this.$el.getBoundingClientRect();
            const fromPointer = event.detail > 0;
            const x = fromPointer ? event.clientX - rect.left : rect.width / 2;
            const y = fromPointer ? event.clientY - rect.top : rect.height / 2;
            const diameter = Math.hypot(rect.width, rect.height) * 2;
            const element = document.createElement('span');
            element.className = @js($wave);
            element.style.cssText = `left:${x - diameter / 2}px;top:${y - diameter / 2}px;width:${diameter}px;height:${diameter}px`;
            this.$refs.layer.append(element);
            if (typeof element.animate !== 'function') return element.remove();
            element.animate(
                [{ scale: '0', opacity: 0.25 }, { scale: '1', opacity: 0 }],
                { duration: 600, easing: 'ease-out' },
            ).onfinish = () => element.remove();
        },
    }"
    x-on:click="ripple($event)"
    {{ $attributes->merge(['type' => 'button'])->class([$base, $variants[$variant], $sizes[$size]]) }}
>
    <span x-ref="layer" class="{{ $layer }}" aria-hidden="true"></span>
    {{ $slot }}
</button>
```

```blade
<x-markas.ripple-button>Add to cart</x-markas.ripple-button>
<x-markas.ripple-button variant="secondary" type="submit">Subscribe</x-markas.ripple-button>
```

### React

Save at `src/components/markas/RippleButton.tsx`. No extra dependencies.

```tsx
"use client";

import { useRef, type ComponentProps, type MouseEvent } from "react";

const base =
  "relative isolate inline-flex items-center justify-center gap-2 overflow-hidden font-medium whitespace-nowrap transition-colors duration-150 ease-out focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:pointer-events-none disabled:opacity-50 motion-reduce:transition-none";
const variants = {
  primary: "bg-primary text-on-primary hover:bg-primary-strong",
  secondary: "border border-line bg-surface text-ink hover:bg-subtle",
  ghost: "text-ink hover:bg-subtle",
  danger: "bg-danger text-on-primary hover:bg-danger/90",
};
const sizes = {
  sm: "h-8 rounded-md px-3 text-sm",
  md: "h-10 rounded-lg px-4 text-sm",
  lg: "h-12 rounded-lg px-6 text-base",
};
const layer = "pointer-events-none absolute inset-0 -z-10";
const wave = "absolute rounded-full bg-current opacity-0";

const WAVE = [
  { scale: "0", opacity: 0.25 },
  { scale: "1", opacity: 0 },
];
const WAVE_DURATION = 600;

const cx = (...c: (string | false | null | undefined)[]) =>
  c.filter(Boolean).join(" ");
const reducedMotion = () =>
  typeof window.matchMedia === "function" &&
  window.matchMedia("(prefers-reduced-motion: reduce)").matches;

/** Adds one wave to the layer, from the pointer or from the center for keyboard clicks. */
function ripple(target: HTMLElement, event: MouseEvent<HTMLElement>) {
  const button = target.parentElement;
  if (!button || reducedMotion()) return;
  const rect = button.getBoundingClientRect();
  const fromPointer = event.detail > 0;
  const x = fromPointer ? event.clientX - rect.left : rect.width / 2;
  const y = fromPointer ? event.clientY - rect.top : rect.height / 2;
  const diameter = Math.hypot(rect.width, rect.height) * 2;
  const element = document.createElement("span");
  element.className = wave;
  element.style.cssText = `left:${x - diameter / 2}px;top:${y - diameter / 2}px;width:${diameter}px;height:${diameter}px`;
  target.append(element);
  if (typeof element.animate !== "function") return element.remove();
  element.animate(WAVE, {
    duration: WAVE_DURATION,
    easing: "ease-out",
  }).onfinish = () => element.remove();
}

export type RippleButtonProps = ComponentProps<"button"> & {
  variant?: keyof typeof variants;
  size?: keyof typeof sizes;
};

export function RippleButton({
  variant = "primary",
  size = "md",
  type = "button",
  className,
  children,
  onClick,
  ...props
}: RippleButtonProps) {
  const layerRef = useRef<HTMLSpanElement>(null);

  const handleClick = (event: MouseEvent<HTMLButtonElement>) => {
    if (layerRef.current) ripple(layerRef.current, event);
    onClick?.(event);
  };

  return (
    <button
      type={type}
      onClick={handleClick}
      className={cx(base, variants[variant], sizes[size], className)}
      {...props}
    >
      <span ref={layerRef} className={layer} aria-hidden="true" />
      {children}
    </button>
  );
}
```

```tsx
import { RippleButton } from "@/components/markas/RippleButton";

<RippleButton onClick={addToCart}>Add to cart</RippleButton>
<RippleButton variant="secondary" type="submit">Subscribe</RippleButton>
```

### Vue

Save at `src/components/markas/RippleButton.vue`. No extra dependencies.

```vue
<script setup lang="ts">
import { useTemplateRef } from "vue";

const variants = {
  primary: "bg-primary text-on-primary hover:bg-primary-strong",
  secondary: "border border-line bg-surface text-ink hover:bg-subtle",
  ghost: "text-ink hover:bg-subtle",
  danger: "bg-danger text-on-primary hover:bg-danger/90",
};
const sizes = {
  sm: "h-8 rounded-md px-3 text-sm",
  md: "h-10 rounded-lg px-4 text-sm",
  lg: "h-12 rounded-lg px-6 text-base",
};

const props = withDefaults(
  defineProps<{
    variant?: keyof typeof variants;
    size?: keyof typeof sizes;
  }>(),
  { variant: "primary", size: "md" },
);

const base =
  "relative isolate inline-flex items-center justify-center gap-2 overflow-hidden font-medium whitespace-nowrap transition-colors duration-150 ease-out focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:pointer-events-none disabled:opacity-50 motion-reduce:transition-none";
const layer = "pointer-events-none absolute inset-0 -z-10";
const wave = "absolute rounded-full bg-current opacity-0";

const WAVE = [
  { scale: "0", opacity: 0.25 },
  { scale: "1", opacity: 0 },
];
const WAVE_DURATION = 600;

const reducedMotion = () =>
  typeof window.matchMedia === "function" &&
  window.matchMedia("(prefers-reduced-motion: reduce)").matches;

const layerRef = useTemplateRef<HTMLSpanElement>("layer");

/** Adds one wave to the layer, from the pointer or from the center for keyboard clicks. */
function ripple(event: MouseEvent) {
  const target = layerRef.value;
  const button = target?.parentElement;
  if (!target || !button || reducedMotion()) return;
  const rect = button.getBoundingClientRect();
  const fromPointer = event.detail > 0;
  const x = fromPointer ? event.clientX - rect.left : rect.width / 2;
  const y = fromPointer ? event.clientY - rect.top : rect.height / 2;
  const diameter = Math.hypot(rect.width, rect.height) * 2;
  const element = document.createElement("span");
  element.className = wave;
  element.style.cssText = `left:${x - diameter / 2}px;top:${y - diameter / 2}px;width:${diameter}px;height:${diameter}px`;
  target.append(element);
  if (typeof element.animate !== "function") return element.remove();
  element.animate(WAVE, {
    duration: WAVE_DURATION,
    easing: "ease-out",
  }).onfinish = () => element.remove();
}
</script>

<template>
  <button
    type="button"
    :class="[base, variants[props.variant], sizes[props.size]]"
    @click="ripple"
  >
    <span ref="layer" :class="layer" aria-hidden="true" />
    <slot />
  </button>
</template>
```

```vue
<script setup lang="ts">
import RippleButton from "@/components/markas/RippleButton.vue";
</script>

<template>
  <RippleButton @click="addToCart">Add to cart</RippleButton>
  <RippleButton variant="secondary" type="submit">Subscribe</RippleButton>
</template>
```

### Svelte

Save at `src/lib/components/markas/RippleButton.svelte`. No extra dependencies.

```svelte
<script lang="ts">
  import type { Snippet } from "svelte";
  import type { HTMLButtonAttributes } from "svelte/elements";

  const base =
    "relative isolate inline-flex items-center justify-center gap-2 overflow-hidden font-medium whitespace-nowrap transition-colors duration-150 ease-out focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:pointer-events-none disabled:opacity-50 motion-reduce:transition-none";
  const variants = {
    primary: "bg-primary text-on-primary hover:bg-primary-strong",
    secondary: "border border-line bg-surface text-ink hover:bg-subtle",
    ghost: "text-ink hover:bg-subtle",
    danger: "bg-danger text-on-primary hover:bg-danger/90",
  };
  const sizes = {
    sm: "h-8 rounded-md px-3 text-sm",
    md: "h-10 rounded-lg px-4 text-sm",
    lg: "h-12 rounded-lg px-6 text-base",
  };
  const layer = "pointer-events-none absolute inset-0 -z-10";
  const wave = "absolute rounded-full bg-current opacity-0";

  const WAVE = [
    { scale: "0", opacity: 0.25 },
    { scale: "1", opacity: 0 },
  ];
  const WAVE_DURATION = 600;

  const reducedMotion = () =>
    typeof window.matchMedia === "function" &&
    window.matchMedia("(prefers-reduced-motion: reduce)").matches;

  type Props = HTMLButtonAttributes & {
    variant?: keyof typeof variants;
    size?: keyof typeof sizes;
    children?: Snippet;
  };

  let {
    variant = "primary",
    size = "md",
    type = "button",
    class: className,
    children,
    onclick,
    ...rest
  }: Props = $props();

  let layerElement = $state<HTMLSpanElement>();

  /** Adds one wave to the layer, from the pointer or from the center for keyboard clicks. */
  function ripple(
    event: MouseEvent & { currentTarget: EventTarget & HTMLButtonElement },
  ) {
    const target = layerElement;
    if (target && !reducedMotion()) {
      const rect = event.currentTarget.getBoundingClientRect();
      const fromPointer = event.detail > 0;
      const x = fromPointer ? event.clientX - rect.left : rect.width / 2;
      const y = fromPointer ? event.clientY - rect.top : rect.height / 2;
      const diameter = Math.hypot(rect.width, rect.height) * 2;
      const element = document.createElement("span");
      element.className = wave;
      element.style.cssText = `left:${x - diameter / 2}px;top:${y - diameter / 2}px;width:${diameter}px;height:${diameter}px`;
      target.append(element);
      if (typeof element.animate === "function")
        element.animate(WAVE, {
          duration: WAVE_DURATION,
          easing: "ease-out",
        }).onfinish = () => element.remove();
      else element.remove();
    }
    onclick?.(event);
  }
</script>

<button
  {type}
  onclick={ripple}
  class={[base, variants[variant], sizes[size], className]}
  {...rest}
>
  <span bind:this={layerElement} class={layer} aria-hidden="true"></span>
  {@render children?.()}
</button>
```

```svelte
<script lang="ts">
  import RippleButton from "$lib/components/markas/RippleButton.svelte";
</script>

<RippleButton onclick={addToCart}>Add to cart</RippleButton>
<RippleButton variant="secondary" type="submit">Subscribe</RippleButton>
```

### Astro

Save at `src/components/markas/RippleButton.astro`. No extra dependencies.

```astro
---
import type { HTMLAttributes } from "astro/types";

const base =
  "relative isolate inline-flex items-center justify-center gap-2 overflow-hidden font-medium whitespace-nowrap transition-colors duration-150 ease-out focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:pointer-events-none disabled:opacity-50 motion-reduce:transition-none";
const variants = {
  primary: "bg-primary text-on-primary hover:bg-primary-strong",
  secondary: "border border-line bg-surface text-ink hover:bg-subtle",
  ghost: "text-ink hover:bg-subtle",
  danger: "bg-danger text-on-primary hover:bg-danger/90",
};
const sizes = {
  sm: "h-8 rounded-md px-3 text-sm",
  md: "h-10 rounded-lg px-4 text-sm",
  lg: "h-12 rounded-lg px-6 text-base",
};
const layer = "pointer-events-none absolute inset-0 -z-10";

type Props = HTMLAttributes<"button"> & {
  variant?: keyof typeof variants;
  size?: keyof typeof sizes;
};

const {
  variant = "primary",
  size = "md",
  type = "button",
  class: className,
  ...rest
} = Astro.props;
---

<button
  type={type}
  data-markas-ripple-button
  class:list={[base, variants[variant], sizes[size], className]}
  {...rest}
>
  <span class={layer} aria-hidden="true"></span>
  <slot />
</button>

<script>
  const wave = "absolute rounded-full bg-current opacity-0";
  const WAVE = [
    { scale: "0", opacity: 0.25 },
    { scale: "1", opacity: 0 },
  ];
  const WAVE_DURATION = 600;

  // One listener per page serves every ripple button. Each click adds one wave, from the
  // pointer or from the center for keyboard clicks.
  document.addEventListener("click", (event) => {
    const button = (event.target as Element).closest<HTMLElement>(
      "[data-markas-ripple-button]",
    );
    const target = button?.firstElementChild;
    if (!button || !target) return;
    if (window.matchMedia?.("(prefers-reduced-motion: reduce)").matches) return;
    const rect = button.getBoundingClientRect();
    const fromPointer = event.detail > 0;
    const x = fromPointer ? event.clientX - rect.left : rect.width / 2;
    const y = fromPointer ? event.clientY - rect.top : rect.height / 2;
    const diameter = Math.hypot(rect.width, rect.height) * 2;
    const element = document.createElement("span");
    element.className = wave;
    element.style.cssText = `left:${x - diameter / 2}px;top:${y - diameter / 2}px;width:${diameter}px;height:${diameter}px`;
    target.append(element);
    if (typeof element.animate !== "function") return element.remove();
    element.animate(WAVE, {
      duration: WAVE_DURATION,
      easing: "ease-out",
    }).onfinish = () => element.remove();
  });
</script>
```

```astro
---
import RippleButton from "@/components/markas/RippleButton.astro";
---

<RippleButton>Add to cart</RippleButton>
<RippleButton variant="secondary" type="submit">Subscribe</RippleButton>
```

### Angular

Save at `src/app/markas/ripple-button.component.ts`. No extra dependencies.

```ts
import {
  ChangeDetectionStrategy,
  Component,
  computed,
  type ElementRef,
  input,
  viewChild,
} from "@angular/core";

const base =
  "relative isolate inline-flex items-center justify-center gap-2 overflow-hidden font-medium whitespace-nowrap transition-colors duration-150 ease-out focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:pointer-events-none disabled:opacity-50 motion-reduce:transition-none";
const variants = {
  primary: "bg-primary text-on-primary hover:bg-primary-strong",
  secondary: "border border-line bg-surface text-ink hover:bg-subtle",
  ghost: "text-ink hover:bg-subtle",
  danger: "bg-danger text-on-primary hover:bg-danger/90",
};
const sizes = {
  sm: "h-8 rounded-md px-3 text-sm",
  md: "h-10 rounded-lg px-4 text-sm",
  lg: "h-12 rounded-lg px-6 text-base",
};
const layer = "pointer-events-none absolute inset-0 -z-10";
const wave = "absolute rounded-full bg-current opacity-0";

const WAVE = [
  { scale: "0", opacity: 0.25 },
  { scale: "1", opacity: 0 },
];
const WAVE_DURATION = 600;

const reducedMotion = () =>
  typeof window.matchMedia === "function" &&
  window.matchMedia("(prefers-reduced-motion: reduce)").matches;

export type RippleButtonVariant = keyof typeof variants;
export type RippleButtonSize = keyof typeof sizes;

/**
 * Attribute selector on the native button: disabled, aria-*, name, value, and the user's
 * class stay on the button itself. Each click adds one wave.
 */
@Component({
  selector: "button[markas-ripple-button]",
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: {
    "[attr.type]": "type()",
    "[class]": "classes()",
    "(click)": "ripple($event)",
  },
  template: `<span #wave [class]="layer" aria-hidden="true"></span
    ><ng-content />`,
})
export class RippleButton {
  readonly variant = input<RippleButtonVariant>("primary");
  readonly size = input<RippleButtonSize>("md");
  readonly type = input<"button" | "submit" | "reset">("button");

  protected readonly layer = layer;
  protected readonly classes = computed(
    () => `${base} ${variants[this.variant()]} ${sizes[this.size()]}`,
  );
  private readonly layerRef =
    viewChild.required<ElementRef<HTMLSpanElement>>("wave");

  /** Adds one wave to the layer, from the pointer or from the center for keyboard clicks. */
  protected ripple(event: MouseEvent) {
    const target = this.layerRef().nativeElement;
    const button = target.parentElement;
    if (!button || reducedMotion()) return;
    const rect = button.getBoundingClientRect();
    const fromPointer = event.detail > 0;
    const x = fromPointer ? event.clientX - rect.left : rect.width / 2;
    const y = fromPointer ? event.clientY - rect.top : rect.height / 2;
    const diameter = Math.hypot(rect.width, rect.height) * 2;
    const element = document.createElement("span");
    element.className = wave;
    element.style.cssText = `left:${x - diameter / 2}px;top:${y - diameter / 2}px;width:${diameter}px;height:${diameter}px`;
    target.append(element);
    if (typeof element.animate !== "function") return element.remove();
    element.animate(WAVE, {
      duration: WAVE_DURATION,
      easing: "ease-out",
    }).onfinish = () => element.remove();
  }
}
```

```ts
import { Component } from "@angular/core";
import { RippleButton } from "./markas/ripple-button.component";

@Component({
  selector: "app-cart",
  imports: [RippleButton],
  template: `
    <button markas-ripple-button (click)="addToCart()">Add to cart</button>
    <button markas-ripple-button variant="secondary" type="submit">
      Subscribe
    </button>
  `,
})
export class Cart {
  addToCart() {}
}
```

Angular uses an attribute selector on the native button, so `disabled`, `aria-*`, and `class` stay on the button.

## Props

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `variant` | `'primary' \| 'secondary' \| 'ghost' \| 'danger'` | primary | Visual style, the same set as Button. |
| `size` | `'sm' \| 'md' \| 'lg'` | md | Height 32, 40, or 48px, the same as Button. |
| `type` | `'button' \| 'submit' \| 'reset'` | button | Native type attribute. |

## Accessibility

- A native button element, so Enter and Space work and focus shows a 2px primary outline.
- Ripples live in an aria-hidden layer and are removed when they finish.
- With prefers-reduced-motion no ripple is drawn, the click still works.

## Notes

- A mouse or touch click starts the ripple at the pointer. Enter and Space start it from the center.
- The ripple uses the text color at low opacity, so every variant gets a matching wave.
- Blade needs Alpine.js.
