0

Edit: I do not try to copy textarea or input value so it is not a duplicate question as suggested.

Can I use copy to clipboard for an element's text value?

Such as I want to copy terra1

<span id="terra-wallet-address">terra1</span>

And jQuery:

  jQuery('#terra-wallet-address').focus();
  jQuery('#terra-wallet-address').select();
  document.execCommand('copy');
  jQuery('.copied').text("Copied to clipboard").show().fadeOut(1200);

I also tried .val() and .text() but did not work.

Thank you.

Ataman
  • 2,530
  • 3
  • 22
  • 34
  • Hello, I am not using any input or textarea. So, no unfortunately it does not answer my question. – Ataman Nov 27 '21 at 18:44
  • 1
    If you don't have an input (or content-editable-div) then what do you think `.focus()` is doing? You can only copy from an `input` (or similar), not from a `span` – freedomn-m Nov 27 '21 at 18:50
  • 1
    Hi Ataman, How much I understood your question you want to copy text inside the element that's it? – beginner_coder Nov 27 '21 at 18:51
  • The linked question provides you a way to generate a `textarea`, add the value you want to copy into that textarea and then copy to clipboard from the (hidden) textarea. There are other answers that have a similar process. – freedomn-m Nov 27 '21 at 18:51

2 Answers2

2

If you don't want to create a temporary textarea, you can programmatically select the text inside the element (with Document.createRange and Range.selectNodeContents), then call execCommand.

Note that you'll need to call execCommand inside an event handler.

var r = document.createRange();
var w = document.getElementById("terra-wallet-address");
r.selectNodeContents(w);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(r);
btn.addEventListener('click', function() {
  document.execCommand('copy');
  jQuery('.copied').text("Copied to clipboard").show().fadeOut(1200);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span id="terra-wallet-address">terra1</span>

<button id="btn">copy</button>
Spectric
  • 30,714
  • 6
  • 20
  • 43
0

Well, you can't focus() an element, but you can use other methods, like create range, and then execute the copy command.

I also made a tiny library that lets you copy inputs, textareas, divs, and any other elements: https://github.com/codingjlu/copyjs

code
  • 5,690
  • 4
  • 17
  • 39