2

I'm trying to use JavaScript to copy text to clipboard. Here is what I've got so far

var copyTextareaBtn = document.querySelector('#copy');

copyTextareaBtn.addEventListener('click', function(event) {
  var copyTextarea = document.getElementById('toCopy');
  copyTextarea.focus();
  copyTextarea.select();

  try {
    var successful = document.execCommand('copy');
    var msg = successful ? 'successful' : 'unsuccessful';
    console.log('Copying text command was ' + msg);
    alert("Link copied!");
  } catch (err) {
    alert("Unable to copy!");
  }
});

I get the error that copyTextarea.select is not a function. Why is that? I'm 100% sure that JavaScript does have a select method.

Human Cyborg Relations
  • 1,202
  • 5
  • 27
  • 52
  • Depends on your environment, What browser are you using and which version is it? – Sgnl Apr 02 '16 at 21:28
  • Here is the compatibility for it from MDN: https://developer.mozilla.org/en-US/docs/Web/API/ClipboardEvent#Browser_compatability As Mr. Alien mentioned(deleted comment now?). If you're not in those environments, using flash is and has been the way to do it. – Sgnl Apr 02 '16 at 21:29
  • I'm using Chrome v49 – Human Cyborg Relations Apr 02 '16 at 21:34
  • [Works just fine for me](https://jsfiddle.net/Siguza/Lhfhzocv/). – Siguza Apr 02 '16 at 21:35
  • You can try https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setSelectionRange#Browser_compatibility. – serverSentinel Apr 02 '16 at 21:36
  • Possible duplicate of [How do I copy to the clipboard in JavaScript?](http://stackoverflow.com/questions/400212/how-do-i-copy-to-the-clipboard-in-javascript) – Conor O'Brien Apr 02 '16 at 22:17

1 Answers1

5

Please make sure the element with id as "toCopy" is of type textarea

Shashi Kant
  • 51
  • 1
  • 4