Thursday, April 12, 2012

jquery copy to clipboard

Here i am going to explain copy to clipboard functionality using ZeroClipboard plugin.
Brief introduction of ZeroClipboard
This library is fully compatible with Flash Player 10, which requires that the clipboard copy operation be initiated by a user click event inside the Flash movie. This is achieved by automatically floating the invisible movie on top of a DOM element of your choice. Standard mouse events are even propagated out to your DOM element, so you can still have rollover and mouse down effects.
There are 4 simple steps to get clipboard functionality.
  1. Download latest jquery base and include in your page.
  2. Download ZeroClipboard plugin and include ZeroClipboard.js file in your page.
  3. copy ZeroClipboard.swf file from downloaded list to your file location and change file path in ZeroClipboard.js
    moviePath: 'FILE PATH/ZeroClipboard.swf', // URL to movie
  4. just add below html next to text you want to add clipboard icon
    <span class='copyclipboard'></span>
    Also, put the text you want to copy in any html tag
    Ex for simple text:
    <span>TEXT TO COPY</span><span class='copyclipboard'></span>
    Ex for link:
    <a>LINK TEXT</a><span class='copyclipboard'></span>
  5. Now, add below code
    <script type="text/javascript">
        $(function() {
                var clip = new ZeroClipboard.Client();
                clip.setHandCursor( true );
                clip.addEventListener('complete', function(client, text) {
                    alert("Copied text to clipboard:\n" + text);
    The above code look for all the "copyclipboard" classes and create clipboard object for each occurrence and get the text from previous tag of current instance and set it in the clipboard object.
  6. Finally
         padding-right: 20px;
         background: url('/images/clipboard.png') 100% 50% no-repeat;
Whenever user click on clipboard icon, it will show alert with the copied text. Output look like this:

No comments:

Post a Comment