I’m trying to create a small (local) page that allows me to copy frequently used texts to the clipboard by clicking on a button.
My code (see below) works so far.
Now my question:
Is there a way to adapt the Javascript code so that I don’t have to create my own/new Javascript function for every new field (there are very, very many) and never have to adjust the Javascript-Code again?
<html>
<head>
<title>Copy!</title>
<script>
function c1() {
var c = document.getElementById("c1");
navigator.clipboard.writeText(c.value);
}
function c2() {
var c = document.getElementById("c2");
navigator.clipboard.writeText(c.value);
}
</script>
</head>
<body>
<span>
I want to be copied!<br />
<input type="text" value="First value to be copied" id="c1"> <button onclick="c1()">Copy the first value!</button>
</span>
<br /><br />
<span>
But I also want to be copied<br />
<input type="text" value="And the second value" id="c2"> <button onclick="c2()">And now the second!</button>
</span>
</body>
</html>
2
Answers
Here’s the solution. To copy text without editing JS. All you need to do is just add copyText class in input element.
You can also add checks like
Start by adding an event listener to the "copyable" zone. On click, check that the click’s target is a button OR that it has a button as its parent (to make sure we include the text within the button). If we clicked within the button, get its previous element sibling, the input and copy its value to the clipboard.