JavaScript: Copy and Paste to the Clipboard

The clipboard can help build an improved user-experience by providing easy one-click solutions to problems. But accessing the "copy-and-paste" functionality via the clipboard 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:
function selectElementContents(el) {
// Copy textarea, pre, div, etc.
if (document.body.createTextRange) {
// Internet Explorer
var textRange = document.body.createTextRange();
else if (window.getSelection && document.createRange) {
// Non-Internet Explorer
var range = document.createRange();
var sel = window.getSelection();
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() {

* 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 does not work!
* @see

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:

// Element to mark and copy

// Button to attach the click event to.

Both parameters are DOM elements. The first parameter is defining the element(s) to copy-and-paste. 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.

This also nicely integrates any toast-notification system you might want to have too.


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.