Copy text to clipboard in html using javascript
popoola Temitope
Posted on May 29, 2021
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
💖 💪 🙅 🚩
popoola Temitope
Posted on May 29, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
watercooler Why does a reboot make your PC run SO much faster than running all the cleaning tools you can possibly imagine?
November 30, 2024