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:
function selectElementContents(el) {
if (document.body.createTextRange) {
var textRange = document.body.createTextRange();
textRange.moveToElementText(el);
textRange.select();
textRange.execCommand("Copy");
}
else if (window.getSelection && document.createRange) {
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);
};
if (document.queryCommandSupported("copy") || parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2]) >= 42) {
copy_btn.value = "Copy to Clipboard";
}
else {
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(
document.getElementById("content-area"),
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