Newsletter
TechAnV Blog
Get updates on security engineering, Rust, eBPF, and DevSecOps. No spam, unsubscribe anytime.
Check your inbox and click the confirmation link to complete your subscription.
Implementing a “copy to clipboard” button#
I had to figure this out while building datasette-copyable - demo here.
The trick is to run document.execCommand("copy") to copy to the clipboard - but only after first ensuring that some selectable content (probably in a textarea) has been selected.
So you do this:
1var ta = document.querySelector("textarea");2var button = document.querySelector("button");3button.onclick = () => {4 ta.select();5 document.execCommand("copy");6};But that’s not quite enough: there’s no visible indication that anything happened!
I decided to fix this by updating the text on the button to say “Copied!” and then reverting the button text back again 1.5 seconds later.
I also opted to add the “copy” button using JavaScript, since without JavaScript enabled it won’t do anything.
Here’s the full HTML and JavaScript snippet I used:
1<div>2<textarea class="copyable">{{ copyable }}</textarea>3<p class="raw-link"><a href="{{ raw_link }}">Raw data</a></p>4</div>5
6<script>7var ta = document.querySelector("textarea.copyable");8var p = document.querySelector("p.raw-link");9var button = document.createElement("button");10button.className = "copyable-copy-button";11button.innerHTML = "Copy to clipboard";12button.onclick = () => {13 ta.select();14 document.execCommand("copy");15 button.innerHTML = "Copied!";16 setTimeout(() => {17 button.innerHTML = "Copy to clipboard";18 }, 1500);19};20p.appendChild(button);21p.insertAdjacentElement("afterbegin", button);22</script>