1function copyToClipboard(text) {
2 const elem = document.createElement('textarea');
3 elem.value = text;
4 document.body.appendChild(elem);
5 elem.select();
6 document.execCommand('copy');
7 document.body.removeChild(elem);
8}
1<head><script>
2function copyToCliBoard() {
3 var copyText = document.getElementById("myInput");
4 copyText.select();
5 copyText.setSelectionRange(0, 99999); /* For mobile devices */
6 document.execCommand("copy");
7 alert("Copied the text: " + copyText.value);
8}
9</script></head>
10
11<body>
12<input type="text" value="Hello World" id="myInput">
13<button onclick="copyToCliBoard()">Copy text</button>
14</body>
1function textToClipboard (text) {
2 var dummy = document.createElement("textarea");
3 document.body.appendChild(dummy);
4 dummy.value = text;
5 dummy.select();
6 document.execCommand("copy");
7 document.body.removeChild(dummy);
8}
9
1const copyToClipboard = () => {
2
3 navigator.permissions.query({name: "clipboard-write"}).then(result => {
4 if (result.state == "granted" || result.state == "prompt") {
5 // write to the clipboard now
6 updateClipboard('I copy this string');
7 }
8 });
9};
10
11const updateClipboard = (newClip) => {
12
13 navigator.clipboard.writeText(newClip).then(() => {
14 // clipboard successfully set
15 console.log('success');
16 }, () => {
17 // clipboard write failed
18 console.log('Failed to copy');
19 });
20};
21
22const btn = document.getElementById('copy-button');
23
24btn.addEventListener('click', copyHashtagToClipboard);
25
26