Home > Net >  How to copy to clipboard in jquery with dynamically added ids?
How to copy to clipboard in jquery with dynamically added ids?

Time:11-17

I have a series of divs to which I add an incremental id dynamically. I also have a tootip that appears when I hover over each div, to inform the user that they can copy the text

i=0;
$('.custom-text--result, .token').each(function(){
  $(this).attr('id', 'copy-' i '');
  $(this).append('<span  onclick="copy(copy-' i ')">Copy</span>');      
   i  ;
 });

When I inspect the code, I have my id on my div, and in the onclick of the tooltip, I have the corresponding id

<div  id="copy-3">My text blablalba<span  onclick="copy(" #copy-3")"="">Copy text</span></div>

Now, if I do something like :

function copy(element) {
        var $temp = $("<input>");
        $("body").append($temp);
        $temp.val($(element).text()).select();
        document.execCommand("copy");
        $temp.remove();
    }

It doen't work..So What is wrong here ? I also added the id manually in the code, it does not work.

Moreover, I read that the exec.commant function was not ideal and that it was better to use the Clipboard API..I can't find any example in jquery. All my code is in jquery, I would like to find a solution in jquery.

CodePudding user response:

I propose you a pure JS solution because clipboard used that like:

function copy(div) {
  navigator.clipboard.writeText(div.innerText).then(
    function() {
      //if function work done work
      alert('copy done by clipboard');
    },
    function() {
      //if fail cliboard use execCommand
      const inputTemp = document.createElement("input");
      inputTemp.setAttribute("value", div.innerText);
      document.body.appendChild(inputTemp);
      inputTemp.select();
      document.execCommand("copy");
      document.body.removeChild(inputTemp);
      alert('copy done by execCommand');
    }
  )
}
<div  onclick="copy(this)">My text blablalbda</div>

  • Related