Favorites

Animation Effects When Copying to Clipboard

☕
Enjoying this site?

Help keep it running with a small coffee donation. Every bit of support is appreciated!

Buy us a coffee
Animation Effects

Copy-to-clipboard is one of those interactions that deserves a little ceremony. The user did something, so let them see that it worked. In a previous post, we added animation effects using the Clipboard.js library. This time, we're doing without the library entirely, and using the browser's built-in navigator.clipboard.writeText(), CSS animations and a little plain JavaScript.

Below are eight effects, from a subtle ripple to a shower of confetti. Each one has a live demo you can click, followed by the CSS and JavaScript that makes it work.

The core pattern

Copying text with the Clipboard API

The Clipboard API is built into every modern browser. Its writeText() method copies a string, and returns a promise: an object that tells you later whether the copy worked. With await, you can wait for that answer before doing anything else:

button.addEventListener('click', async () => {
  await navigator.clipboard.writeText('Text to copy');
  console.log('Copied!');
});

Two rules to know: the Clipboard API only works on secure pages (served over HTTPS, or from localhost while you're developing). And browsers only let a page copy in response to something the user does, such as clicking a button. Both rules stop websites from quietly changing what's on your clipboard.

A helper that reports success

Copying can still fail, for example if the browser blocks it. If it does, await throws an error. So that every effect can check the result, we'll wrap the copy in a small helper function that returns true when the copy works and false when it doesn't:

// Copies text and reports whether it worked
async function copyText(text) {
  try {
    await navigator.clipboard.writeText(text);
    return true;
  } catch (error) {
    console.error('Copy failed:', error);
    return false;
  }
}

Every effect in this post then follows the same pattern: copy first, and only animate if the copy worked. An animation that celebrates a copy that never happened would be worse than no animation at all.

The starting HTML and CSS

All the effects start from the same markup: a box showing the text, and a button. The text to copy is stored in a data-copy attribute, so the JavaScript can read it with button.dataset.copy. This keeps the JavaScript out of the HTML, so there's no need for onclick attributes.

<div class="snippet-row">
  <code class="snippet">npm install my-package</code>
  <button type="button" class="copy-btn" data-copy="npm install my-package">
    <svg aria-hidden="true" viewBox="0 0 24 24" width="15" height="15"
         fill="none" stroke="currentColor" stroke-width="2">
      <rect x="9" y="9" width="13" height="13" rx="2"/>
      <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>
    </svg>
    Copy
  </button>
</div>
.snippet-row {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 12px;
}

.snippet {
  flex: 1;
  min-width: 0;
  padding: 12px 16px;
  border: 1.5px solid #e2e8f0;
  border-radius: 8px;
  background: #fff;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.copy-btn {
  position: relative;       /* effects are positioned inside the button */
  overflow: hidden;         /* and clipped to its edges */
  display: inline-flex;
  align-items: center;
  gap: 7px;
  padding: 10px 18px;
  border: none;
  border-radius: 8px;
  background: #2563eb;
  color: #fff;
  font: 600 14px/1.2 system-ui, sans-serif;
  cursor: pointer;
}

.copy-btn:hover {
  background: #1d4ed8;
}

Each effect below adds its own class to the button, such as ripple-btn, plus a few lines of CSS and JavaScript. To save space, the later examples show <!-- copy icon --> in place of the full SVG.

Effects on the button

Ripple burst

The classic Material Design ripple: a see-through white circle grows outward from the centre of the button and fades away. It's instantly familiar, and works on any colour of button. The button's overflow: hidden clips the circle as it grows.

Results
npm install my-package

Give the button the ripple-btn class, then add:

.ripple {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 100%;
  aspect-ratio: 1;          /* a circle as wide as the button */
  translate: -50% -50%;     /* centred on the button */
  border-radius: 50%;
  background: rgb(255 255 255 / 0.55);
  pointer-events: none;
  animation: ripple-out 0.6s ease-out forwards;
}

@keyframes ripple-out {
  from { scale: 0;   opacity: 0.5; }
  to   { scale: 2.5; opacity: 0; }
}
document.querySelectorAll('.ripple-btn').forEach((button) => {
  button.addEventListener('click', async () => {
    if (!(await copyText(button.dataset.copy))) return;

    const ripple = document.createElement('span');
    ripple.className = 'ripple';
    button.append(ripple);
    ripple.addEventListener('animationend', () => ripple.remove());
  });
});

The JavaScript adds a <span> to the button each time it's clicked, and removes it again when the animationend event fires, so the old ripples don't build up.

Checkmark swap

The clearest confirmation of all: the button turns green, and its label changes to a tick and "Copied!". The button holds both labels, and a copied class decides which one shows.

Results
git clone https://github.com/user/repo.git
<button type="button" class="copy-btn check-btn" data-copy="git clone https://github.com/user/repo.git">
  <span class="label-copy"><!-- copy icon --> Copy</span>
  <span class="label-done"><!-- tick icon --> Copied!</span>
</button>
.check-btn :is(.label-copy, .label-done) {
  display: inline-flex;
  align-items: center;
  gap: 6px;
}

.check-btn .label-done { display: none; }

.check-btn.copied { background: #15803d; }
.check-btn.copied .label-copy { display: none; }
.check-btn.copied .label-done { display: inline-flex; }
document.querySelectorAll('.check-btn').forEach((button) => {
  button.addEventListener('click', async () => {
    if (button.classList.contains('copied')) return;  // ignore repeat clicks
    if (!(await copyText(button.dataset.copy))) return;

    button.classList.add('copied');
    setTimeout(() => button.classList.remove('copied'), 2000);
  });
});

The first line of the click handler ignores any extra clicks while the button is showing "Copied!", so the timer can't be started twice.

Slide-up label

"Copy" slides up and out of the button while "Done" rises in from below. A springy cubic-bezier() timing function makes the new label overshoot slightly and settle, giving a satisfying little bounce. It uses the same two-label HTML as the checkmark swap, with a slide-btn class instead.

Results
docker pull node:22-alpine
.slide-btn :is(.label-copy, .label-done) {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  transition: transform 0.3s cubic-bezier(0.34, 1.56, 0.64, 1), opacity 0.25s;
}

.slide-btn .label-done {
  position: absolute;
  inset: 0;
  transform: translateY(100%);   /* waiting below the button */
  opacity: 0;
}

.slide-btn.slid { background: #1e40af; }
.slide-btn.slid .label-copy { transform: translateY(-110%); opacity: 0; }
.slide-btn.slid .label-done { transform: translateY(0); opacity: 1; }
document.querySelectorAll('.slide-btn').forEach((button) => {
  button.addEventListener('click', async () => {
    if (button.classList.contains('slid')) return;
    if (!(await copyText(button.dataset.copy))) return;

    button.classList.add('slid');
    setTimeout(() => button.classList.remove('slid'), 2200);
  });
});

Effects that pop out

Floating toast

A small tooltip-style message rises from the button, lingers for a moment, then fades away. It sits above the right-hand end of the button, so it stays inside the page when the button is at the end of a row. It's ideal for hidden or shortened text, such as API keys, where the user can't see what was copied: the message reassures them that something was. The button sits inside a wrapper, which gives the message something to position itself against.

Results
sk-live-••••••••••••••••
<span class="toast-anchor">
  <button type="button" class="copy-btn toast-btn" data-copy="sk-live-EXAMPLE-KEY">
    <!-- copy icon --> Copy
  </button>
</span>
.toast-anchor {
  position: relative;
  display: inline-flex;
}

.toast {
  position: absolute;
  bottom: calc(100% + 8px);
  right: 0;                 /* lined up with the button's right edge */
  padding: 5px 12px;
  border-radius: 6px;
  background: #0f172a;
  color: #fff;
  font-size: 12px;
  white-space: nowrap;
  pointer-events: none;
  animation: toast-rise 1.6s ease forwards;
}

.toast::after {       /* the little arrow */
  content: "";
  position: absolute;
  top: 100%;
  right: 20px;
  border: 5px solid transparent;
  border-top-color: #0f172a;
}

@keyframes toast-rise {
  0%   { opacity: 0; transform: translateY(0) scale(0.85); }
  15%  { opacity: 1; transform: translateY(-12px) scale(1); }
  75%  { opacity: 1; transform: translateY(-14px) scale(1); }
  100% { opacity: 0; transform: translateY(-28px) scale(0.9); }
}
document.querySelectorAll('.toast-btn').forEach((button) => {
  button.addEventListener('click', async () => {
    if (!(await copyText(button.dataset.copy))) return;

    const anchor = button.parentElement;
    anchor.querySelector('.toast')?.remove();   // remove any toast still showing

    const toast = document.createElement('span');
    toast.className = 'toast';
    toast.textContent = '✓ Copied to clipboard';
    anchor.append(toast);
    toast.addEventListener('animationend', () => toast.remove());
  });
});

Particle burst

Ten dots burst outward from the centre of the button like a firework, each on its own path. It's energetic and playful, so it suits casual or marketing pages better than serious developer tools. The particles fly beyond the edges of the button, so this button needs overflow: visible instead of hidden.

Results
const { data } = await fetch('/api/users');
.particle-btn {
  overflow: visible;      /* let the particles escape the button */
}

.particle {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 6px;
  height: 6px;
  margin: -3px 0 0 -3px;  /* centre the dot on that point */
  border-radius: 50%;
  background: #3b82f6;
  pointer-events: none;
  animation: particle-fly 0.65s ease-out forwards;
}

@keyframes particle-fly {
  to {
    translate: var(--tx) var(--ty);   /* set for each particle in JavaScript */
    scale: 0;
    opacity: 0;
  }
}
document.querySelectorAll('.particle-btn').forEach((button) => {
  button.addEventListener('click', async () => {
    if (!(await copyText(button.dataset.copy))) return;

    const count = 10;
    for (let i = 0; i < count; i++) {
      const angle = (i / count) * 2 * Math.PI;      // evenly spaced around a circle
      const distance = 28 + Math.random() * 14;

      const particle = document.createElement('span');
      particle.className = 'particle';
      particle.style.setProperty('--tx', `${Math.cos(angle) * distance}px`);
      particle.style.setProperty('--ty', `${Math.sin(angle) * distance}px`);
      button.append(particle);
      particle.addEventListener('animationend', () => particle.remove());
    }
  });
});

A little trigonometry spaces the particles evenly: Math.cos() and Math.sin() turn each angle into a horizontal and vertical distance. JavaScript stores these in the --tx and --ty custom properties, which the keyframes then use.

Highlighting the copied text

Scanner sweep

A glowing blue line sweeps across the text box while it flashes pale blue, as if the text is being scanned and captured. This effect is applied to the text rather than the button, which makes it a good fit for tokens, hashes and other values that feel machine-readable.

Results
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
<div class="snippet-row">
  <code class="snippet scanner-box">eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9</code>
  <button type="button" class="copy-btn scanner-btn"
          data-copy="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9">
    <!-- copy icon --> Copy
  </button>
</div>
.scanner-box {
  position: relative;
  overflow: hidden;
}

.scanner-box.scanning {
  animation: scan-flash 0.7s ease;
}

.scan-line {
  position: absolute;
  top: 0;
  bottom: 0;
  width: 3px;
  background: linear-gradient(transparent, #2563eb, transparent);
  box-shadow: 0 0 10px #2563eb, 0 0 20px #93c5fd;
  pointer-events: none;
  animation: scan-sweep 0.7s ease-in-out forwards;
}

@keyframes scan-sweep {
  0%   { left: -4px; opacity: 0; }
  5%   { opacity: 1; }
  95%  { opacity: 1; }
  100% { left: calc(100% + 4px); opacity: 0; }
}

@keyframes scan-flash {
  40% { background: #eff6ff; }
}
document.querySelectorAll('.scanner-btn').forEach((button) => {
  button.addEventListener('click', async () => {
    // Find the text box in the same row as this button
    const box = button.closest('.snippet-row').querySelector('.scanner-box');
    if (box.querySelector('.scan-line')) return;   // already scanning
    if (!(await copyText(button.dataset.copy))) return;

    const line = document.createElement('span');
    line.className = 'scan-line';
    box.classList.add('scanning');
    box.append(line);
    line.addEventListener('animationend', () => {
      line.remove();
      box.classList.remove('scanning');
    });
  });
});

Animating the border

Border trace

A bright blue line traces clockwise around the button's border in under a second. It's subtle but impressive. The ring is a conic-gradient() behind the button, and the trick is animating how far round the blue goes.

Results
https://api.example.com/v2/endpoint
<span class="trace-wrap">
  <button type="button" class="copy-btn trace-btn" data-copy="https://api.example.com/v2/endpoint">
    <!-- copy icon --> Copy
  </button>
</span>
@property --progress {
  syntax: "<percentage>";
  inherits: false;
  initial-value: 0%;
}

.trace-wrap {
  position: relative;
  display: inline-flex;
  padding: 3px;              /* the thickness of the ring */
  border-radius: 11px;
  background: #e2e8f0;       /* grey ring at rest */
}

.trace-wrap::before {
  content: "";
  position: absolute;
  inset: 0;
  border-radius: inherit;
  background: conic-gradient(#2563eb var(--progress), transparent 0);
  opacity: 0;
}

.trace-wrap.tracing::before {
  opacity: 1;
  animation: trace-go 0.85s linear forwards;
}

@keyframes trace-go {
  to { --progress: 100%; }
}

.trace-wrap .copy-btn {
  z-index: 1;                /* sits above the ring */
}
document.querySelectorAll('.trace-btn').forEach((button) => {
  button.addEventListener('click', async () => {
    const wrap = button.closest('.trace-wrap');
    if (wrap.classList.contains('tracing')) return;
    if (!(await copyText(button.dataset.copy))) return;

    wrap.classList.add('tracing');
    setTimeout(() => wrap.classList.remove('tracing'), 950);
  });
});

Normally, CSS can't animate a value inside a gradient. The @property rule fixes that: it registers --progress as a percentage, so the browser knows how to animate it smoothly from 0% to 100%.

Celebrating with confetti

Confetti shower

Eighteen coloured pieces of confetti tumble down from the button, each drifting, falling and spinning by a random amount. It's unashamedly joyful, so save it for moments that deserve it, such as promo codes, invite links or finishing a task. On a plain code snippet, it would feel out of place.

Results
Your promo code: WELCOME10
<span class="confetti-anchor">
  <button type="button" class="copy-btn confetti-btn" data-copy="WELCOME10">
    <!-- copy icon --> Copy code
  </button>
</span>
.confetti-anchor {
  position: relative;
  display: inline-flex;
}

.confetto {
  position: absolute;
  top: 0;
  left: 50%;
  z-index: 10;
  width: 7px;
  height: 7px;
  border-radius: 2px;
  pointer-events: none;
  animation: confetti-fall 0.9s ease-in forwards;
}

/* --cx, --cy and --cr are set for each piece in JavaScript */
@keyframes confetti-fall {
  from {
    opacity: 1;
    transform: translate(var(--cx), -4px) rotate(var(--cr));
  }
  to {
    opacity: 0;
    transform: translate(var(--cx), var(--cy)) rotate(calc(var(--cr) + 360deg)) scale(0.3);
  }
}
const confettiColours = ['#2563eb', '#93c5fd', '#fbbf24', '#34d399', '#f87171', '#a78bfa'];

document.querySelectorAll('.confetti-btn').forEach((button) => {
  button.addEventListener('click', async () => {
    if (!(await copyText(button.dataset.copy))) return;

    for (let i = 0; i < 18; i++) {
      const piece = document.createElement('span');
      piece.className = 'confetto';
      piece.style.background = confettiColours[i % confettiColours.length];
      piece.style.setProperty('--cx', `${(Math.random() - 0.5) * 90}px`);
      piece.style.setProperty('--cy', `${40 + Math.random() * 40}px`);
      piece.style.setProperty('--cr', `${Math.random() * 360}deg`);
      piece.style.animationDelay = `${Math.random() * 0.2}s`;
      button.parentElement.append(piece);
      piece.addEventListener('animationend', () => piece.remove());
    }
  });
});

Accessibility and reduced motion

Announce the copy

Animations are great for people who can see them, but a screen reader user won't know the copy worked. Fix this with a live region: an element with role="status", which screen readers announce whenever its text changes. Hide it visually, then update it from the copyText() helper, so every effect gets announcements for free:

<!-- Once, anywhere on the page -->
<p id="copy-status" class="visually-hidden" role="status"></p>
.visually-hidden {
  position: absolute;
  width: 1px;
  height: 1px;
  overflow: hidden;
  clip-path: inset(50%);
  white-space: nowrap;
}
const copyStatus = document.querySelector('#copy-status');

async function copyText(text) {
  try {
    await navigator.clipboard.writeText(text);
    copyStatus.textContent = 'Copied to clipboard';
    return true;
  } catch (error) {
    copyStatus.textContent = 'Sorry, the text could not be copied';
    return false;
  } finally {
    // Clear the message so the same words are announced again next time
    setTimeout(() => { copyStatus.textContent = ''; }, 3000);
  }
}

All the demos in this post use a live region like this one.

Respect reduced motion

Some people find movement on screen distracting, or even makes them feel unwell, so they turn on a "reduce motion" setting on their device. The prefers-reduced-motion media query lets your CSS respond to it. The decorative effects can simply be switched off, and the ones that carry a message can fade instead of move:

@media (prefers-reduced-motion: reduce) {
  /* Remove the purely decorative effects */
  .ripple,
  .particle,
  .confetto,
  .scan-line {
    display: none;
  }

  /* Fade the toast in place, instead of floating it upwards */
  .toast {
    animation-name: toast-fade;
  }

  /* Swap the slide-up labels with a fade, instead of sliding */
  .slide-btn :is(.label-copy, .label-done) {
    transition: opacity 0.2s;
  }
}

@keyframes toast-fade {
  0%, 100% { opacity: 0; }
  15%, 75% { opacity: 1; }
}

The checkmark swap and border trace are already calm enough to leave as they are. If you turn on reduced motion on your device, you'll see the demos above change.

Tips for real projects

Call writeText() straight away

Browsers only allow copying in response to a user action, and Safari is especially strict about it. If your click handler waits for something else first, such as a network request, the copy may be blocked:

// Works: writeText is called straight away, inside the click
button.addEventListener('click', async () => {
  await navigator.clipboard.writeText(button.dataset.copy);
});

// Can fail in Safari: by the time the fetch finishes,
// the browser no longer treats the copy as part of the click
button.addEventListener('click', async () => {
  const response = await fetch('/api/invite-link');
  const link = await response.text();
  await navigator.clipboard.writeText(link);
});

Where possible, have the text ready before the click, so writeText() can run straight away.

More tips

  • Ignore repeat clicks while an effect is playing, as the checkmark swap, slide-up and border trace examples do with a class check.
  • Remove what you add. Elements created for an effect should be removed when they're finished, and the animationend event is the neatest time to do it.
  • Don't add an execCommand('copy') fallback. It's deprecated, and every browser that's still in use supports the Clipboard API.
  • Copying inside an iframe needs permission from the parent page: add allow="clipboard-write" to the <iframe>.

Choosing an effect

Pick the effect that matches the energy of your design. The ripple, checkmark swap and slide-up label work almost anywhere. The toast suits hidden text, and the scanner sweep and border trace suit developer tools. Save the particles and confetti for moments worth celebrating. Whichever you choose, the rule is the same: copy first, and only celebrate when it worked.

☕
Enjoying this site?

Help keep it running with a small coffee donation. Every bit of support is appreciated!

Buy us a coffee