Ben Borgers / Posts /

How to copy text with JavaScript

January 24, 2021 by @benborgers

You can only copy text for the user if it's in an input or textarea.

<input class="copy-to-clipboard" />

If you don't want to have a visible input element on the page, you can add this CSS to the input so that it still exists (in the top left corner) but isn't visible or clickable:

input.copy-to-clipboard {
  opacity: 0;
  pointer-events: none; /* to ignore clicks */
  position: absolute;
  top: 0;
  left: 0;

Now that you've got the input element, you can use JavaScript to fill the value of the input and copy that text to the clipboard:

const copyText = (text) => {
  const input = document.querySelector("input.copy-to-clipboard")
  input.value = text
  input.setSelectionRange(0, 9999) // selects characters 0 through 9,999 in the input
  document.activeElement.blur() // deselects the input

A quick favor: was anything I wrote incorrect or misspelled, or do you still have questions? Please use this form to let me know or ask for help!