Playground
A small icon button that copies its value to the clipboard and confirms with a check mark. Every code block on this site uses it.
Examples
Basic
<sb-button>Launch</sb-button>
<code><sb-button>Launch</sb-button></code>
<sb-copy-button value="<sb-button>Launch</sb-button>"></sb-copy-button>
Copy a Datastar signal
Bind value to a signal with data-attr, and the button always copies the current value.
<div data-signals:_coords="'51.4779° N, 0.0015° W'">
<span data-text="$_coords"></span>
<sb-copy-button data-attr:value="$_coords" label="Copy coordinates"></sb-copy-button>
</div>
React to copies
The sb-copy event bubbles out of the shadow root, so data-on works on any ancestor.
<div data-signals:_copies="0" data-on:sb-copy="$_copies++">
<sb-copy-button value="ignition"></sb-copy-button>
<span data-text="'Copied ' + $_copies + ' times'"></span>
</div>
Accessibility
The button has an accessible label (label, then copied-label after copying). The visual "Copied!" bubble is decorative.
Installation
Add Datastar with Rocket and the Starbase autoloader once per page, then use the tag. The autoloader imports each component the first time its tag appears, including tags added later by a Datastar morph.
<!-- Once per page: Datastar with Rocket, and the Starbase autoloader.
It loads every <sb-…> component the first time its tag appears. -->
<script type="importmap">
{ "imports": { "datastar": "https://cdn.jsdelivr.net/gh/starfederation/datastar@v1.0.4/bundles/datastar-rocket.js" } }
</script>
<script type="module" src="https://rocket.libretto.ch/c/autoloader.js"></script>
<!-- Optional, no flash of undefined elements: class="sb-cloak" on <html>, and -->
<style>.sb-cloak :not(:defined) { visibility: hidden }</style>
<div style="display: flex; align-items: center; gap: 8px"><code>go run .</code><sb-copy-button value="go run ."></sb-copy-button></div>
<!-- Or skip the autoloader and load just this component: -->
<!-- <script type="module" src="https://rocket.libretto.ch/c/copy-button/copy-button.js"></script> -->API reference
Props
| Attribute | Type | Default | Description |
|---|---|---|---|
value | string | "" | The text copied to the clipboard. |
label | string | "Copy to clipboard" | Accessible label of the button. |
copied-label | string | "Copied!" | Label shown after copying. |
reset-ms | number | 1600 | How long the copied state lasts, in ms. |
Events
| Name | Description |
|---|---|
sb-copy | After copying. detail: { value }. |