Copy button

Copy a fixed text

Add data-copy to a .btn. Children marked data-idle show normally, and children marked data-done show for 1.5 seconds after the copy.

Copy from an element

data-copy-target takes a selector. An input or textarea copies its value; any other element copies its text.

Copy a code block

In a .code-block the button sits in the top right corner of the pre, for commands and snippets.

npm install @tsunami/ui

With a toast

data-copy-toast also shows a toast. Leave it empty for "Copied", or give your own message.

API

NameValuesDescription
tsunami.copy(text)stringCopies the text and returns a promise of true or false. It uses navigator.clipboard and falls back to document.execCommand("copy") on pages that are not a secure context.

Events

NameValuesDescription
tsunami:copydetail.textBubbles from the button after a successful copy.

Attributes

Attribute / elementValuesDescription
data-copytextThe text to copy.
data-copy-targetCSS selectorCopies the value of an input or textarea, or the text of any other element. Used when there is no data-copy.
data-copy-toastmessage (may be empty)Shows a toast too. Empty means Copied.
data-copiedset by the scriptOn the button for 1.5 s after a copy. Use it to style the state.
[data-idle]childHidden while the button has data-copied.
[data-done]childShown only while the button has data-copied.

Accessibility

  • Every copy is announced as Copied in a polite live region, so the icon swap is not the only signal.
  • An icon-only button needs an aria-label.
  • Nothing happens if the clipboard is blocked or the target is missing; the button stays as it was.