We use JavaScript's document.execCommand() to copy the text to the clipboard.


How To copy text to clipboard with JavaScript ?


Copy Text to Clipboard

We will use the following steps to copy text to clipboard:

Step (1) : In the first step we create an input box and a button.

<!-- An input box -->
<input type="text" value="CodexRadar" id="inputText">

<!-- This button used to copy text to clipboard -->
<button onclick="copyText()">Copy Text</button> code-box

Step (2) : In this step, we write the code of JavaScript in the following step:
  • First of all, create a copyText() function.
  • Then with the help of getElementById() method, we will get the value of the input box, whose id is inputText and store it in a variable named text.
  • Then using the select() method, we select the text that was stored in the text variable in the previous step.
  • Then copy the text of the input box with the help of document.execCommand ("copy").
  • All values of the input box can be selected using the setSelectionRange(selectionStart, selectionEnd) method.

function copyText() {
/* Get the value of input box */
var text = document.getElementById("inputText");

/* Select this text */
text.select();
text.setSelectionRange(0, 99999);

/* Copy text with this */
document.execCommand("copy");

/* Alert the copied text */
alert("Copied the text: " + text.value);
} code-box

Note: The document.execCommand() method is not supported in IE8 and earlier. alert-warning


Output

Post a Comment

Previous Post Next Post