Components Buttons

Magnetic Button

Draw a call to action toward the pointer as it approaches, then let it settle back into place.

Live previewGo + JavaScript

Move your pointer close to pull the button toward it.

Usage

Set Label and Href for a link, or omit Href for a native button. For a form action, set Type to submit or reset and optionally supply Name and Value. Radius sets how many pixels beyond the button’s resting edge activate the pull (96 by default). Strength sets the fraction of pointer displacement to follow, from 0 to 1 (default 0.45). MaxOffset caps total travel in pixels (default 24). Set any of these to 0 to keep the button still. Set ShowArrow to false for a text-only button, or Disabled to disable the action. Touch and keyboard users can activate the control in place. Reduced-motion preferences keep it stationary.

Register magnetic-button with Head and pass its properties to Render. Go setup guide

The dashed line in the preview marks the attraction radius. The inner outline marks the resting position. Set --magnet-bg, --magnet-ink, --magnet-padding, or --magnet-corner on the component to customize its appearance.

Go usage
Go usage
err := mono.UI.Render(w, "magnetic-button", mono.Props{
	"Href":  "../components/exhibit-gallery.html",
	"Label": "Explore the gallery",
})
Rendered HTML
Rendered HTML
<span class="mu-magnet" data-mono="magnetic-button"
  
  
  >
  
  <a id="demo-magnetic-button" class="mu-magnet-action" data-magnet-action href="../components/exhibit-gallery.html">
  <span class="mu-magnet-label">Explore the gallery</span>
  <span class="mu-magnet-arrow" aria-hidden="true"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" focusable="false"><path d="M6 18 18 6M6 6h12v12"/></svg></span>
</a>
  
</span>
A submit button with a softer pull
A submit button with a softer pull
// Render inside a form with a POST action.
err := mono.UI.Render(w, "magnetic-button", mono.Props{
	"Label":     "Request a print",
	"Type":      "submit",
	"Name":      "intent",
	"Value":     "request-print",
	"Radius":    72,
	"Strength":  0.25,
	"MaxOffset": 12,
	"ShowArrow": false,
})
Go template
Go template
{{define "magnet-content"}}
  <span class="mu-magnet-label">{{or .Label "Explore"}}</span>
  {{if ne (print .ShowArrow) "false"}}<span class="mu-magnet-arrow" aria-hidden="true"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" focusable="false"><path d="M6 18 18 6M6 6h12v12"/></svg></span>{{end}}
{{end}}
<span class="mu-magnet" data-mono="magnetic-button"
  {{if ne .Radius nil}}data-radius="{{.Radius}}"{{end}}
  {{if ne .Strength nil}}data-strength="{{.Strength}}"{{end}}
  {{if ne .MaxOffset nil}}data-max-offset="{{.MaxOffset}}"{{end}}>
  {{if and .Href (not .Disabled)}}
  <a id="{{.ID}}" class="mu-magnet-action" data-magnet-action href="{{.Href}}">{{template "magnet-content" .}}</a>
  {{else}}
  <button id="{{.ID}}" class="mu-magnet-action" data-magnet-action
    type="{{if eq .Type "submit" "reset"}}{{.Type}}{{else}}button{{end}}"
    {{if .Name}}name="{{.Name}}"{{end}} {{if ne .Value nil}}value="{{.Value}}"{{end}} {{if .Disabled}}disabled{{end}}>{{template "magnet-content" .}}</button>
  {{end}}
