How to copy text to the clipboard with JavaScript?


To copy text to the clipboard, we will use the HTMLInputElement methods, select() and setSelectionRange(). With that, we have also used the document execCommand() method to copy.

Create an Input Text

We will create an input text. This will the text that we will copy to the clipboard

<input type="text" value="Hello World" class="textInput" />

Set a Button

We will click this button to copy the clipboard text −

<button class="copy">Copy text</button>

You can also style the button accordingly −

button {
   border: none;
   outline: none;
   background-color: rgb(191, 187, 255);
   color: black;
   font-weight: bold;
   padding: 10px;
}

Script to Copy Text to the Clipboard

When the button is clicked the copytext() custom function is called. In the function, we have the select() and setSelectionRange() buil-in functions to copy text to the clipboard.

<script>
document.querySelector(".copy").addEventListener("click", copyText);
function copyText() {
   var copyText = document.querySelector(".textInput");
   copyText.select();
   copyText.setSelectionRange(0, 99999);
   document.execCommand("copy");
   alert("The copied text is: " + copyText.value);
}

Alert box to Display the Clipboard Text

Above, we have also used the alert() to display the copied clipboard text. For that, the value property is used −

alert("The copied text is: " + copyText.value);

Example

The following is the code to copy text to the clipboard with JavaScript −

<!DOCTYPE html>
<html>
<head>
   <style>
      button {
         border: none;
         outline: none;
         background-color: rgb(191, 187, 255);
         color: black;
         font-weight: bold;
         padding: 10px;
      }
      input {
         padding: 10px;
      }
   </style>
</head>
<body>
   <h1>Clipboard example</h1>
   <p>Click the below button to copy text and paste it somewhere</p>
   <input type="text" value="Hello World" class="textInput" />
   <button class="copy">Copy text</button>
   <script>
      document.querySelector(".copy").addEventListener("click", copyText);
      function copyText() {
         var copyText = document.querySelector(".textInput");
         copyText.select();
         copyText.setSelectionRange(0, 99999);
         document.execCommand("copy");
         alert("The copied text is: " + copyText.value);
      }
   </script>
</body>
</html>

Updated on: 17-Nov-2023

326 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements