DEV Community

popoola Temitope
popoola Temitope

Posted on

Copy text to clipboard in html using javascript

In this post we are going to learn how to copy text on a webpage direct to our client device.

HTML Part

Note this only work with select text.
Create a html file and copy the code below in the file.

 <!DOCTYPE html> <html> <head> <title></title> </head> <body> <!-- The text field --> <input type="text" value="text me to copy" id="mycopy"> <!-- The button used to copy the text --> <button onclick="myFunction()">Copy text</button> </body> </html> 
Enter fullscreen mode Exit fullscreen mode

What the above html code do is

 <input type="text" value="text me to copy" id="mycopy"> 
Enter fullscreen mode Exit fullscreen mode
  • This is an input tag that will contain the value of the text we want to copy and the attribute id="mycopy" to identify the input tag that we also want to select and copy.


  •  <button onclick="myFunction()">Copy text</button> 
    Enter fullscreen mode Exit fullscreen mode
  • the above button tag contain onclick="myFunction()" which when user click on the button the text will be copy.
  • JavaScript Part

     <script> function myFunction() { /* Get the text field */ var copyText = document.getElementById("mycopy"); /* Select the text field */ copyText.select(); copyText.setSelectionRange(0, 99999); /* For mobile devices */ /* Copy the text inside the text field */ document.execCommand("copy"); /* Alert the copied text */ alert("Copied the text: " + copyText.value); } </script> 
    Enter fullscreen mode Exit fullscreen mode

    What the above script code do is:

  • we create the myFunction() function tht will copy the text whenever is call

  • var copyText = document.getElementById("mycopy");

  • Here will get id of the text we want to copy "mycopy"
  • copyText.select();

  • This'll select the input/text area automatic, which will allow us to copy the selected text.
  •  copyText.setSelectionRange(0, 99999); 
    Enter fullscreen mode Exit fullscreen mode
  • This is to select the range of the text



  •  document.execCommand("copy"); 
    Enter fullscreen mode Exit fullscreen mode
  • This code copy the text to the clipboard.



  •  <!DOCTYPE html> <html> <head> <title></title> </head> <body> <!-- The text field --> <input type="text" value="text me to copy" id="mycopy"> <!-- The button used to copy the text --> <button onclick="myFunction()">Copy text</button> <script> function myFunction() { /* Get the text field */ var copyText = document.getElementById("mycopy"); /* Select the text field */ copyText.select(); copyText.setSelectionRange(0, 99999); /* For mobile devices */ /* Copy the text inside the text field */ document.execCommand("copy"); /* Alert the copied text */ alert("Copied the text: " + copyText.value); } </script> </body> </html> 
    Enter fullscreen mode Exit fullscreen mode

    Feel free to leave comment

    Top comments (0)