Skip to content

Instantly share code, notes, and snippets.

@JamesMGreene
Last active August 29, 2015 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JamesMGreene/ec05eca43b1433a6a663 to your computer and use it in GitHub Desktop.
Save JamesMGreene/ec05eca43b1433a6a663 to your computer and use it in GitHub Desktop.
An example of how synthetic click-to-"copy" events might look if we use `document.execCommand`.
var hasModernClipboardApi, queryCopySupported, syntheticCopySupported, button;
hasModernClipboardApi = window.ClipboardEvent != null;
try {
queryCopySupported = document.queryCommandSupported("click-to-copy") === true;
}
catch (e) {
queryCopySupported = false;
}
syntheticCopySupported = hasModernClipboardApi && queryCopySupported;
button = document.getElementById("copyButton");
if (!syntheticCopySupported) {
//
// Polyfill in with Flash clipboard support or the weakly supported RichTextEditor and/or oldIE Clipboard APIs
//
// e.g.
var client = new ZeroClipboard(button);
client.on("ready", function() {
client.on("copy", function(e) {
e.clipboardData.setData("text/plain", "WINNING! With Flash...");
//e.preventDefault();
});
});
}
else {
button.addEventListener("click", function(e) {
var isClickEvent,
queryCopyEnabled,
syntheticCopyEnabledRightNow,
syntheticCopySucceeded;
isClickEvent = e != null && e.type === "click";
try {
queryCopyEnabled = document.queryCommandEnabled("click-to-copy") === true;
}
catch (e) {
queryCopyEnabled = false;
}
syntheticCopyEnabledRightNow = isModernCopyEvent && queryCopyEnabled;
if (syntheticCopyEnabledRightNow) {
try {
// Trigger the copy action
syntheticCopySucceeded = document.execCommand("copy", false, null);
}
catch (e) {
syntheticCopySucceeded = false;
}
}
else {
syntheticCopySucceeded = false;
}
// Announce the results
console.log("Click-to-copy was " + (syntheticCopySucceeded ? "NOT " : "") + "successful");
}, false);
button.addEventListener("copy", function(e) {
if (e != null && e.clipboardData && e.clipboardData.setData) {
e.clipboardData.setData("text/plain", "WINNING! With HTML.");
e.preventDefault();
}
else {
console.error("Unexpected error! This was not a modern ClipboardEvent instance.");
}
}, false);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment