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>
What the above html code do is
<input type="text" value="text me to copy" id="mycopy">
<button onclick="myFunction()">Copy text</button>
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>
What the above script code do is:
var copyText = document.getElementById("mycopy");
copyText.select();
copyText.setSelectionRange(0, 99999);
document.execCommand("copy");
<!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>
Feel free to leave comment
Top comments (0)