Copy Text to Clipboard with Pure JavaScript

Copy Text to Clipboard with Pure JavaScript

·

2 min read

Intro

In this blog, you can know the easy way to copy text from browser to clipboard with pure JavaScript without any external libraries or packages.

Where it helps?

This feature may help you in adding the text copying feature in your JS projects.

How it works?

Copying text can only be done from <textarea> and <input> tags of HTML.

1st case:

Copying directly from <textarea> and <input>.

<input class="text"></input>
<button class="copy-button">Copy</button>

or

<textarea class="text"></textarea>
<button class="copy-button">Copy</button>

We use some unfamiliar JS methods to copy.

function copyToClipboard() {
  var text = document.querySelector(".text");
  text.select();
  document.execCommand("copy");
  //document.execCommand("cut"); To cut
}

document.querySelector(".copy-button").addEventListener("click", copyToClipboard);

2nd Case:

Copying from a variable containing a string.

  • Pass the string variable to the function that copies.
  • Create a <textarea> in the DOM and set its value as the string.
  • Append the element to the DOM.
  • Select the element.
  • Execute the copy or cut command.
  • Remove the element from the DOM.
function copyToClipboard() {
  var string = "This is to be copied!";
  var textarea = document.createElement("textarea");
  textarea.value = string;
  document.body.appendChild(textarea);
  textarea.select();
  document.execCommand("copy");
  document.body.removeChild(textarea);
  //document.execCommand("cut");
}

document
  .querySelector(".copy-button")
  .addEventListener("click", copyToClipboard);

⭐Hola, that's it, the required string gets copied to the clipboard. Hope, you find this blog useful and helped you in completing the projects.

Thanks and see you in the next article. Connect with me on Github ,Twitter.