Skip to content

Instantly share code, notes, and snippets.

@krisleech
Last active June 7, 2022 08:16
Show Gist options
  • Save krisleech/2d57d007cb788ba6f782c3db773b641a to your computer and use it in GitHub Desktop.
Save krisleech/2d57d007cb788ba6f782c3db773b641a to your computer and use it in GitHub Desktop.
3 ways to copy to clipboard in Javascript
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.

@tangbc
Copy link

tangbc commented Jan 14, 2019

It's good, in addition, this code will cause browser activeElement change, if hope prevent it, we can add $('#clipboard').val('readOnly', true) and not use document.getElementById('clipboard').focus().

@thelastfantasy
Copy link

Should add window.getSelection().removeAllRanges(); before window.getSelection().addRange(range);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment