JavaScript copy to clipboard not working

妖精的绣舞 提交于 2019-12-05 01:24:10

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.

Great answer by Intervalia.

Small improvement to it, sometimes the clicked element is not the one you want to copy.
So I suggest you pass the id of the element you want to copy.

<button onClick='copyText("display")'> Copy </button>
<h1 id='display'> Text Sample </h1>

And then, in the first line of your function do

element = document.getElementById(element); 

Not much of a difference but I think it's more useful this way.

select() method is used to select the contents of text fields. it won't work on h1 element.

hi so I looked into it and since you are not using a textInput you cannot just use the .select()function. I borrowed some code from a fellow stack overflow developer Jason on how to highlight an item in javaScript

selecting text in an element akin to highlighting with your mouse.

function selectedText(element)(){

var doc = document,
text = doc.getElementById(element)
range, selection;

if(doc.body.createTextRange){ 
 range = document.body.createTextRange();
 range.moveToElementText(text);
 range.select(); 
}
else if(window.getSelection){
  selection = window.getSelection();
  range = document.createRange();
  range.selectNodeContents(text);
  selection.removeAllRanges();
  selection.addRange(range);   
}

return range;

I then modified it to return the range. and with that all you would have to do is

document.onclick = function(e){
  if(e.target.className === 'click'){

      var copytext = SelectText('display');
      document.execCommand("copy");
      alert("Copied the text: " + copytext);
   }
}

the key part here is that the string passed in to .execCommand() is lower case 'copy'

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!