skip to Main Content

How do I copy to the clipboard in JavaScript?

In JavaScript, you can copy text or data to the clipboard using the Clipboard API. Here’s an example of how you can accomplish this:

function copyToClipboard(text) {
  // Create a temporary textarea element
  const textarea = document.createElement('textarea');
  textarea.value = text;

  // Make the textarea hidden
  textarea.style.position = 'fixed';
  textarea.style.opacity = 0;

  // Append the textarea to the DOM
  document.body.appendChild(textarea);

  // Select and copy the text from the textarea
  textarea.select();
  document.execCommand('copy');

  // Remove the textarea from the DOM
  document.body.removeChild(textarea);
}

// Usage:
const textToCopy = 'Hello, world!';
copyToClipboard(textToCopy);

In this example, the copyToClipboard function takes a text parameter representing the text you want to copy. It creates a temporary <textarea> element, sets its value to the desired text, and makes it hidden by positioning it off-screen with 0 opacity.

The <textarea> is then appended to the document’s body, selected, and the document.execCommand('copy') method is called to copy the selected text to the clipboard. Finally, the <textarea> element is removed from the DOM.

Please note that the document.execCommand method is deprecated, but it is still widely supported by modern browsers. An alternative approach using the asynchronous Clipboard API is available, but it requires additional permissions and complexity.

A Self Motivated Web Developer Who Loves To Play With Codes...

This Post Has 0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top