</span>
Component CSS
Component CSS
.mu-magnet[data-mono] {
  display: inline-grid;
  grid-template-columns: minmax(0, 1fr);
  width: fit-content;
  max-width: 100%;
  min-width: 0;
  vertical-align: middle;
  font: 600 1rem/1.2 Inter, "Helvetica Neue", Arial, sans-serif;
}
.mu-magnet-action {
  display: inline-flex;
  justify-content: center;
  align-items: center;
  gap: .9em;
  min-width: 0;
  min-height: 3em;
  padding: var(--magnet-padding, .45em 1.2em);
  border: 1px solid transparent;
  border-radius: var(--magnet-corner, 999px);
  appearance: none;
  background: var(--magnet-bg, #141414);
  color: var(--magnet-ink, #fff);
  font: inherit;
  letter-spacing: -.025em;
  text-align: start;
  text-decoration: none;
  cursor: pointer;
}
.mu-magnet-action:has(.mu-magnet-arrow) { padding-inline-end: var(--magnet-arrow-inset, .45em); }
.mu-magnet-label { min-width: 0; overflow-wrap: anywhere; }
.mu-magnet-arrow {
  display: grid;
  flex: none;
  place-items: center;
  width: 2em;
  height: 2em;
  border: 1px solid #ffffff5c;
  border-color: color-mix(in srgb, currentColor 38%, transparent);
  border-radius: 50%;
}
.mu-magnet-arrow svg { width: 1em; height: 1em; }
.mu-magnet .mu-magnet-action:focus-visible {
  outline: 2px solid #151515;
  outline-offset: 3px;
  box-shadow: 0 0 0 3px #fff;
}
.mu-magnet-action:disabled { cursor: not-allowed; opacity: .55; }
@media (prefers-reduced-motion: no-preference) {
  .mu-magnet-action:not(:disabled, :focus-visible) {
    transform: translate(var(--magnet-x, 0px), var(--magnet-y, 0px));
    transition: transform 150ms cubic-bezier(.2, .8, .22, 1);
  }
}
@media (forced-colors: active) {
  .mu-magnet-action, .mu-magnet-arrow { border: 1px solid currentColor; }
  .mu-magnet .mu-magnet-action:focus-visible { outline-color: Highlight; box-shadow: none; }
}
JavaScript module
JavaScript module
const active = new Set();
const reducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)');
let listeners;
let pointer;
let frame = 0;

function configure(value, fallback, max = Infinity) {
  const number = value == null || value.trim() === '' ? NaN : Number(value);
  return Number.isFinite(number) ? Math.min(max, Math.max(0, number)) : fallback;
}

function place(button, x = 0, y = 0) {
  if (x === 0 && y === 0) {
    if (button.moved) {
      button.action.style.removeProperty('--magnet-x');
      button.action.style.removeProperty('--magnet-y');
      button.moved = false;
    }
    return;
  }
  button.action.style.setProperty('--magnet-x', x.toFixed(2) + 'px');
  button.action.style.setProperty('--magnet-y', y.toFixed(2) + 'px');
  button.moved = true;
}

function draw() {
  frame = 0;
  const positions = [];
  for (const button of active) {
    const { root, action, radius, strength, maxOffset } = button;
    if (action.matches(':disabled, :focus-visible, [aria-disabled="true"]')) {
      positions.push([button, 0, 0]);
      continue;
    }
    // The wrapper stays at rest even while the native action moves.
    const rect = root.getBoundingClientRect();
    const dx = pointer.x - (rect.left + rect.width / 2);
    const dy = pointer.y - (rect.top + rect.height / 2);
    const edge = Math.hypot(Math.max(0, Math.abs(dx) - rect.width / 2),
      Math.max(0, Math.abs(dy) - rect.height / 2));
    const proximity = Math.max(0, 1 - edge / radius);
    const falloff = proximity * proximity * (3 - 2 * proximity);
    const pull = Math.min(strength, maxOffset / (Math.hypot(dx, dy) || 1)) * falloff;
    positions.push([button, dx * pull, dy * pull]);
  }
  // Finish geometry reads for all instances before changing any transforms.
  for (const [button, x, y] of positions) place(button, x, y);
}

function schedule() {
  if (pointer && !frame) frame = requestAnimationFrame(draw);
}

function release() {
  if (!pointer && !frame) return;
  pointer = null;
  cancelAnimationFrame(frame);
  frame = 0;
  for (const button of active) place(button);
}

function track() {
  if (!active.size) {
    listeners?.abort();
    listeners = null;
    release();
    return;
  }
  if (listeners) return;
  listeners = new AbortController();
  const options = { passive: true, signal: listeners.signal };
  window.addEventListener('pointermove', event => {
    if (event.pointerType === 'touch') { release(); return; }
    pointer = { x: event.clientX, y: event.clientY };
    schedule();
  }, options);
  window.addEventListener('pointerdown', event => {
    if (event.pointerType === 'touch') release();
  }, options);
  window.addEventListener('pointerout', event => {
    if (!event.relatedTarget) release();
  }, options);
  for (const type of ['keydown', 'pointercancel', 'blur', 'resize']) {
    window.addEventListener(type, release, options);
  }
  window.addEventListener('scroll', release, { ...options, capture: true });
  document.addEventListener('visibilitychange', () => {
    if (document.hidden) release();
  }, options);
}

export function mount(root) {
  const action = root.querySelector('[data-magnet-action]');
  if (!action || !('IntersectionObserver' in window)) return;
  const button = { root, action, moved: false };
  let visible = false;
  function sync() {
    button.radius = configure(root.dataset.radius, 96);
    button.strength = configure(root.dataset.strength, .45, 1);
    button.maxOffset = configure(root.dataset.maxOffset, 24);
    if (visible && root.isConnected && !reducedMotion.matches && button.radius && button.strength
        && button.maxOffset && !action.matches(':disabled, [aria-disabled="true"]')) {
      active.add(button);
      schedule();
    } else {
      active.delete(button);
      place(button);
    }
    track();
  }
  const changes = new MutationObserver(sync);
  const viewport = new IntersectionObserver(entries => {
    visible = entries[entries.length - 1].isIntersecting;
    if (visible) {
      reducedMotion.addEventListener('change', sync);
      changes.observe(root, { subtree: true, attributes: true,
        attributeFilter: ['disabled', 'aria-disabled', 'data-radius', 'data-strength', 'data-max-offset'] });
    } else {
      reducedMotion.removeEventListener('change', sync);
      changes.disconnect();
    }
    sync();
  });
  viewport.observe(root);
}
Use the HTML in a static site

Copy the rendered HTML above. Download these assets into the same folder as your page, then add the tags below to its head.

Shared CSS Component CSS Ready-to-use module

HTML head
<link rel="stylesheet" href="./base.css">
<link rel="stylesheet" href="./magnetic-button.css">
<script type="module" src="./magnetic-button.js"></script>

Copy into your project

Run this command from the Mono checkout. Set -out to the component directory in your application.

Terminal
go run ./cmd/mono-ui add -out ./components magnetic-button
Example properties (JSON)
example.json
{
  "Href": "../components/exhibit-gallery.html",
  "Label": "Explore the gallery"
}