I often find myself wanting a simple copy button in my web projects.
This is the recipe I build them from using clipboard.js and a couple lines of JavaScript.
In this case I use icons, specifically LineAwesome, to indicate that the copy operation ocurred. There are certainly better solutions with toasts and the like, which this can easily be extended to.
<link
rel="stylesheet"
href="https://maxst.icons8.com/vue-static/landings/line-awesome/line-awesome/1.3.0/css/line-awesome.min.css"
/>
<button
class="clippy las la-clipboard"
data-clipboard-text="I want to be in the clipboard please"
>
Click to copy
</button>
<script src="https://cdn.jsdelivr.net/npm/clipboard@2.0.11/dist/clipboard.min.js"></script>
<script>
var clipboard = new ClipboardJS(".clippy");
clipboard.on("success", function (e) {
e.trigger.classList.add("la-clipboard-check");
setTimeout(function () {
e.trigger.classList.remove("la-clipboard-check");
}, 500);
});
</script>
Try it out with this button, which is basically the one from above with some classes to render properly on my blog: