copy to clipboard in javascript

To copy text to clipboard using Javascript, we can use the execCommand method. However, this method is deprecated in many modern browsers, but still, it works on most of them.

Here is an example that shows how to copy text to the clipboard using the execCommand method:

function copyToClipboard(text) {
  const textarea = document.createElement('textarea');
  textarea.value = text;
  document.body.appendChild(textarea);
  textarea.select();
  document.execCommand('copy');
  document.body.removeChild(textarea);
}
246 chars
9 lines

We create a new TextArea element and set its value to the desired text. Then we add it to the document, select the contents of the TextArea, and execute the copy command.

We can use this function in our code like this:

const copyButton = document.querySelector('#copy-button');
const copyText = 'Copy this text';
copyButton.addEventListener('click', () => {
  copyToClipboard(copyText);
});
172 chars
6 lines

In this example, we create a button with an ID copy-button and on click event, we call the copyToClipboard function, passing the text to be copied as an argument.

gistlibby LogSnag