Easy way to copy to clipboard for vanilla Javascript

Here is a small script that I put together in order to create a copy to clipboard button. It works in all modern browsers. I created this to be used on my json to xml converter. I needed an easy way to copy to clipboard instead of marking an immense amount of XML or JSON and hit ctrl + V. This script is vanilla javascript and does not require any third party library (like Angular, React or Jquery). Below is my solution to the problem.

In order to use this, add a copy-to-clipboard attribute to the button you wish to use for the copy function. The value for this attribute should be a selector for the textarea you wish to copy from. I have created an example below:

<textarea class="copy-to-clipboard-xml"></textarea>
<button copy-to-clipboard=".copy-to-clipboard-xml">Copy to clipboard</button>

The script which does the actual event binding and binding the copy to clipboard event is below. It is a very small script:


    window.copyToClipboard = window.copyToClipboard || {};

    window.copyToClipboard.bindEvents = function () {
        var bindCopyToClipboardEvent = function (element, copyToSelector) {
            var textarea = window.document.querySelector(copyToSelector);
            element.addEventListener('click', function () {

                try {
                } catch (err) {
                    console.log('oops - failed to copy to clipboard!');

        var copyToClipboardButtons = window.document.querySelectorAll('[copy-to-clipboard]');
        for (var i = 0; i < copyToClipboardButtons.length; i++) {
            var button = copyToClipboardButtons[i];
            var copyToSelector = button.getAttribute('copy-to-clipboard');
            bindCopyToClipboardEvent(button, copyToSelector);

I have added a small function to bind the copy to clipboard events. This can be added to the bottom of the above script if you wish to trigger it immediately. You bind the events using the following javascript:



Here is a small demo of how it works, input your text below and copy it to the clipboard using the button.

Found this useful? Please let me know in the comments down below!