if(document.queryCommandSupported('copy')) {
if(text=='') { text = ' '; } // empty inputs do not get selected
// copy text to off-screen input
$('#clipboard').val(text);
// 1.) does copy empty inputs, but adds newline before content
var range = document.createRange();
range.selectNode(document.querySelector('#clipboard'));
window.getSelection().addRange(range);
// 2.) doesn't copy empty inputs
document.querySelector('#clipboard').select();
// 3.) doesn't copy empty inputs
document.getElementById('clipboard').focus();
document.execCommand('SelectAll');
// do the copy
document.execCommand('Copy');
};
Requires input#clipboard
in the DOM, this could be static or dynamically created. It cannot be display:none
but it can be off screen using relative
position left: -9999px
.
The copy command can only be called from certain events, such as click.