• Post category:JavaScript
  • Reading time:4 mins read

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.

Implementing the feature of copying text to the clipboard

  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.

index.html
<html>

<head>
  <title>Copy text to the clipboard using JavaScript - Code Premix</title>
</head>

<body>
  <div class="container">
    <h3>Copy text to the clipboard using JavaScript - <a href="https://codepremix.com/" target="_blank" rel="noopener noreferrer">Code Premix</a></h3>
    <input type="text" value="Welcome to Code Premix" id="textInput" />
    <button id="btnCopy" onclick="copyText()">Copy Text</button>
  </div>
</body>

</html>

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..!!

Leave a Reply