Copy Button

This page contains the recipe to make a copy button.

It is activated by adding data-js="copy" to an element and including the CSS and JS files.

The button itself is an SVG that is added to an HTML element using an ::after pseudo-element.

The JS is an EventListener on a Click event, and uses navigator.clipboard to copy the text.

Once the text is copied, the button is given a CSS class that changes the SVG to a checkmark.

Both SVG icons are taken from Material Line Icons.

It can be seen in action below.

<link rel="stylesheet" href="https://gist.pother.ca/33b4d10024f56ba0610f8e70477687cb/copy-button.css">
<script async src="https://gist.pother.ca/33b4d10024f56ba0610f8e70477687cb/copy-button.js"></script>
<pre data-js="copy">Your Text Goes Here</pre>

If the HTML of the target should be copied (rather than the text) use: data-js="copy copy-html". This will also copy any HTML tags present in the content.

To have a button that copies something else, add data-js-copy="selector", where selector can be any valid CSS selector.

For example:

<link rel="stylesheet" href="https://gist.pother.ca/33b4d10024f56ba0610f8e70477687cb/copy-button.css">
<script async src="https://gist.pother.ca/33b4d10024f56ba0610f8e70477687cb/copy-button.js"></script>
<a data-js="copy" data-js-copy="pre[data-js-copy-this='target']" title="Copy the text below"></a>
<pre data-js-copy-this="target">Your Text Goes Here</pre>