Skip to content

Instantly share code, notes, and snippets.

@rainforest-of-code
Forked from krisleech/clipboard.md
Created June 28, 2018 13:21
Show Gist options
  • Save rainforest-of-code/ab2971125c32d34d167c8c0d4bb2f071 to your computer and use it in GitHub Desktop.
Save rainforest-of-code/ab2971125c32d34d167c8c0d4bb2f071 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.

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