Svelte Copy
Usage
The simplest use is to just pass the text you want to copy
<script>
import { copy } from 'svelte-copy';
</script>
<button use:copy={'__text__'}>
Copy
</button>
We could pass this as an object
<button use:copy={{ text: '__text__' }}>
Copy
</button>
Let's alert the user if the text was copied
<button
use:copy={{
text: '__text__',
onCopy() {
alert('Copied text!');
},
}}
>
Copy
</button>
We could tell the user what was copied
<button
use:copy={{
text: '__text__',
onCopy({ text }) {
alert(`Copied Text: "${text}"`);
},
}}
>
Copy
</button>
If there was an error, we can check for that too
<button
use:copy={{
text: '__text__',
onError({ error }) {
alert(error.message);
},
}}
>
Copy
</button>
We can trigger the copy on custom events
<button
use:copy={{
text: '__text__',
events: ['pointerover'],
onCopy({ text, event }) {
alert(`The text "${text}" was copied because of the "${event.type}" event`);
},
onError({ error }) {
alert(error.message);
},
}}
>
Copy
</button>
Extra
copyText()
We expose the underlying copyText
function. It uses the navigator.clipboard
API by default, with a fallback to the legacy
method.
<script lang="ts">
import { copyText } from 'svelte-copy';
import { Debounced } from 'runed';
let text = $state('');
const debounced = new Debounced(() => text);
$effect(() => {
if (debounced.current) {
copyText(debounced.current)
.then(() => alert('Copied!'))
.catch((error) => alert(error?.message));
}
});
</script>
<input
type="text"
placeholder="Text to copy..."
bind:value={text} />