1-Byte
1-Byte Bespoke tools & code

JavaScript

Copy to Clipboard Utility

JavaScript

Adds a simple <code>copyToClipboard</code> function you can call from buttons or icons. Works with plain strings or the text content of an element.

Usage notes

Include this in your front-end bundle and wire it to any button that should copy text.

<button onclick="copyToClipboard(document.querySelector('#my-code').innerText)">
  Copy
</button>

Copy this snippet into your project

Use the full version for learning, or copy it without comments when you just want the bare code.

export async function copyToClipboard(textOrElement) {
  let text = textOrElement;

  if (textOrElement instanceof HTMLElement) {
    text = textOrElement.innerText || textOrElement.textContent || '';
  }

  if (typeof text !== 'string') {
    text = String(text ?? '');
  }

  try {
    await navigator.clipboard.writeText(text);
    return true;
  } catch (err) {
    console.error('Clipboard copy failed', err);
    return false;
  }
}
      

Tags

#javascript #clipboard #ux #buttons
← Back to all snippets