Copy to clipboard example

Copy text to clipboard on one click

by dshilkret

HTML

<input type="text" onclick="copyText()" readonly id="previewLinkBox" class="preview-link-box" value = "Copy this Content"> 
<button type="button" onclick="copyText()">Copy</button>
<input type="text" class="preview-link-box">

CSS

.preview-link-box{
  border: 1px solid #ccc;
  width: 300px;
  height: 30px;
  boder-radius: 10px;
  margin: 20px auto;
  padding: 10px;
}

JavaScript

function copyText(){		
    var linkBox = $("#previewLinkBox");
		linkBox.focus();
		linkBox.select();
		try {
		    var successful = document.execCommand('copy');
		    var msg = successful ? 'successful' : 'unsuccessful';
		    console.log('Copying text command was ' + msg);
		} catch (err) {
			console.log('Oops, unable to copy');
		}
}