There are all sorts of reasons why you might want to automatically copy some text to the users clipboard. The reason it can be so useful is actually the same reason it’s not possible, it allows data to break out of the webpage sandbox. The clipboard is considered to be part of the operating system so can’t be interacted with using JavaScript from a normal page, interestingly it is possible to copy text from the developer console, but that’s another story.
The traditional way to get around this problem is to use little flash buttons instead of normal ones since flash can access the clipboard without restriction. That causes a bit of a problem though since you then have to maintain and style each button in flash as well as on your page. Introducing ZeroClipboard, a small library that overlays your HTML element with a transparent flash movie and mapping the copy event back to JavaScript.
Once you have the library included copying text when a button is clicked is as simple as adding an extra attribute
<input type="button" value="Copy link" data-clipboard-text="http://some-website.com/" />
and adding the clipboard handler with a bit of JavaScript
(function(){
window.addEventListener('DOMContentLoaded', function(event){
var elements = document.querySelectorAll('[data-clipboard-text]');
var clickHandler = function(event){
event.preventDefault();
};
Array.prototype.forEach.call(elements, function(element){
(new ZeroClipboard(element)).on('ready', function(event){
element.addEventListener('click', clickHandler);
});
});
});
})();
We cancel the click event once we know we can use automatic copying so that a fallback can be added showing the text in a window or something.
There are a few things that get in the way, since the flash movie covers up the button the normal :hover and :active selectors don’t work. Luckily this has been thought about, ZeroClipboard will add a class to the element for all of the pseudo selectors so only a tiny CSS modification is needed
input[type="button"]:hover, input[type="button"].zeroclipboard-is-hover {
/* Hover styles */
}
input[type="button"]:active, input[type="button"].zeroclipboard-is-active {
/* Active styles */
}