-
Notifications
You must be signed in to change notification settings - Fork 9
Open
Description
Copies text to clipboard when clicked. Attach to the node you want to copy or, with the optional target parameter, attach to a button to copy the desired text. I've seen this used a lot for coding tutorials, specifically for copying long terminal commands.
<p use:clickToCopy> Click to copy this text </p>
or
<button use:clickToCopy={'p'}> Click to copy that text </button>
...
export function clickToCopy(node, target) {
async function copyText(event) {
const text = target
? document.querySelector(target).innerText
: event.target.innerText;
try {
await navigator.clipboard.writeText(text);
} catch(e) {
// not sure what kind of error handling.
// could have try/catch dispatch
// success/failure events so the dev
// can use it to alert users of the outcome?
}
}
node.addEventListener('click', copyText);
return {
destroy() {
node.removeEventListener('click', copyText);
}
}
}
REPL example: https://svelte.dev/repl/667d8ac94e2349f3a1b7b8c5fa4c0082?version=3.32.1
Would be happy to try a PR if people like this.
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
No labels