The clipboard helps improving the user-experience by providing easy one-click solutions instead of treadful manual marking and copying. But accessing the "copy-and-paste" functionality via the clipboard API using JavaScript can be annoying. For security reasons: clipboards could be filled with malicious strings as well as varying browser support. I look at you IE.
At the same time, I'm not a big fan of large packages and dependencies for a small functionality. VanillaJS is here my go-to starting point. After comparing and trying a few copy-and-paste snippet solutions, I've found one version working stable and across common browsers. It's adopted from this question and breaks down into two functions:
// From: https://stackoverflow.com/a/33536393
function selectElementContents(el) {
// Copy textarea, pre, div, etc.
if (document.body.createTextRange) {
// Internet Explorer
var textRange = document.body.createTextRange();
textRange.moveToElementText(el);
textRange.select();
textRange.execCommand("Copy");
}
else if (window.getSelection && document.createRange) {
// Non-Internet Explorer
var range = document.createRange();
range.selectNodeContents(el);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
try {
var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
console.log('Copy command was ' + msg);
}
catch (err) {
console.log('Oops, unable to copy');
}
}
}
function attach_copy_and_paste(el, copy_btn) {
copy_btn.onclick = function() {
selectElementContents(el);
};
/**
* Switch the text on the button with changing browser support.
*
* Note:
* document.queryCommandSupported("copy") should return "true"
* on browsers that support copy, but there was a bug in
* Chrome versions 42 to 47 that makes it return "false".
* So in those versions of Chrome feature detection won't work!
*
* @see https://code.google.com/p/chromium/issues/detail?id=476508
*/
if (document.queryCommandSupported("copy") || parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2]) >= 42) {
// Copy works with Internet Explorer 4+, Chrome 42+, Firefox 41+, Opera 29+
copy_btn.value = "Copy to Clipboard";
}
else {
// Select only for Safari and older Chrome, Firefox and Opera
copy_btn.value = "Select All (then press Ctrl + C to Copy)";
}
}
Once these two functions are defined, you can simply attach the copy-and-paste functionality on any clickable element using:
attach_copy_and_paste(
// Element to mark and copy
document.getElementById("content-area"),
// Button to attach the click event to.
document.getElementById("copy-button")
);
Both parameters are DOM elements. The first parameter is defining the element(s) to copy into the clipboard. The second parameter defines the clickable element, here a button, from which the event will be triggered. On click the visible elements (text, images, etc.) are marked and stored in the clipboard.
If you are having issues getting document.execCommand('copy')
to work, you should ensure you are testing the browser support as described above. You can find detailed information about the clipboard API browser support on can I use.
This also nicely integrates any toast-notification system you might want to have too. As I've done integrated it on my new project PastableLists.com. It's a site cutting your work down by providing your ready-to-use copy and paste lists as well as document types such as PDFs, Excel Sheets, etc.
🙏🙏🙏
Since you've made it this far, sharing this article on your favorite social media network would be highly appreciated 💖! For feedback, please ping me on Twitter.
Published