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);
CodePudding user response:
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!')
})
CodePudding user response:
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 protected]">
Buttons do not have a select method, textboxes have it.
