How to copy text to the clipboard using JavaScript
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.
Steps to implement copy text to the clipboard functionality
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <html> <head> <title>Copy text to the clipboard using JavaScript - Clue Mediator</title> </head> <body> <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> </body> </html> |
2. Write JavaScript code
Now, we have to write the JavaScript code to perform the copy to clipboard functionality.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <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..!! 🙂