Clue Mediator

How to copy text to the clipboard using JavaScript

📅January 18, 2021

In this article, we’ll discuss how to copy text to the clipboard using JavaScript.

Generally, Ctrl + C keyboard shortcut is used to copy text to the clipboard for the purpose of pasting it somewhere else. If you want to copy text to the clipboard functionality in your website, we can do it easily using JavaScript.

Using execCommand() method, we can easily copy text inside the text field.

You may also like the following articles related to ReactJS.

Example

We will create the following example for the demonstration.

Output - How to copy text to the clipboard using JavaScript - Clue Mediator

Output - How to copy text to the clipboard using JavaScript - Clue Mediator

Steps to implement copy text to the clipboard functionality

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

Let’s start with a simple example.

1. Create HTML page

First, we will write the following code in the HTML page where the input text field and copy button will be displayed.

index.html




  <title>Copy text to the clipboard using JavaScript - Clue Mediator</title>



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

2. Write JavaScript code

Now, we have to write the JavaScript code to perform the copy to clipboard functionality.

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

After clicking the copy button, if you try to press Ctrl + V or right click and select Paste, you will see that the content of the text field has been copied to the clipboard.

3. Output

Run the HTML page and you can see the output as expected.

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