Skip to main content

Copy Text to Clipboard with JavaScript

In this tutorial, we are going to explain how to implement Copy Text to Clipboard functionality with JavaScript in your website. We will use execCommand("copy") JavaScript command to copy content to clipboard.

The Copy text to clipboard is a special feature that allow user’s to copy contents without using any key combination. There are no need to highlight and manually copy text. User’s just need to click button to copy content to clipboard and content copied automatically.

So there are various reasons to prefer copy to clipboard feature into your website instead of manual copy. As in our previous tutorial you learned how to Refresh or Reload Page using JavaScript. Here in this tutorial, we will cover copy to clipboard using JavaScript tutorial with live demo.

Also, read:

So let’s implement Copy Text to Clipboard with JavaScript. The major files are:

  • index.php
  • copyText.js

Step1: Create Input and Copy Button

In index.php file, first we will create an input text and a button to copy input text into clipboard when click button.

<div class="form-group">
  <input type="text" class="form-control" value="This is test text to copy into clipboard!" id="message">
</div>
<button id="copy" class="btn btn-info" data-trigger="click">Copy to clipboard</button>

Step2: Implement Copy to the Clipboard with JavaScript

In copyText.js file, we will implement functionality to copy input text to clipboard. We will implement click event on button click and call function copyText() to copy input text to clipboard. We will also implement tooltip display when content copied to clipboard and hide tooltip after sometime.

$(document).ready(function(){
  $("#copy").click(function(){
    copyText();
	$(this).attr({'data-placement':'bottom','data-original-title':"Copied"}).tooltip('show');
	setTimeout(function(){ 		
	 $(".tooltip").tooltip("hide");		
	}, 2000);
  });
});

We will implement the function copyText() to get the object of text input and implement input text select using object. After input text select, we will call document.execCommand("copy") command to copy selected content to clipboard.

function copyText() {  
  var copyText = $("#message")[0]; 
  copyText.select();  
  document.execCommand("copy");   
}

You may also like:

You can view the live demo from the Demo link and can download the source from the Download link below.
Demo Download