Skip to content

Instantly share code, notes, and snippets.

@ypetya
Last active July 27, 2022 01:59
Show Gist options
  • Select an option

  • Save ypetya/f12b1569d4f910f750c5 to your computer and use it in GitHub Desktop.

Select an option

Save ypetya/f12b1569d4f910f750c5 to your computer and use it in GitHub Desktop.
Copy to Clipboard javascript

Copy to clipboard

This is a small multibrowser copy to clipboard component

(function createClipboardAPI(document){
/**
* multi browser clipboard copy - [email protected]
* */
document.ClipboardApi = new ClipboardApi();
function ClipboardApi() {
this.setCopyButton= function(selector, copyAreaSelector) {
var copyBtn = document.querySelector(selector);
copyBtn.addEventListener('click', function(event) {
console.info(event);
eventDispatcher( copyAreaSelector, 'copy');
});
}
}
/***
* This function uses multiple methods for copying data to clipboard
* 1. document.execCommand('copy') can be supported only for user initiated contexts
* - that means we can only determine it on the fly
* - d3 eventDispatch is not working this way
* 2. ClipboardEvent constructor is only defined for Firefox (see MDN)
* - for FF, d3 selector uses input's value property instead of selection.text()
* */
function eventDispatcher( inputSelector, action) {
var clipboardEl = document.querySelector(inputSelector);
// Chrome
if(document.queryCommandSupported && document.queryCommandSupported(action)) {
clipboardEl.select();
document.execCommand(action);
} else {
// FF
var event = new ClipboardEvent(action)
var text = clipboardEl.value;
event.clipboardData.setData('text/plain', text);
event.preventDefault();
document.dispatchEvent(event);
}
};
}(window.document));
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Copy to clipboard</title>
<script src="clipboard.js"></script>
<style>
body {
text-align: center;
height:100%;
}
.center {
margin-top: 10%;
}
</style>
</head>
<body>
<h1>Multibrowser clipboard copy</h1>
<div class="center">
<textarea class="selection" placeholder="enter text"></textarea>
<button class="copy">Copy</button>
</div>
<script>
document.ClipboardApi.setCopyButton('.copy','.selection');
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment