0

I'm trying to copy an anchor element (title) using onclick. This fires but doesn't copy the value. Any thoughts?

I know it's very rudimentary but, well, that's me.

<a id="myAnchor" onclick="myFunction()" title="smarty@pants.com" href="#">smarty@pants.com</a>

<script>
  function myFunction() {
    var copyText = document.getElementById("myAnchor").title;
    document.execCommand("Copy");
    alert("Copied the text: " + copyText.value);
  }
</script>
RobC
  • 22,977
  • 20
  • 73
  • 80
mr.smith
  • 1
  • 1

2 Answers2

2

I would do it differently, but since you want to use execCommand("Copy"), one way is to create a "mock" input element inside your click handler and select it:

function myFunction() {
  var copyText = document.getElementById("myAnchor").title;
  var mockInput = document.createElement("input");
  document.body.appendChild(mockInput);
  mockInput.type = "text";
  mockInput.value = copyText;
  mockInput.style.opacity = 0;
  mockInput.style.position = "absolute";
  mockInput.style.top = "0px";
  mockInput.style.left = "0px";
  mockInput.select();
  document.execCommand("Copy");
  alert("Copied the text: " + copyText.value);
  mockInput.parentNode.removeChild(mockInput);
}

Now you "copied" to clipboard

ibrahim tanyalcin
  • 5,643
  • 3
  • 16
  • 22
1

JsFiddle: https://jsfiddle.net/phj1wyqj/

HTML:

<a id="myAnchor" title="smarty@pants.com" href="#">smarty@pants.com</a>

JS Code:

function myFunction() {
  var copyText = document.getElementById("myAnchor").title;
  document.addEventListener('copy', function(event) {
    event.clipboardData.setData('text/plain', copyText);
    event.preventDefault();
    document.removeEventListener('copy', handler, true);
  }, true);
  document.execCommand('copy');
  alert("Copied: " + copyText);
}
document.getElementById('myAnchor').addEventListener('click', myFunction);

Ref: StackOverflow

Alvin
  • 290
  • 5
  • 25
  • **event.clipboardData.setData** [link](https://developer.mozilla.org/en-US/docs/Web/API/ClipboardEvent/clipboardData) **document.execCommand('copy');** [link](https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand) – Alvin Apr 19 '18 at 17:48
  • Thank you so much :) –  Mar 31 '20 at 18:02