Friday, 21 November 2014

Copy Text to Clipboard Using JavaScript

In a recent web project, I needed to create a button that would copy text from textbox onto the user's clipboard. The obvious approach is to use jQuery or JavaScript to trigger onclick() event of the button and copy text to clipboard. It sounds easy and convenient and should be achieved with few lines of code but it is not. 

During the code generation process, I found that JavaScript copy to clipboard was not available because of security which also meant that jQuery would not be able to copy the text to clipboard. Actually you can still use JavaScript, but it prompts the user to allow the application to copy text on clipboard, and hence voids the whole idea of providing user convenience. This means I had to find another way around, but I still wanted to use JavaScript.

After spending some time on Google search, luckily I found a jQuery library called ZeroClipboard. This library provides an easy way to copy text to the clipboard using a pinch of Invisible Adobe Flash movie, and touch of JavaScript. Flash can access your computer's clipboard because you have to install flash and agree to the security settings. We can use JavaScript as an interface to flash so we can start this off with a click event on a button.

Note: Before we continue to tutorial/demo there are some things to consider. Due to security issues, flash cannot access the clipboard unless the action originates from a click (or user interaction) with a flash object.
You cannot copy paste code in html file and open it with browser and expect ZeroClipboard to run. You will not able to click button. So you have to host the HTML page in your local IIS website e.g http://localhost:8080/zeroclipbaord.html to make it work.

How to Use ZeroClipboard?
You can download ZeroClipboard from http://zeroclipboard.org/ or use it the from the public content distribution network (CDN) cdnjs: http://cdnjs.com/libraries/zeroclipboard
To start using ZeroClipboard simply include following JavaScript file in your page.

<script src="//cdnjs.cloudflare.com/ajax/libs/zeroclipboard/2.1.6/ZeroClipboard.js" type="text/javascript"></script>

The following example shows you two common ways to copy text on clipboard
1 - Copy the text by Setting Target Area
2 - Copy the text with a HTML data-attribute

1- Copy the Text by Setting Target Area
This method allows you to define a HTML element that you can get the text from to copy. The value that it will use can either be the value of the element, the innerHTML or the textContent. This works off a data attribute of data-clipboard-target with a value of the ID of element you want to copy.

<button data-clipboard-target="clipboard-text" id="btn-To-Copy">Copy To Clipboard</button>

<textarea cols="20" id="clipboard-text" name="clipboard-text" onclick="this.select();" rows="20">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus mattis lacus nibh, ac sollicitudin sapien accumsan in. Mauris euismod posuere tellus luctus sodales.
Fusce a consectetur massa, non tincidunt mauris. Phasellus a rutrum libero. Praesent tempus urna et nisi aliquam convallis. Fusce porttitor justo condimentum orcieuismod, pulvinar congue magna vestibulum.
Sed gravida eleifend justo, id ultrices tellus porttitor nec. Nam porttitor gravida tempor. In libero ante, euismod ac fermentum nec, gravida ut dolor. Nullam a pulvinar ligula.
</textarea>

<div id="responsecopy" style="display: none; position: relative;">
</div>

We setup the ZeroClipboard client to be attached to the btn-To-Copy button. ZeroClipboard will search for the data-clipboard-target attribute and use this value to get the text to copy on clipboard.

2- Copy the Text with a HTML data-attribute
You provide button with the text and use Html data-attribute (data-clipboard-text) to tell ZeroClipboard to copy value from button to Clipboard.

<button data-clipboard-text="This text will be copied to Clipboard" id="btn-To-Copy" name="btn-To-Copy">Copy To Clipboard</button>
<div id="responsecopy" style="display: none; position: relative;">
</div>

Both above examples use the same following JavaScript

<script type="text/javascript">
        var client = new ZeroClipboard(document.getElementByIdid("btn-To-Copy"));

        client.on("ready", function (readyEvent) {
            // alert( "ZeroClipboard SWF is ready!" );

            client.on("aftercopy", function (event) {
                // `this` === `client`
                // `event.target` === the element that was clicked

                var msgBox = document.getElementById("responsecopy");
                msgBox.innerHTML = "Copied '" + event.data["text/plain"] + "' to clipboard";
                msgBox.style.display = 'block';

               //alert("Copied text to clipboard: " + event.data["text/plain"]);
           });
        });
    </script>

ZeroClipboard uses a Flash movie, and so your users obviously need to have Adobe Flash installed. You do need to handle the case where it is not present.

ZeroClipboard Documentation
Need to learn more how to Use ZeroClipboard? You can go though the latest version documentation of ZeroClipboard on their Github Project page.


/Adnan

0 comments :

Post a comment