js select and copy on click

How to select and copy text on click using JavaScript

I recently had a requirement to enable users to select and copy text on click of a button. After researching, I found a few ways to achieve this using JavaScript. Here are some of the ways:

Method 1: Using document.execCommand()

This method allows you to select and copy text programmatically using the document.execCommand() method.


function copyText() {
  var text = document.getElementById("myText").select();
  document.execCommand("copy");
}

In the above code snippet, we first select the text using the select() method and then call document.execCommand("copy") to copy the text to the clipboard.

Method 2: Using Clipboard API

The Clipboard API allows you to interact with the clipboard programmatically. We can use the writeText() method to write the selected text to the clipboard.


function copyText() {
  var text = document.getElementById("myText").select();
  navigator.clipboard.writeText(text);
}

In the above code snippet, we first select the text using the select() method and then call navigator.clipboard.writeText(text) to write the text to the clipboard.

Method 3: Using range and selection objects

The range and selection objects allow you to manipulate and select text on a web page. We can use them to select and copy text on click of a button.


function copyText() {
  var range = document.createRange();
  range.selectNode(document.getElementById("myText"));
  window.getSelection().removeAllRanges();
  window.getSelection().addRange(range);
  document.execCommand("copy");
}

In the above code snippet, we first create a range object and select the text using the selectNode() method. We then add the range to the selection object and call document.execCommand("copy") to copy the text to the clipboard.

These are some of the ways to select and copy text on click using JavaScript. Choose the one that suits your requirements and implement it in your web application.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe