Utils (@pim.sk/utils)

copy-code

Adds a clipboard button to any element marked with data-copy-code. The button appears on hover (position:fixed — never shifts layout), copies text to clipboard and confirms via flash message. Works with <pre>, <textarea>, <input> or any element.
import '@pim.sk/utils/copy-code.mjs'

Examples

data-copy-code — copy from self

Add data-copy-code to any element. A clipboard button appears on hover (fixed-position, never shifts layout). Clicking copies the element's text content.

<div data-copy-code>
  Hello, copy-code!
</div>
Hello, copy-code!
import '@pim.sk/utils/copy-code.mjs'   // auto-init via side-effect

data-copy-code="selector" — copy from child

Pass a CSS selector as the attribute value. The button copies from the first matching child element. Typical pattern: <pre data-copy-code="code"><code>...</code></pre> — copies only the inner code, not the wrapper markup.

<pre data-copy-code="code">
  <code>const x = 42</code>
</pre>

// selektor moze byt lubovolny CSS:
<div data-copy-code="textarea.my-area">
  <textarea class="my-area">...</textarea>
</div>
const x = 42
<div data-copy-code="child.selector">...</div>

data-copy-code-class — custom button style

Override the default button classes via data-copy-code-class. Works with Bulma, Bootstrap or any custom class. The attribute is read lazily on each hover — setting it after init takes effect on the next show.

<pre data-copy-code="code"
     data-copy-code-class="button is-danger is-small">
  <code>...</code>
</pre>
is-info is-rounded
is-success is-small
is-danger is-outlined

Hover each element — button style changes per element.

data-copy-code-class="button is-info is-small"

textarea / input — copies .value

When the resolved source element is a <textarea> or <input>, copy-code reads .value instead of innerHTML. Ideal for editable code snippets where the user can modify content before copying.

<div data-copy-code="textarea">
  <textarea>Edit me, then copy!</textarea>
</div>

// input works too:
<div data-copy-code="input">
  <input value="copy me" />
</div>
<div data-copy-code="textarea">
  <textarea></textarea>
</div>

copyCode( input ) — manual / dynamic init

Pass a CSS selector string, a single Element, or any iterable (NodeList, Array). Elements passed directly do not need data-copy-code. Already-bound elements are skipped automatically (idempotent).

// CSS selector — binds all matching elements in document:
copyCode('.my-pre')

// single Element — no data-copy-code attribute required:
copyCode(textareaEl)

// NodeList / Array:
copyCode(document.querySelectorAll('.my-code'))
copyCode([ el1, el2 ])

copyCode('#taManualInit')
v 1.1.2