Easy way to copy to clipboard for vanilla javascript

Here is a small script that I put together in order to create a copy from 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, Ember 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 and example below:

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

I have added a small function to bind the events. This can be added to the actual script (at the bottom of this page) if you wish to hide the binding. However I like to make it explicit when I bind my events - except if I use a javascript framework of course.

window.copyToClipboard.bindEvents();

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

(function(){

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

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

                try {
                    document.execCommand('copy');
                } 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);
        }
    };

}());

Demo

Here is a small demo of how it works. Input text below and copy it to the clipboard!

Found this useful? Let me know!