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

Screenshot

Screenshot

HTML

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

Javascript

// 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);
clipElems.click(function() {
    clipElems.data('bs.tooltip').options.title = 'Copied!';
    clipElems.tooltip('show');
});
clipElems.mouseleave(function () {
    clipElems.data('bs.tooltip').options.title = tooltipOptions.title;
});

CSS

.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.