Sometimes copy to clipboard jquery feature document.execCommand(“copy”); doesn’t work as we want. I got skipped working in some specific browsers or sometimes in specific versions. Then we were again stuck at the same stage we got started to work with the issue. Here is the solution to that problem in this article. We can work with the clipboard.js here. I got personally hands on this and found the results. It is easy to use and comes with many advanced features.
Here are the steps to follow to make this CDN work for you too:
Use any of the CDN here in your page head
tag. If you want to use other versions of this CDN, you can find them here.
<script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.11/clipboard.min.js"></script> or <script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.11/clipboard.js"></script>
Now, you need to instantiate it by passing a DOM selector
new ClipboardJS('.btn');
Now you have to add an data-clipboard-target
attribute to your trigger element. The value you assign to this attribute needs to match another’s element selector to which you want to copy contents to the clipboard.
<!-- Target --> <input id="targetToCopy" value="The content got coppied from here."> <!-- Trigger --> <button class="btn" data-clipboard-target="#targetToCopy"> Copy to clipboard </button>
Additionally, you can define a data-clipboard-action
attribute to specify if you want to either copy
or cut
content. If you omit this attribute, copy
will be used by default.
It has custom events such as success
and error
so that we can use them to implement our custom logic.
var clipboard = new ClipboardJS('.btn'); clipboard.on('success', function(e) { console.info('Action:', e.action); console.info('Text:', e.text); console.info('Trigger:', e.trigger); e.clearSelection(); }); clipboard.on('error', function(e) { console.error('Action:', e.action); console.error('Trigger:', e.trigger); });
You can get more details for advanced usage of the package from here.
To get more knowledge about the JQuery topics, you can check these articles too.