copy clipboard in javascript

To copy data to the clipboard using JavaScript, you can use the following code:

index.tsx
function copyToClipboard(text) {
  var input = document.createElement('textarea');
  input.value = text;
  document.body.appendChild(input);
  input.select();
  document.execCommand('copy');
  document.body.removeChild(input);
}
229 chars
9 lines

This code creates a new textarea element, sets its value to the text parameter, adds it to the document body, selects its contents, copies them to the clipboard using the execCommand method, and removes the textarea element from the document.

To use this function, simply call it with the text you want to copy:

index.tsx
copyToClipboard('Hello, world!');
34 chars
2 lines

Note that in modern browsers, the execCommand method may only work in response to a user-triggered event, such as a click or key press. To work around this restriction, you can listen for a copy or paste event and trigger the copying or pasting code in response to it.

gistlibby LogSnag