Skip to content

Instantly share code, notes, and snippets.

@vadviktor
Created July 23, 2023 18:54
Show Gist options
  • Save vadviktor/812df9646471a3ac5fe0d6630f23de62 to your computer and use it in GitHub Desktop.
Save vadviktor/812df9646471a3ac5fe0d6630f23de62 to your computer and use it in GitHub Desktop.
Copy to clipboard button with AlpineJs.
<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>
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