JavaScript copy to clipboard not working

user7570296 picture user7570296 · Dec 21, 2017 · Viewed 29.3k times · Source

I have a function in my script that gives me an error. The function purpose is to copy text from static panel(not textbox or input) with onClick event.

Uncaught TypeError: copyText.select is not a function

The thing i want is to make the user able to click the text and it's get copied to his clipboard.

Maybe you can offer better function that works?

https://codepen.io/abooo/pen/jYMMMN?editors=1010

function myFunction() {
  var copyText = document.getElementById("display");
  copyText.select();
  document.execCommand("Copy");
  alert("Copied the text: " + copyText.value);
}

From w3schools

Answer

Intervalia picture Intervalia · Dec 21, 2017

This will allow you to copy the text of an element. Though I have not tested it with complicated layout.

If you want to use this then remove the alerts and provide a better way to let the user know the content was copied.

SAFARI: This does not work on Safari before version 10.0. But as of Safari 10.0 this now works.

function copyText(element) {
  var range, selection, worked;

  if (document.body.createTextRange) {
    range = document.body.createTextRange();
    range.moveToElementText(element);
    range.select();
  } else if (window.getSelection) {
    selection = window.getSelection();        
    range = document.createRange();
    range.selectNodeContents(element);
    selection.removeAllRanges();
    selection.addRange(range);
  }
  
  try {
    document.execCommand('copy');
    alert('text copied');
  }
  catch (err) {
    alert('unable to copy text');
  }
}
<h1 id='display' onClick='copyText(this)'>Text Sample</h1>

If you want to use this on an <input> or <textarea> element then let me know the code is different.

The try/catch is for older versions of Safari that would throw an exception. So if you don't plan to support Safari before version 10.0 then you can remove it.