# Magnetic Button

> A button that leans towards the pointer as it comes near, its words a little further, and settles back softly. Its click area moves with it. Calm on touch screens.

Buttons · button, magnetic, hover, cursor · HTML, CSS, vanilla JS · no dependencies · updated 2026-10-16
Demo: https://kodza.dev/components/magnetic-button/

## Files

The code below, served as files: byte for byte what the Kodza site copies (the CSS includes its theme guard).

- [`kodza-magnetic-button.css`](https://kodza.dev/registry/magnetic-button/kodza-magnetic-button.css) · 4.5 KB
- [`kodza-magnetic-button.js`](https://kodza.dev/registry/magnetic-button/kodza-magnetic-button.js) · 4.3 KB
- [`kodza-magnetic-button.html`](https://kodza.dev/registry/magnetic-button/kodza-magnetic-button.html) · 0.3 KB · the markup, to adapt and paste into your page

**Can you run shell commands? Download the CSS and the JS, don't retype them.** Retyping costs thousands of tokens and can drop or change lines of the CSS. Put the files where your stack expects them (Use it says where: change the `-o` paths):

```bash
curl -fsSL --create-dirs -o kodza/kodza-magnetic-button.css https://kodza.dev/registry/magnetic-button/kodza-magnetic-button.css
curl -fsSL --create-dirs -o kodza/kodza-magnetic-button.js https://kodza.dev/registry/magnetic-button/kodza-magnetic-button.js
```

Then load the files from your page as Use it shows, instead of pasting the content. The HTML is the part you adapt (text, links, modifiers): paste it from the Code section. Copy the CSS and the JS from the Code section only if you can't run commands, exactly as they are. (Windows PowerShell: `curl.exe`.)

## API

- Root: `.kodza-magnetic`
- Variables (set them on the root element itself: it declares its own defaults):
  - `--kz-magnetic-bg: #0a0a0a`
  - `--kz-magnetic-fg: #ffffff`
  - `--kz-magnetic-height: 52px`
  - `--kz-magnetic-pad-x: 30px`
- Modifiers: `.kodza-magnetic--round`
- Attributes:
  - `data-strength`
- Lifecycle: `kodza:init` / `kodza:destroy` on `document`, with `{ detail: { root } }` to target a container.

## Dark mode

The values Kodza uses on a dark background (`#0a0a0a`). For a page that follows the system theme, add them after the component's CSS:

```css
@media (prefers-color-scheme: dark) {
  .kodza-magnetic {
    --kz-magnetic-bg: #ffffff;
    --kz-magnetic-fg: #0a0a0a;
  }
}
```

A site with its own theme switch puts the same rules under its dark selector instead (`[data-theme="dark"] .kodza-magnetic { … }`); a single dark section, under that section's class.

## Use it

### Plain HTML page

- CSS: `kodza/kodza-magnetic-button.css` next to the page (the Files commands as they are), linked in `<head>`: `<link rel="stylesheet" href="kodza/kodza-magnetic-button.css">`. Without a shell, paste it in a `<style>` in `<head>` instead. It only touches `kodza-` classes.
- HTML: where the component goes. Paste it as many times as you need: instances never interfere.
- JS: `kodza/kodza-magnetic-button.js`, loaded with `<script src="kodza/kodza-magnetic-button.js" defer></script>` in `<head>`. Without a shell, paste it in a `<script>` before `</body>` (or in `<head>`: it waits for the page). One copy per page, whatever the number of instances.
- Restyle with the `--kz-…` variables, set on the component's root element itself (the root declares its own defaults, so a value on an ancestor is ignored), and with the modifiers / attributes listed under API.
- Font: it takes the page's own. The Kodza look is Geist: `<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Geist:wght@400;500;600;700&family=Geist+Mono:wght@400;500&display=swap">`.
- Content added later (AJAX navigation, a SPA route, a builder preview): start it with `document.dispatchEvent(new CustomEvent('kodza:init', { detail: { root: container } }))`; before removing it, the same call with `'kodza:destroy'` stops it and puts the original markup back.

### Claude artifact (claude.ai)

- Paste the CSS in a `<style>` and the JS in a `<script>` at the end, in the artifact itself: it loads stylesheets only from Google Fonts and scripts only from a few CDNs, so no `<link>` or `<script src>` to Kodza.
- Writing the artifact file with a shell? Insert the downloaded files (Files) with a command instead of retyping them: a line `KODZA-CSS` alone inside the `<style>`, `KODZA-JS` inside the `<script>`, then `sed -e '/^KODZA-CSS$/{r kodza/kodza-magnetic-button.css' -e 'd' -e '}' -e '/^KODZA-JS$/{r kodza/kodza-magnetic-button.js' -e 'd' -e '}' page.html > artifact.html`.
- Font: load Geist from Google Fonts (allowed): `<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Geist:wght@400;500;600;700&family=Geist+Mono:wght@400;500&display=swap">`.
- Dark mode: the viewer sets `data-theme="dark"` or `"light"` on `<html>`, or nothing when it follows the system. Write the Dark mode rules twice: inside `@media (prefers-color-scheme: dark)` with `:root:not([data-theme="light"])` in front of each selector, and with `:root[data-theme="dark"]` in front of each selector.

### WordPress

- HTML: a **Custom HTML** block (or a pattern / template part). WordPress keeps this markup as it is only for users allowed to post unfiltered HTML (Administrators; Super Admins on multisite): for anyone else it strips tags such as `<svg>`, `<input>` or `<dialog>`, so add it from the theme (a pattern or template part) instead.
- This one is inline (it flows like a word): pasted alone, many themes leave it at the edge of the page (block themes, and classic ones like Twenty Twenty-One or Blocksy), so put the Custom HTML block inside a **Group** block to line it up with the text.
- CSS and JS: the downloaded files go in the theme, under `wp-content/themes/<your-theme>/kodza/` (the child theme if there is one), enqueued from its functions.php (or a code-snippets plugin):
  ```php
  add_action('wp_enqueue_scripts', function () {
    $dir = get_stylesheet_directory() . '/kodza/';
    $uri = get_stylesheet_directory_uri() . '/kodza/';
    wp_enqueue_style('kodza-magnetic-button', $uri . 'kodza-magnetic-button.css', [], filemtime($dir . 'kodza-magnetic-button.css'));
    wp_enqueue_script('kodza-magnetic-button', $uri . 'kodza-magnetic-button.js', [], filemtime($dir . 'kodza-magnetic-button.js'), true);
  });
  ```
  Scoped to `kodza-` classes, the CSS never touches the theme. One copy of the JS, whatever the number of blocks.
- No access to the theme files? The CSS can also go, as it is, in **Appearance → Customize → Additional CSS** (classic theme) or **Styles → Additional CSS** in the Site Editor (block theme).
- Theme with AJAX page transitions: fire `kodza:init` on the new content after each swap (and `kodza:destroy` on the old one).
- Performance plugin (WP Rocket, LiteSpeed Cache, Perfmatters…) with **Delay JavaScript execution** turned on: add `kodza` to the scripts it must not delay. Otherwise the component waits for the visitor's first scroll, tap or mouse move, and that first click can be lost.
- Colours: by default, match the theme's palette. After the component's CSS, point these variables at the theme's colours, on the component root, Kodza's value as the fallback:
  `.kodza-magnetic { --kz-magnetic-bg: var(ACCENT, #0a0a0a); --kz-magnetic-fg: var(BACKGROUND, #ffffff); }`
  TEXT, BACKGROUND and ACCENT (the colour the theme fills its own buttons with) are the theme's own colour variables — block themes (theme.json, like Twenty Twenty-Five): `--wp--preset--color--contrast`, `--wp--preset--color--base`, `--wp--preset--color--contrast` (they fill their buttons with it; their accent-1… colours are decorative); Astra: `--ast-global-color-2`, `--ast-global-color-4`, `--ast-global-color-0`; Kadence: `--global-palette3`, `--global-palette9`, `--global-palette1`; GeneratePress: `--contrast`, `--base-3`, `--accent`; Blocksy: `--theme-palette-color-4`, `--theme-palette-color-8`, `--theme-palette-color-1`. Use only these names, and only if the site really has them (the theme's CSS, or Styles → Colors): the `--wp--preset--color--black`, `--white`, `--vivid-…` that WordPress adds everywhere are not the theme's palette. Another theme, or one without these variables (Hello Elementor, OceanWP): leave the variables alone, it keeps Kodza's monochrome; same when the developer asks for monochrome or the Kodza look. Leave the translucent greys (`rgba(10, 10, 10, …)`) as they are: they suit any light background. On a dark palette, set the other variables from Dark mode too.
- WordPress turns straight quotes and `--` into typographic ones in the text of a Custom HTML block (not inside `<code>` or `<pre>`).

#### With Elementor

- HTML: an **HTML** widget (Elementor shows it to administrators only). It keeps the code exactly as pasted, straight quotes included.
- CSS and JS: as above. Elementor's Site Settings → Theme Style styles every button, field, link and image of the page, components included; the theme guard at the end of the CSS keeps the component's buttons, fields and link colours as they are.
- The Elementor editor redraws each widget after the page has loaded: without the script below, the component stays still in the editor preview (the published page works). Add it once per site, in the footer like the component's script (`kodza/elementor-editor.js`, or a code-snippets plugin):

```js
// Kodza in the Elementor editor: the editor redraws each HTML widget after the page has loaded.
// Start Kodza in what it draws, stop it in what it replaces or removes. Once per site.
window.addEventListener('elementor/frontend/init', () => {
  if (!elementorFrontend.isEditMode()) return;
  class KodzaWidget extends elementorModules.frontend.handlers.Base {
    onInit() {
      super.onInit();
      this.kodza = [...this.$element[0].children];
      document.dispatchEvent(new CustomEvent('kodza:init', { detail: { root: this.$element[0] } }));
    }
    onDestroy() {
      super.onDestroy();
      this.kodza.forEach((root) => document.dispatchEvent(new CustomEvent('kodza:destroy', { detail: { root } })));
    }
  }
  elementorFrontend.elementsHandler.attachHandler('html', KodzaWidget);
});
```

- No child theme: everything can go in the HTML widget instead, `<style>` with the CSS, the HTML, then `<script>` with the JS. It works on the page and in the editor without the script above.

### Shopify

- Files: `assets/kodza-magnetic-button.css` and `assets/kodza-magnetic-button.js` (the Files commands with `-o assets/…`).
- In the section: `{{ 'kodza-magnetic-button.css' | asset_url | stylesheet_tag }}` and `<script src="{{ 'kodza-magnetic-button.js' | asset_url }}" defer></script>`, then the HTML.
- The theme editor re-renders sections: restart them with
  `document.addEventListener('shopify:section:load', (e) => document.dispatchEvent(new CustomEvent('kodza:init', { detail: { root: e.target } })));`
  and the same with `shopify:section:unload` → `kodza:destroy`.

### React / Next.js

- Files, side by side (e.g. in `components/kodza/`): `MagneticButton.tsx` (below), the CSS block under Code saved as `magnetic-button.css` and the JS block as `magnetic-button.js`, both as they are. The HTML block is already inside the component: skip it.
- Use it: `import { MagneticButton } from '@/components/kodza/MagneticButton';` then `<MagneticButton>Get in touch</MagneticButton>`. Props: `variant` ("round", or several in an array), `vars` (the `--kz-…` variables listed under API, e.g. `vars={{ '--kz-magnetic-bg': … }}`), `children` (the text, plain), `className`, `style` and the other props of its `<a>` (`onClick`, `aria-…`).
- Next.js App Router: it is a Client Component already (`'use client'`). Pages Router: Next.js takes global CSS only in `pages/_app`, so move the `import './magnetic-button.css'` line there.
- Safe under StrictMode, client-side navigation and prop changes: when a prop changes, the `key` gives React a fresh element, `kodza:destroy` stops the script on the old one and `kodza:init` starts it on the new one.

```tsx
'use client';
// Kodza — Magnetic Button, for React. From https://kodza.dev/components/magnetic-button/
// Kodza License: free to use, client work included. Not to resell or redistribute, ported or not: https://kodza.dev/docs/#print-license
// Next to this file: magnetic-button.css and magnetic-button.js, the component's CSS and JS from Kodza, as they are.
// Yours to edit: the markup is plain JSX below.
// The script changes this markup once React has rendered it (it adds layers, splits text, moves
// nodes), so React must not patch it afterwards. When a prop changes, the key gives React a fresh
// element: kodza:destroy stops the script on the old one, kodza:init starts it on the new one.
import { useRef, useEffect, type ComponentPropsWithoutRef, type ComponentRef, type CSSProperties } from 'react';
import './magnetic-button.css';

type Variant = "round";

export type MagneticButtonProps = Omit<ComponentPropsWithoutRef<'a'>, "children" | "variant" | "vars"> & {
  /** Modifier class(es): .kodza-magnetic--round */
  variant?: Variant | Variant[];
  /** Settings, as CSS variables on the root */
  vars?: {
    /** default: #0a0a0a */
    "--kz-magnetic-bg"?: string | number;
    /** default: #ffffff */
    "--kz-magnetic-fg"?: string | number;
    /** default: 52px */
    "--kz-magnetic-height"?: string | number;
    /** default: 30px */
    "--kz-magnetic-pad-x"?: string | number;
  };
  /** The text, plain: the script reads it and rebuilds the markup around it */
  children?: string;
  className?: string;
};

export function MagneticButton({ variant, vars, children = "Get in touch", className, style, ...rest }: MagneticButtonProps) {
  const ref = useRef<ComponentRef<'a'>>(null);
  const classes = ["kodza-magnetic", ...([] as string[]).concat(variant ?? []).map((v) => `kodza-magnetic--${v}`), className].filter(Boolean).join(' ');
  // Everything the markup is made of: when it changes, React gets a fresh element (see the top)
  const key = JSON.stringify([classes, vars, children, style, rest]);

  // Starts the script on this element once React has rendered it, stops it when it goes
  useEffect(() => {
    const root = ref.current;
    let live = true;
    // @ts-ignore: a plain script, no types to find
    import('./magnetic-button.js').then(() => {
      if (live) document.dispatchEvent(new CustomEvent('kodza:init', { detail: { root } }));
    });
    return () => {
      live = false;
      document.dispatchEvent(new CustomEvent('kodza:destroy', { detail: { root } }));
    };
  }, [key]);

  return (
    <a href="#" key={key} {...rest} className={classes} style={{ ...vars, ...style } as CSSProperties} ref={ref}>
      <span className="kodza-magnetic__label">{children}</span>
    </a>
  );
}
```

## Code

```html
<a class="kodza-magnetic" href="#"><span class="kodza-magnetic__label">Get in touch</span></a>

<a class="kodza-magnetic kodza-magnetic--round" href="#" aria-label="Next project"><span class="kodza-magnetic__label"><svg viewBox="0 0 16 16" aria-hidden="true"><path d="M3 8h10M9 4l4 4-4 4" /></svg></span></a>
```

```css
/* Kodza License: free to use, client work included. Not to resell or redistribute, ported or not: https://kodza.dev/docs/#print-license */
/* Kodza — Magnetic Button
   A button that leans towards the pointer as it comes near, its words a little further, and
   settles back softly when the pointer goes. The click area moves with it, so it is never
   harder to hit. --round for an icon. Nothing happens on touch screens or with reduced motion.
   Everything is tuned with the --kz-magnetic-* variables (and data-strength, 0 to 1, 0.3 by default). */
.kodza-magnetic {
  --kz-magnetic-bg: #0a0a0a;
  --kz-magnetic-fg: #ffffff;
  --kz-magnetic-height: 52px;
  --kz-magnetic-pad-x: 30px;

  display: inline-grid;
  place-items: center;
  height: var(--kz-magnetic-height);
  padding: 0 var(--kz-magnetic-pad-x);
  border-radius: 999px;
  background: var(--kz-magnetic-bg);
  color: var(--kz-magnetic-fg);
  font-weight: 500;
  letter-spacing: -0.01em;
  text-decoration: none;
  white-space: nowrap;
  transform: translate(var(--kz-magnetic-x, 0px), var(--kz-magnetic-y, 0px));
  -webkit-tap-highlight-color: transparent;
}

.kodza-magnetic--round {
  width: calc(var(--kz-magnetic-height) * 1.35);
  height: calc(var(--kz-magnetic-height) * 1.35);
  padding: 0;
}

.kodza-magnetic__label {
  display: inline-flex;
  transform: translate(var(--kz-magnetic-lx, 0px), var(--kz-magnetic-ly, 0px));
}

.kodza-magnetic svg {
  width: 20px;
  height: 20px;
  fill: none;
  stroke: currentColor;
  stroke-width: 1.6;
  stroke-linecap: round;
  stroke-linejoin: round;
}

.kodza-magnetic:focus-visible {
  outline: 2px solid var(--kz-magnetic-bg);
  outline-offset: 4px;
}

/* Theming example — on a dark background:
.dark-section .kodza-magnetic {
  --kz-magnetic-bg: #ffffff;
  --kz-magnetic-fg: #0a0a0a;
}
*/

/* kodza-guard 879d705fa2f8 — generated by Kodza, do not edit.
   Theme guard: keeps a site's own CSS (WordPress themes, Bootstrap, CSS resets…) off this
   component. :not(#_) is always true and weighs as much as an id, so these lines win over
   theme rules made of classes and tags. Customise the component through its --kz-* variables. */

/* What the browser gives, where the component sets it only in some states: at the lowest weight, so its own rules below put it back */

:where(.kodza-magnetic):not(#_) {
  outline: revert;
  outline-offset: revert;
}

/* What the browser gives, on everything the component leaves to it */

.kodza-magnetic:not(#_) {
  border: revert;
  transition: revert;
  list-style: revert;
  box-sizing: revert;
  position: revert;
  box-shadow: revert;
  appearance: revert;
  max-height: revert;
  font-family: revert;
  font-size: revert;
  font-style: revert;
  line-height: revert;
  text-transform: revert;
  text-underline-offset: revert;
  text-align: revert;
  text-indent: revert;
  text-shadow: revert;
  vertical-align: revert;
}

.kodza-magnetic__label:not(#_) {
  box-sizing: revert;
}

.kodza-magnetic__label svg:where(:not([class*="kodza-"])):not(#_) {
  border: revert;
  margin: revert;
  padding: revert;
  border-radius: revert;
  outline: revert;
  text-decoration: revert;
  transition: revert;
  list-style: revert;
  box-sizing: revert;
  float: revert;
  position: revert;
  background-color: revert;
  background-image: revert;
  box-shadow: revert;
  outline-offset: revert;
  appearance: revert;
  max-width: revert;
  max-height: revert;
  color: revert;
  font-family: revert;
  font-size: revert;
  font-weight: revert;
  font-style: revert;
  line-height: revert;
  letter-spacing: revert;
  text-transform: revert;
  text-underline-offset: revert;
  text-align: revert;
  text-indent: revert;
  text-shadow: revert;
  vertical-align: revert;
}

.kodza-magnetic__label svg:where(:not([class*="kodza-"])):not(#_):where(:not([hidden])) {
  display: revert;
}

.kodza-magnetic__label svg:where(:not([class*="kodza-"])):not(#_):where([hidden]) {
  display: none;
}

/* The component's own rules, one step stronger: real buttons and fields, what it sets on tags themes style (links, lists, headings, images…), and the root width (a theme may narrow it, never widen it) */

.kodza-magnetic:not(#_) {
  display: inline-grid;
  padding: 0 var(--kz-magnetic-pad-x);
  border-radius: 999px;
  background: var(--kz-magnetic-bg);
  color: var(--kz-magnetic-fg);
  font-weight: 500;
  letter-spacing: -0.01em;
  text-decoration: none;
}

.kodza-magnetic--round:not(#_) {
  padding: 0;
}

.kodza-magnetic:focus-visible:not(#_) {
  outline: 2px solid var(--kz-magnetic-bg);
  outline-offset: 4px;
}
```

```js
// Kodza License: free to use, client work included. Not to resell or redistribute, ported or not: https://kodza.dev/docs/#print-license
// Kodza — Magnetic Button
// Each button watches the pointer on the page: within reach (its size, plus a margin) it is
// drawn towards the pointer, its label a little more, and every frame eases the motion so it
// settles back softly. Measured in the button's own pixels, so a scaled parent is fine.
(() => {
  const SELECTOR = '.kodza-magnetic';
  const fine = window.matchMedia('(hover: hover) and (pointer: fine)').matches;
  const reduceMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;

  // One instance. Everything it starts is tied to `signal`, so kodza:destroy stops it all
  function mount(el, signal) {
    if (!fine || reduceMotion) return;
    const strength = Math.min(1, Math.max(0, parseFloat(el.dataset.strength) || 0.3));
    let x = 0;
    let y = 0;
    let tx = 0;
    let ty = 0;
    let frame = 0;

    const tick = () => {
      frame = 0;
      let moving = false;
      x += (tx - x) * 0.16;
      y += (ty - y) * 0.16;
      if (Math.abs(tx - x) < 0.05 && Math.abs(ty - y) < 0.05) {
        x = tx;
        y = ty;
      } else moving = true;
      el.style.setProperty('--kz-magnetic-x', `${x.toFixed(2)}px`);
      el.style.setProperty('--kz-magnetic-y', `${y.toFixed(2)}px`);
      el.style.setProperty('--kz-magnetic-lx', `${(x * 0.3).toFixed(2)}px`);
      el.style.setProperty('--kz-magnetic-ly', `${(y * 0.3).toFixed(2)}px`);
      if (moving) frame = requestAnimationFrame(tick);
    };

    const aim = (event) => {
      const box = el.getBoundingClientRect();
      const k = box.width / el.offsetWidth || 1;
      // The box at rest: where it would be without its current pull
      const cx = box.left + box.width / 2 - x * k;
      const cy = box.top + box.height / 2 - y * k;
      const dx = event.clientX - cx;
      const dy = event.clientY - cy;
      const reach = Math.max(box.width, box.height) / 2 + 60 * k;
      const near = Math.hypot(dx, dy) < reach;
      // Never further than half its height: it leans, it does not run
      const max = el.offsetHeight * 0.5;
      tx = near ? (dx / k) * strength : 0;
      ty = near ? (dy / k) * strength : 0;
      const pull = Math.hypot(tx, ty);
      if (pull > max) {
        tx *= max / pull;
        ty *= max / pull;
      }
      if (!frame) frame = requestAnimationFrame(tick);
    };

    window.addEventListener('pointermove', aim, { passive: true, signal });
    document.addEventListener('pointerleave', () => {
      tx = ty = 0;
      if (!frame) frame = requestAnimationFrame(tick);
    }, { signal });
    signal.addEventListener('abort', () => cancelAnimationFrame(frame));
  }

  // Kodza lifecycle, the same in every component: `kodza:init` starts the instances inside
  // event.detail.root (the whole page by default), `kodza:destroy` stops them and puts their
  // markup back. For themes and apps that swap content without a page load.
  const instances = new WeakMap();
  const find = (scope = document) => [scope, ...scope.querySelectorAll(SELECTOR)].filter((el) => el.matches?.(SELECTOR));
  const init = (scope) => find(scope).forEach((root) => {
    if (root.classList.contains('is-ready')) return; // already running, maybe from another copy of this script
    const controller = new AbortController();
    instances.set(root, { controller, html: root.innerHTML, attrs: [...root.attributes].map((a) => [a.name, a.value]) });
    mount(root, controller.signal);
    root.classList.add('is-ready');
  });
  const destroy = (scope) => find(scope).forEach((root) => {
    const instance = instances.get(root);
    if (!instance) return;
    instances.delete(root);
    instance.controller.abort();
    [...root.attributes].forEach((a) => root.removeAttribute(a.name));
    instance.attrs.forEach(([name, value]) => root.setAttribute(name, value));
    root.innerHTML = instance.html;
  });
  document.addEventListener('kodza:init', (event) => init(event.detail?.root));
  document.addEventListener('kodza:destroy', (event) => destroy(event.detail?.root));
  init();
  // Loaded in <head>, the script runs before the markup exists: once more when it is parsed
  if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', () => init(), { once: true });
})();
```

Free to use, from Kodza (https://kodza.dev).
