Copy to clipboard

Copy any text to clipboard

How It Works

  • Clicking an element with blx-el="copy-trigger":
    • Finds the corresponding copy-text and reads its content
    • Writes the content to the clipboard
    • Shows the matching copy-alert with animation
  • Uses blx-id (optional for single instance) to associate the three elements

‍

<!-- BLX by https://www.codeandwander.com -- Copy to clipboard -->
<script>
  document.addEventListener('click', function (event) {
    const trigger = event.target.closest('[blx-el="copy-trigger"]');
    if (!trigger) return;

    const id = trigger.getAttribute('blx-id') || '';

    // Match text element
    const textEl = document.querySelector(
      `[blx-el="copy-text"][blx-id="${id}"], [blx-el="copy-text"]:not([blx-id])`
    );

    // Match alert element
    const alertEl = document.querySelector(
      `[blx-el="copy-alert"][blx-id="${id}"], [blx-el="copy-alert"]:not([blx-id])`
    );

    const text = textEl?.textContent || textEl?.value || '';
    if (!text) return;

    // Special case: sharelink
    const finalText = id === 'sharelink' ? window.location.href : text;

    navigator.clipboard.writeText(finalText).then(() => {
      if (!alertEl) return;

      alertEl.style.display = 'block';
      alertEl.classList.add('show');

      setTimeout(() => {
        alertEl.classList.remove('show');
        alertEl.style.display = 'none';
      }, 2000);
    }, (err) => {
      console.error('Copy failed:', err);
    });
  });
</script>

CSSΒ (Slide-Up animation)

Used to show and hide the alert

[blx-el="copy-alert"] {
  position: relative;
  opacity: 0;
  transform: translateY(10px);
  transition: opacity 0.2s ease-in, transform 0.2s ease-in;
  display: none;
}

[blx-el="copy-alert"].show {
  opacity: 1;
  transform: translateY(0);
  display: block;
}

You need three elements:

  1. blx-el="copy-trigger" β€” The clickable element
  2. blx-el="copy-text" β€” The element containing the text to copy
  3. blx-el="copy-alert" β€” The alert element shown after copy

They must share the same blx-id to be linked.

Optional Enhancements

  • Add role="alert" and aria-live="polite" to your alert for screen reader support.
  • Replace .copy-alert with your own class and styles.
  • Wrap this logic in a reusable BLX component handler (blx.component('copy', handler) if you build one).

πŸ” You can also use blx-id="sharelink" to copy the current page URL.