0

I create my own portfolio website, on the navigation bar, there is my email. I want anybody cliking on this email will copy it to the clipboard. That's what i tried but it's not working !

<button onclick="copy()" id="copy">Copy</button>

function copy() {
var copyText = document.querySelector("#copy"); 
copyText.select(); document.execCommand("copy");}
document.querySelector("#copy").addEventListener("click", copy);
Theo H
  • 26
  • 1
  • 5
  • 2
    It looks like somebody else [has also asked this](https://stackoverflow.com/search?q=%5Bjavascript%5Dcopy+text+to+clipboard). – Teemu Jan 06 '22 at 17:17
  • https://stackoverflow.com/questions/400212/how-do-i-copy-to-the-clipboard-in-javascript – lucas Jan 06 '22 at 17:21
  • Does this answer your question? [How do I copy to the clipboard in JavaScript?](https://stackoverflow.com/questions/400212/how-do-i-copy-to-the-clipboard-in-javascript) – Max Klein Oct 16 '22 at 21:35

3 Answers3

2

Buttons do not have a select method, text boxes do.
You can use a text input to hold the email address to copy to the clipboard.

function copy() {
  var copyText = document.querySelector("#email"); 
  copyText.select(); document.execCommand("copy");
}
document.querySelector("#copy").addEventListener("click", copy);
input {margin:-100%}
<button onclick="copy()" id="copy">Copy</button>
<input id=email value="email@so.com"> 

Buttons do not have a select method, textboxes have it.

Musa
  • 96,336
  • 17
  • 118
  • 137
1

Do not use execCommand(). It has been deprecated, browsers still support it for now, but not in the future.

For a better solution, You can refer to this: https://stackoverflow.com/a/75721119/21388320

0

Note that there is an ability to "request permission" and test for access to the clipboard via the permissions API in Chrome 66.

var text = "text to be copied"
navigator.clipboard.writeText(text).then(_ => {
  console.log('copied successfully!')
})
AnonHexo
  • 63
  • 1
  • 5