Home > Enterprise >  The "TEXT COPY" function does not work.. Help me
The "TEXT COPY" function does not work.. Help me

Time:11-28

I have this code that sometimes works and sometimes it doesn't. I am not very involved in these topics, but I need to fix it. Can you help me solve my problem?

this code

function CopyToClipboard(containerid){if(document.selection)
{var range=document.body.createTextRange();range.moveToElementText(document.getElementById(containerid));range.select().createTextRange();document.execCommand("copy");}
else if(window.getSelection){var range=document.createRange();range.selectNode(document.getElementById(containerid));window.getSelection().addRange(range);
document.execCommand("copy");$("#text-3").fadeIn().delay(2000).fadeOut()}}
function myFunction(){var copyText=document.getElementById("myInput");copyText.select();copyText.setSelectionRange(0,99999);document.execCommand("copy");$("#text-2").fadeIn().delay(2000).fadeOut();}

html

<button name="copy text" onclick="CopyToClipboard('div1')"></button>
<div id="div1"><h3>my text</h3><br></div>

<div id="text-2">notif 2</div>
<div id="text-3">notif 3</div>

I am looking for a code for this case that is up-to-date and different browsers do not have problems with this code I will post the code here

CodePudding user response:

try like below,

function copyToClipboard() {
    navigator.clipboard.writeText(document.getElementById('div1').innerText);
    //alert('data copied');
    document.getElementById('messageis').style.display = "block";
    setTimeout(function() {
      document.getElementById('messageis').style.display = "none";
  }, 3000);
  
}
  #messageis
  {
    display: none;
    background: red;
    padding: 10px;  
    position: absolute;
    bottom: 10px;
    left:30%;

  }
<button name="copy text" onclick="copyToClipboard()">Copy</button>
<div><h3  id="div1">my text</h3><br></div>
<div id="messageis">Code Copied</div>

  • Related