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.

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

2. Write JavaScript code

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

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

If you found value in this article,
you can support us by buying me a coffee! ☕

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *