PASSWORD RESET

Your destination for complete Tech news

How to copy text to the clipboard in JavaScript?

373 0
< 1 min read

To copy text to the clipboard in JavaScript, you can use the execCommand method of the document object, along with the copy command. The execCommand method allows you to execute a command on the current document, such as copying text to the clipboard or printing the document.

Here is an example of how to use the execCommand method to copy text to the clipboard:

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

  // Set the text and style of the textarea
  textarea.textContent = text;
  textarea.style.position = 'fixed'; // Prevent scrolling to bottom of page in MS Edge.
  document.body.appendChild(textarea);

  // Select the textarea
  textarea.select();

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

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

To use this function, you can call it with the text that you want to copy to the clipboard as an argument. For example:

copyToClipboard('Hello, world!');

This will copy the text “Hello, world!” to the clipboard, and the user can paste it into another application or document.

Note that the execCommand method has some limitations and may not work in all browsers or environments. It is also

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.