Sunday, January 7, 2018

Copy Text to Clipboard Using Javascript

This post explains how to copy text to the clipboard with JavaScript. To copy text to clipboard here we are using document.execCommand("copy")  method. Nowadays it is supported by most of the browsers.

Browsers support
To keep it simple, most of the modern browsers are supported, except Safari.
Chrome >   43.0.2356
Firefox  >= 41.0
Opera   >= 30
IE          >= 9
Safari  is Not supported

Example :1 Copy text to clipboard from textarea ]

In this example we are copying the text from the textarea field to clipboard using javascript with help of copyToClipboard function.
Lets see the complete source code.
<html>
<head>
<script>
function copyToClipboard() {
  var copyText = document.getElementById("myInput");
  copyText.select();
  document.execCommand("Copy");
  
}
</script>
</head>
<body style="width:500px;margin:80px auto;">
<textarea id="myInput" rows="4" cols="50">
Welcome to www.skptricks.com. In This tutorial how to copy text to the clipboard with JavaScript.

</textarea>
</body>
<br>
<button onclick="copyToClipboard()">Copy text</button>

</html>

Click on the button to copy the text from the textarea field. Try to paste the text (e.g. ctrl+v) afterwards in a different window, to see the effect.

Example :2 Copy text to clipboard from div tag ]

In this example we are copying the text from div tag to clipboad using javascript with help of copyToClipboard function.
lets see the complete example to build more understanding.
<html>
<head>
<script>
function copyToClipboard() {

  // Create a new textarea element and give it id='t'
  let textarea = document.createElement('textarea')
  textarea.id = 't'
  // Optional step to make less noise on the page, if any!
  textarea.style.height = 0
  // Now append it to your page somewhere, I chose <body>
  document.body.appendChild(textarea)
  // Give our textarea a value of whatever inside the div of id=containerid
  textarea.value = document.getElementById("myInput").innerText
  // Now copy whatever inside the textarea to clipboard
  let selector = document.querySelector('#t')
  selector.select()
  document.execCommand('copy')
  // Remove the textarea
  document.body.removeChild(textarea) 
}

</script>
</head>
<body style="width:500px;margin:80px auto;">
<div id="myInput" style="background-color:yellow;padding:10px;" >
Welcome to www.skptricks.com. In This tutorial how to copy text to the clipboard with JavaScript.

</div>
</body>
<br>
<button id="my_button" onclick="copyToClipboard()">Copy text</button>

</html>

Click on the button to copy the text from the div area. Try to paste the text (e.g. ctrl+v) afterwards in a different window, to see the effect.

Download Link :
https://github.com/skptricks/php-Tutorials/tree/master/Copy%20Text%20to%20Clipboard%20Using%20Javascript

Video Link :


Please do comments in case of any queries and questions.

No comments:

Post a Comment