0

I've been trying to copy HTML <div> to clipboard with JavaScript.
I want to copy the entire div and paste it as an email format.

<button class="btn-primary copyToClipboard">Copy Text</button>
<br /><br /><br /><br />
<div id ="emailContent">
  <header style="text-align: center; font-size: 24px;background: #ccc;padding: 10px;width: 100%; box-sizing: border-box">Header Text</header>
  <p>This is a Demo Text to Copy and Paste the Content. Please click the link below to activate your account</p>
  <a href="#" style="border: 1px solid #4d4d4d; padding: 7px 15px; color: #4d4d4d;text-decoration: none">Click Here</a>
</div>
var copyToClip = document.getElementsByClassName("copyToClipboard")[0];

copyToClip.onclick = function (str) {
  function listener(e) {
    e.clipboardData.setData("text/html", str);
    e.clipboardData.setData("text/plain", str);
    e.preventDefault();
  }
  var txtValue = document.getElementById("emailContent");
  document.addEventListener("copy", listener);
  document.execCommand("copy");
  document.removeEventListener("copy", listener);
}
Azametzin
  • 4,342
  • 12
  • 22
  • 38
tkamath99
  • 391
  • 3
  • 17
  • 4
    You should explaing what is that is not working (attach some error logs) – Francisco Hanna May 07 '19 at 07:12
  • 5
    Possible duplicate of [How do I copy to the clipboard in JavaScript?](https://stackoverflow.com/questions/400212/how-do-i-copy-to-the-clipboard-in-javascript) – Wendelin May 07 '19 at 07:14
  • You're putting the wrong thing into the clipboard, namely the mouse event. Fixed: https://jsfiddle.net/khrismuc/5bn4vf3m/ – Chris G May 07 '19 at 07:20
  • @ChrisG Thanks! I have set a specific width to the div. But when i paste it in Outlook mail, it is always taking the 100% width. Any solution to this ? – tkamath99 May 07 '19 at 08:04
  • I have updated my fiddle. – Chris G May 07 '19 at 08:07

0 Answers0