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.
CodePudding user response:
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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
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