Code Premix

How to Copy to Clipboard in JavaScript

📅April 16, 2022

In this tutorial, we’ll look at how to copy text to the clipboard in JavaScript. Ctrl + C is a common keyboard shortcut for copying text to the clipboard and pasting it somewhere else. If you want to add copy-to-clipboard capability to your website, we can do so quickly and easily with JavaScript.

We may easily copy text inside the text field by using the execCommand() function.

  1. Create HTML page
  2. Write JavaScript code
  3. Output

Let’s start with a simple example.

1. Create HTML page

First, we’ll add the following code to the HTML page that will display the input text box and copy button.

2. Write JavaScript code

To accomplish the copy to clipboard capability, we must write the following JavaScript code.

<script type="text/javascript">
  function copyText() {
    // Get the text field
    var copyText = document.getElementById("textInput");

    // Select the text field
    copyText.select();

    // Copy the text inside the text field
    document.execCommand("copy");

    // Change the button text
    document.getElementById("btnCopy").innerHTML = "Copied!";
  }
</script>

If you hit Ctrl + V or right-click and select Paste after pressing the copy button, the content of the text field will be transferred to the clipboard.

3. Output

Run the HTML page and check the output in the browser.

That’s it for today.
Thank you for reading. Happy Coding..!!