0
var $temp = $("<input>");
$("body").append($temp);
$temp.val('123').select();
document.execCommand("copy");
$temp.remove();

What is wrong with this code? It should be correct

Doesn't work at all for me.

I have read many threads here and this seems to work for others.

I have no Idea why this doesn't work for me. In console I nothing.

Krystian Polska
  • 1,286
  • 3
  • 15
  • 27

1 Answers1

2

Reading the answers to this question:

All document.execCommand('copy') calls must take place as a direct result of a user action, e.g. click event handler. This is a measure to prevent messing with the users clipboard when they don't expect it.

The example:

function copyToClipBoard(txt) {
    try {
        var $temp = $("<input>");
        $("body").append($temp);
        $temp.val(txt).select();
        var retVal = document.execCommand("copy");
        console.log('Copy to clipboard returns: ' + retVal);
        $temp.remove();
    } catch (err) {
        console.log('Error while copying to clipboard: ' + err);
    }
}

$('button').on('click', function (e) {
    copyToClipBoard('123');
});


copyToClipBoard('123');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<div style="display:inline-block;">
    <button style="vertical-align:top;">Copy To ClipBoard</button>
    <textarea class="js-test-textarea" cols="35" rows="4">Try pasting into here to see what you have on your clipboard:
  </textarea>
</div>
gaetanoM
  • 41,594
  • 6
  • 42
  • 61