Copy to clipboard

Update 4 Oct 2015, this ugly flash workaround is now obsolete thanks to clipboard.js.

I recently worked on a web app that present code snippets to the user, so I though it would be nice to have a “copy to clipboard” feature. Saving a few clicks is always welcome!

So first thing to note is the lack of a standard javascript function for that. The most common way is to use an invisible flash movie, which means it won’t work on a mobile devise (and you need to handle it gracefully).

I will use ZeroClipboard, which is the most popular library that implement this flash hack. To make it looks nice I will use Bootstrap




<div class="code-box">
    <span class="btn btn-default btn-sm btn-clipboard pull-right" data-clipboard-target="code">
    <pre id="code">
var odds = => v + 1);
var nums =, i) => v + i);
var pairs = => ({even: v, odd: v + 1}));


// zeroclipboard object
var clip = new ZeroClipboard($('.btn-clipboard'));
var clipElems = $(clip.elements());
// tooltip logic
var tooltipOptions = {title: 'Copy to clipboard', placement: 'top'};
clipElems.tooltip(tooltipOptions); {'bs.tooltip').options.title = 'Copied!';
clipElems.mouseleave(function () {'bs.tooltip').options.title = tooltipOptions.title;


.btn-clipboard {
    position: relative;
    right: 51px;
    border-radius: 0 4px 0 4px;

.zeroclipboard-is-hover {
    color: #fff;
    border-color: #563d7c;
    background-color: #563d7c;

I created a Gist with the full example.