Clipboard.js: copy to clipboard only via JavaScript and no DOM Element need?

Created on 13 Mar 2017  路  4Comments  路  Source: zenorocha/clipboard.js

Hi,

is it possible to copy text to clipboard only use Javascript?
There is no DOM element for use!

Example:
<script> Clipboard.toClipboard('my Text'); </script>
or something?

Most helpful comment

@godoffrags Or you can do like this:

    function clipboard(text, event) {
        const cb = new Clipboard('.null', {
            text: () => text
        });

        cb.on('success', function(e) {
            console.log(e);
            cb.off('error');
            cb.off('success');
        });

        cb.on('error', function(e) {
            console.log(e);
            cb.off('error');
            cb.off('success');
        });

        cb.onClick(event);
    }

In this way, you don't need to bind clipboard with any DOM element. This is useful if you want to keep clipboard separated from your code logic / markup. You can even use it with angularjs / ng-click.

All 4 comments

You could use clipboard-action directly but the browser requires a click event for security.

import ClipboardAction from 'clipboard/lib/clipboard-action';

const elementToCopy = document.querySelector('.some-element');
elementToCopy.addEventListener('click', (e) => {
  const clipboardAction = new ClipboardAction({
    action: 'copy',
    target: elementToCopy ,
    text: elementToCopy.textContent,
    trigger: e,
    emitter: { emit: () => {} },
  });

  clipboardAction.destroy();
});

@godoffrags Or you can do like this:

    function clipboard(text, event) {
        const cb = new Clipboard('.null', {
            text: () => text
        });

        cb.on('success', function(e) {
            console.log(e);
            cb.off('error');
            cb.off('success');
        });

        cb.on('error', function(e) {
            console.log(e);
            cb.off('error');
            cb.off('success');
        });

        cb.onClick(event);
    }

In this way, you don't need to bind clipboard with any DOM element. This is useful if you want to keep clipboard separated from your code logic / markup. You can even use it with angularjs / ng-click.

Hey guys, I added a proposal for this feature. Can you check #518?

Thanks!

Was this page helpful?
0 / 5 - 0 ratings