How to create copy to clipboard in JavaScript?

Javascript, Tools

Copy to Clipboard is a feature in which we temporarily stores the data(text, images etc) to clipboard(holding place on device). And the copied data remains until we copy the other data. And We are using the JavaScript for different types like creating web page, creating hybrid mobile apps, developing server applications etc. In our applications sometimes we need to add a feature copy to clipboard for ease of application. So, here we will create copy to clipboard in JavaScript.

Step 1 : Create a Button and Textarea Field(Between <body> </body> tag)

<button onclick="copyText()">Copy Text</button>
<textarea id="textField">
    	This is the text which needs to be copy.
</textarea>

Step 2 : Create Function copyText and add this code before closing body tag( </body>) in footer.

<script>
function copyText(e){
	alert('Text Copied Successfully!');

	var copyText = document.getElementById("textField");

	copyText.select();
	
	document.execCommand("copy");
}
</script>

In the above code we selected the text which needs to be copy and used the execCommand to create copy to clipboard in JavaScript.

Read For MoreĀ JavaScript Tutorials and Code.

If you like this, share this.

Follow us on FacebookTwitterTumblrLinkedIn.