Ishwar Kurwade
Ishwar Kurwade

Reputation: 33

How to copy to clipboard from a input box?

I am building a website in html, php, javascript, etc. In that I want to add a specific button, after button clicked the words from input box should get copied into clipboard. I have tried by using Zeroclipboard but I could not.

I have used the following code and added jquery.zclip.js and jquery-1.8.0.min.js to the same directory. Welcome for any suggestions.

<head>    
    <script type="text/javascript" src="jquery-1.8.0.min.js"></script> 
    <script src="jquery.zclip.js"></script> 
    <style> 
        #dynamic { font-size: 15px; height: 28px; width: 357px; } 
    </style> 
    <script> 
        $(document).ready(function(){ 
            $("a#copy-dynamic").zclip({ 
                      path:"ZeroClipboard.swf", 
                      copy:function(){return $("input#dynamic").val();} 
            }); 
        }); 
    </script> 
</head>
<body> 
    <input type="text" id="dynamic" value="Copy me !!" /> 
    <a href="#copy" id="copy-dynamic">Copy Now</a> 
</body>

Upvotes: 2

Views: 577

Answers (1)

Katharine Osborne
Katharine Osborne

Reputation: 7031

I recently had to deal with ZeroClipboard; the docs are not the greatest.

First you need to add the source script to the head of your html document:

<script src="https://cdnjs.cloudflare.com/ajax/libs/zeroclipboard/2.2.0/ZeroClipboard.js"></script>

I used a CDN, but I'm sure it works fine if you have a local copy.

Then in your javascript, in global scope:

ZeroClipboard.config( { swfPath: "whateverpath/ZeroClipboard.swf" } );

Then you need to bind the swf to the element you want to use to trigger copying:

var copyButton = document.getElementById('thingThatCopies');
var copyclient = new ZeroClipboard(copyButton); //can be array

It should work from there, but in case you want to add a user notification, there are some events you can work with:

copyclient.on("ready", function(readyEvent) {
    //is ready
    copyclient.setText(window.location.href);
    //in this instance, set the text to copy to the url of the current page. You can set it to anything with this function
    copyclient.on("aftercopy", function(event) {
        //copied
        //this is the place to add a user notification
    }
}

Hopefully that gives you enough of a start to adapt it to your project.

Upvotes: 1

Related Questions