Copy to clipboard

Copy to clipboard of the value of an invisible input element

by Ben Clayton

HTML

<div class="wrapper">

<div class="clicktocopy">Copy Link</div><input class="copylink" onclick="copyToClipboard(this);" value="Mouse"/>
</div>
<br><br>
https://stackoverflow.com/questions/22581345/click-button-copy-to-clipboard-using-jquery

CSS

.wrapper {
  width: 80px;
  display: block;
}

.copylink {
  display: block;
  width: 100px;
  height: 20px;
  color: black;
  cursor: pointer;
  opacity: 0;
}

.clicktocopy {
  position: absolute;
  width: 100px;
  height: 20px;
  pointer-events: none;
}

JavaScript

function copyToClipboard(elem) {
	  // create hidden text element, if it doesn't already exist

		var target = elem;
    target.focus();
    target.setSelectionRange(0, target.value.length);
    
    // copy the selection
    var succeed;
    try {
    	  succeed = document.execCommand("copy");
    } catch(e) {
        succeed = false;
    }
    // restore original focus
		alert("Copied");
    return succeed;
}