JavaScriptmediumJavaScript

Copy to Clipboard

Copies text to user's clipboard

01

The problem

Need to copy text to user's clipboard

02

The solution

JavaScript
async function copyToClipboard(text) {
  try {
    // Use modern Clipboard API
    if (navigator.clipboard && window.isSecureContext) {
      await navigator.clipboard.writeText(text);
      return true;
    } else {
      // Fallback for older browsers
      const textarea = document.createElement('textarea');
      textarea.value = text;
      textarea.style.position = 'fixed';
      textarea.style.opacity = '0';
      document.body.appendChild(textarea);
      textarea.select();
      const success = document.execCommand('copy');
      document.body.removeChild(textarea);
      return success;
    }
  } catch (error) {
    console.error('Copy failed:', error);
    return false;
  }
}

03

Parameters

textstring

Text to copy

04

Put it to work

Example
// Copy static text
const success = await copyToClipboard('Hello, World!');
if (success) {
  alert('Copied to clipboard!');
}

// Copy dynamic content
const element = document.querySelector('#content');
copyToClipboard(element.textContent);

// Copy with feedback
async function copyWithFeedback(text, successMsg = 'Copied!') {
  if (await copyToClipboard(text)) {
    console.log(successMsg);
  } else {
    console.error('Copy failed');
  }
}