0

It's a fairly common question, but I haven't found a simple answer to it. Since I can't write the answers, I'll write a question-answer. This is the first post on stackoverflow, please do not judge strictly :)

1 Answers1

0
<span class="contacts-link" id="CopyMail" data-value="test@stackoverflow.com"></span>
<span class="link" onClick="copyClipboard()">Copy Hidden Text</span>
<style>
  .contacts-link {
    display: none;
  }
  .link {
    background: #000000;
    color: white;
    padding: 25px;
    font-size: 32px;
    cursor: pointer;
  }
  .link:hover {
    background-color: #ff5722;
  }
  .link:active {
    padding: 30px;
  }
</style>

<script>
  function copyClipboard() {
    const str = document.getElementById("CopyMail").getAttribute("data-value");
    const element = document.createElement("textarea");
    element.value = str;
    element.setAttribute("readonly", "");
    element.style.position = "absolute";
    element.style.left = "-9999px";
    document.body.appendChild(element);
    element.select();
    document.execCommand("copy");
    document.body.removeChild(element);
  }
</script>