Component

Copy pre

Published on

Description anchor

Write a plain <pre><code> block and mark it up as <pre is="ds-copy-pre">. The component prepends a button that writes the text content of the nested <code> element to the clipboard. Without JavaScript the block still renders as preformatted text, only the button is missing, so nothing is lost.

Use it for anything a reader is expected to paste elsewhere: install commands, configuration snippets, tokens, identifiers. It pairs with the Codeblock component, which wraps its highlighted code in this same element.

Example anchor

Open in new tab(opens in new tab)
View HTML markup
  <pre is="ds-copy-pre">
  <code>npm install @willfarrell-ds/vanilla</code></pre> <pre is="ds-copy-pre" data-i18n-copy="Copy token" data-i18n-copied="Token copied">
  <code>eyJhbGciOiJFZERTQSIsInR5cCI6IkpXVCJ9</code></pre>

Accessibility anchor

  • The control is a native <button type="button">, so it is reachable by keyboard and activated with Enter or Space.
  • The icon is aria-hidden="true" and focusable="false"; the accessible name comes from a visually hidden label.
  • That label is an aria-live="polite" region that switches from Copy to Copied for two seconds, so success is announced rather than shown only in colour.
  • The button is prepended in the DOM so it is announced before the code it copies, and moved to the inline end corner visually with order.
  • Text and line breaks are preserved by <pre>, so what is announced matches what is copied.

References anchor

  • Codeblock — for code samples that also need syntax highlighting
  • Icon — used for the button glyph
  • Inline format — for short code references within a sentence

Variables anchor

  • data-icon — icon reference, defaults to /img/icons.svg#copy
  • data-i18n-copy — idle label, defaults to Copy
  • data-i18n-copied — confirmation label, defaults to Copied