Home >>Javascript Programs >How to copy text to clipboard with JavaScript

How to copy text to clipboard with JavaScript

How to copy text to clipboard with JavaScript

In this article, we will learn how to copy text to clipboard by using JavaScript. Copying content text is one of the quite often in modern website building. It saves the time of visitors by selecting text or hitting ctrl+ c every time for selecting text. User can easily copy some text to clipboard without selecting text.

Let's take an example:

<!DOCTYPE HTML> 
<html> 
	<head> 
		<title> 
			copy text to clipboard with JavaScript 
		</title> 
	</head> 
	<body> 
<!-- The text field -->
<input type="text" value="Welcome to Phptpoint" id="myInput">
<!-- The button used to copy the text -->
<button onclick="myCopy()">Copy text</button>
<script>
function myCopy() {
  /* Get the text field */
  var copyText = document.getElementById("myInput");

  /* Select the text field */
  copyText.select();
  copyText.setSelectionRange(0, 99999); /*For mobile devices*/

  /* Copy the text inside the text field */
  document.execCommand("copy");
}
</script>
	</body> 
</html>		
Output


No Sidebar ads