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?
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!
Most helpful comment
@godoffrags Or you can do like this:
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.