Created
July 23, 2023 18:54
-
-
Save vadviktor/812df9646471a3ac5fe0d6630f23de62 to your computer and use it in GitHub Desktop.
Copy to clipboard button with AlpineJs.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<div> | |
<button class="btn btn-dark" type="button" | |
x-on:click="copyToClipboard" | |
id="clipboard-000"> | |
<i class="bi bi-clipboard"></i> Copy to clipboard | |
</button> | |
<div class="d-none" id="clipboard-000-text">Text to be copied to the clipboard</div> | |
</div> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let copyToClipboard = (e) => { | |
let currentTarget = e.currentTarget; | |
navigator.permissions.query({name: "clipboard-write"}).then(result => { | |
if (result.state == "granted" || result.state == "prompt") { | |
// Clipboard access is granted. Use it to write to the clipboard | |
const text = document.getElementById(`${currentTarget.id}-text`).innerText; | |
try { | |
navigator.clipboard.writeText(text); | |
console.log('Text copied to clipboard'); | |
} catch (err) { | |
console.log('Failed to copy text: ', err); | |
} | |
} else { | |
console.log('Clipboard access denied'); | |
} | |
}).catch(err => { | |
console.log('Clipboard access denied: ', err); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment