-2
var delayBecauseFirebase = 1000;
setTimeout(function() {
      var buttonShowJ = document.getElementById("buttonShow");
      var messagesInJ = document.getElementById("messagesIn");
      if(buttonShowJ)
      {
        buttonShowJ.addEventListener("click",function(){
          var info = messagesInJ.innerHTML.replace(`<button id="buttonShow">Copy</button>`,"");
          info.select(); \\**(!HERE, because that doesnt works)**
          document.execCommand("copy");
        });
      }else{
        console.log("error");
      }
}, delayBecauseFirebase);

I want to select the "text" inside info to can do

document.execCommand("copy");

But i dont know how can i use select for that var.

j08691
  • 190,436
  • 28
  • 232
  • 252
  • Did you try innerText? https://developer.mozilla.org/es/docs/Web/API/HTMLElement/innerText – German Faller Jan 06 '21 at 17:48
  • 1
    Does this answer your question? [How do I copy to the clipboard in JavaScript?](https://stackoverflow.com/questions/400212/how-do-i-copy-to-the-clipboard-in-javascript) – imvain2 Jan 06 '21 at 17:50
  • @GermanFaller yes, but with innerText "Copy" doesn't disappear. But thx. – Mitsworth SCZD Jan 06 '21 at 17:52
  • Your problem is that variable info is a string, not an element. Select is not a method of a string. Instead, you probably should consider using Clipboard.writeText(info), or put info in an html element that you select. – Russ Jan 06 '21 at 17:53
  • so, why not having 3 elements ```
    ``` easier to get just the text
    – German Faller Jan 06 '21 at 17:54

1 Answers1

0

I think this could work

  • In the HTML
<div class="container">
  <div id="messagesIn">
    ...Some Text
  </div>
  <button id="buttonShow">Copy</button>
</div>
  • Then in the code
var delayBecauseFirebase = 1000;

function copyText(){
    //Select your text
    var range = document.createRange();
    range.selectNode(document.getElementById("messagesIn"));
    window.getSelection().removeAllRanges();
    window.getSelection().addRange(range);

    //Call copy command
    document.execCommand("copy");
}

function addClickListener() {
    var buttonShowJ = document.getElementById("buttonShow");
    if(buttonShowJ){
        buttonShowJ.addEventListener("click", copyText);
    }else{
        console.error("Copy button not found");
    }
}

setTimeout(addClickListener, delayBecauseFirebase);

Recomended post:

German Faller
  • 440
  • 3
  • 12