Tuesday, December 31, 2019

Copy HTML into the clipboard from the DOM with JavaScript.

var textArea = document.createElement("textarea");
textArea.value = document.getElementById("touchMe").innerHTML;
textArea.style.position = "fixed";
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
document.execCommand('copy');
document.body.removeChild(textArea);

 
 

Honestly, something like this might be a little bit better:

if (!copying) {
   copying = true;
   var textArea = document.createElement("textarea");
   textArea.value = document.getElementById("touchMe").innerHTML;
   textArea.style.position = "fixed";
   document.body.appendChild(textArea);
   textArea.focus();
   textArea.select();
   document.execCommand('copy');
   var cleanUp = function() {
   try {
      document.body.removeChild(textArea);
   } catch (error) {
      
   }    clearInterval(interval);
   copying = false;
   };
   var interval = setInterval(cleanUp, 6000);
}

No comments:

Post a Comment