Copy to clipboard in JavaScript

javascript

Copying text to the clipboard in JavaScript can be achieved by using the Clipboard API. Here is an example function that can be used to copy a string to the clipboard:

function copyToClipboard(text) {
  // Create a temporary textarea element
  var textarea = document.createElement('textarea');
  textarea.value = text;
  textarea.setAttribute('readonly', '');  // Make it readonly to prevent focus and move outside of view

  // Add the textarea to the document
  document.body.appendChild(textarea);

  // Select the text in the textarea
  textarea.select();

  // Copy the text to the clipboard
  document.execCommand('copy');

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

To use this function, simply pass the text you want to copy as an argument. For example:

var myText = 'Hello, world!';
copyToClipboard(myText);

This function creates a temporary textarea element and sets its value to the text that needs to be copied. It then selects the text in the textarea, copies it to the clipboard using document.execCommand(‘copy’), and finally removes the textarea from the document.

Note that the Clipboard API is not supported in some older browsers, so it’s a good idea to provide a fallback method for copying text to the clipboard. One way to do this is by prompting the user to manually copy the text by displaying a message with the text to copy.