Michael Riva
0
Q:

copy text to clipboard javascript

function copyToClipboard(text) {
   const elem = document.createElement('textarea');
   elem.value = text;
   document.body.appendChild(elem);
   elem.select();
   document.execCommand('copy');
   document.body.removeChild(elem);
}
10
function copy() {
  var copyText = document.querySelector("#input");
  copyText.select();
  document.execCommand("copy");
}

document.querySelector("#copy").addEventListener("click", copy);
8
function copyToClipboard(text) {
  var input = document.body.appendChild(document.createElement("input"));
  input.value = text;
  input.focus();
  input.select();
  document.execCommand('copy');
  input.parentNode.removeChild(input);
}
1
// Since Async Clipboard API is not supported for all browser!
function copyTextToClipboard(text) {
  var textArea = document.createElement("textarea");
  textArea.value = text
  document.body.appendChild(textArea);
  textArea.focus();
  textArea.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');
  }

  document.body.removeChild(textArea);
}
3
<html>
  <input type="text" value="Hello world"(Can be of your choice) id="myInput"(id is the name of the text, you can change it later)
<button onclick="Hello()">Copy Text</button>

<script>
  function Hello() {
  var copyText = document.getElementById('myInput')
  copyText.select();
  document.execCommand('copy')
  console.log('Copied Text')
}
</script>
1
$(document).ready(function(){
	$("#ewefmwefmp").click(function(){
    //alert()
      var copyText = document.getElementById("myInput");
      copyText.select();
      copyText.setSelectionRange(0, 99999)
      document.execCommand("copy");
      alert("Copied the text: " + copyText.value);
    
    });
});
2
const el = document.createElement('textarea');
el.value = str;	//str is your string to copy
document.body.appendChild(el);
el.select();
document.execCommand('copy');	// Copy command
document.body.removeChild(el);
1
var copyTextarea = document.getElementById("someTextAreaToCopy");
copyTextarea.select(); //select the text area
document.execCommand("copy"); //copy to clipboard
3

  function myFunction() {
  /* 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");

  
  /* Alert the copied text */
  
  alert("Copied the text: " + copyText.value);
} 
1
<button id="demo" onclick="copyToClipboard(document.getElementById('demo').innerHTML)">Copy</button>

<script>
  function copyToClipboard(text) {
    window.prompt("Copy to clipboard: Ctrl+C, Enter", text);
  }
</script>
0

New to Communities?

Join the community