Creating one or multiple buttons to copy text to the clipboard
To create a single “copy to clipboard” button on a website page, we can use simple code like this:
<html>
<head>
<script>
function copy_to_clipboard(elm_id) {
var text = document.getElementById(elm_id).innerHTML;
navigator.clipboard.writeText(text);
}
</script>
</head>
<body>
<p id="1">text to copy</p>
<button onclick="copy_to_clipboard('1')">Copy</button>
</body>
</html>
If we need to have, on the same web page, several buttons in different text boxes, we repeat this code for each button, only being required to change the id attribute for each button. I usually use id=”1” for the first button on the page, id=”2” for the second button, and so on.
If you want to have two or more buttons on the same frame, here is an example:
<html>
<head>
<script>
function copy_to_clipboard(elm_id) {
var text = document.getElementById(elm_id).innerHTML;
navigator.clipboard.writeText(text);
}
</script>
</head>
<body>
<p id="8">text to copy-1</p>
<button onclick="copy_to_clipboard('8')">Copy</button>
<p id="9">text to copy-2</p>
<button onclick="copy_to_clipboard('9')">Copy</button>
<p id="10">text to copy-3</p>
<button onclick="copy_to_clipboard('10')">Copy</button>
</body>
</html>
Enjoy Reading This Article?
Here are some more articles you might like to read next: