Component
Copy pre
Published on
Description
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
Accessibility
- 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"andfocusable="false"; the accessible name comes from a visually hidden label. - That label is an
aria-live="polite"region that switches fromCopy
toCopied
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
Related
- 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
data-icon— icon reference, defaults to/img/icons.svg#copydata-i18n-copy— idle label, defaults toCopydata-i18n-copied— confirmation label, defaults toCopied