How can I get a simple ZeroClipboard copy-to-clipboard setup working within jQuery on jsFiddle on a single click?

Ryan picture Ryan · Mar 19, 2014 · Viewed 8.1k times · Source

I'm struggling to get ZeroClipboard working within a jQuery context. The basic usage I'm after is clipping the text of each div with the class copy on click.

The following jsFiddle works on double click using the stable ZeroClipboard v1.3.3

http://jsfiddle.net/bEQ6R/

html:

<div class="copy">Click this text to copy this text</div>
<div class="copy">Or click this text to copy this text</div>
<p class="debug flash-loaded">Flash player is loaded.</p>
<p class="debug confirm-copy">Text Copied.</p>
<textarea placeholder="Use this textarea to test your clipboard"></textarea>

js:

$(document).ready(function() {
    ZeroClipboard.config({ moviePath: 'http://zeroclipboard.org/javascripts/zc/ZeroClipboard_1.3.2.swf',debug: true });    
    var client = new ZeroClipboard($('.copy'));
    client.on('load', function(client) {
        $('.flash-loaded').fadeIn();
        client.on('complete', function(client, args) {
            client.setText($(this).text());
            // client.setText('Manually Set Text to This instead of the contents of the div');
            console.log(client);
            $('.confirm-copy').fadeIn();
        });
    });
});

Yes, I understand there are other similar ZeroClipboard questions here, but I have yet to see a simple jsFiddle version actually work. Existing fiddles I've come across are either deprecated or no longer functional for some other reason.

Also, ZeroClipboard's demo on their own site http://zeroclipboard.org/ for the same version appears to work just fine, so I know it's possible.

Answer

SAL picture SAL · Mar 19, 2014

Here is a working solution. On the fiddle I changed client.on('complete'... to client.on('mouseover'... to initialize the ZeroClipboard flash file before the first click.

$(document).ready(function() {
    ZeroClipboard.config({ moviePath: 'http://zeroclipboard.org/javascripts/zc/ZeroClipboard_1.3.2.swf',debug: true });

    var client = new ZeroClipboard($('.copy'));
    client.on('load', function(client) {
        $('.flash-loaded').text('Flash player loaded at ' + $.now()).fadeIn();
        client.on('mouseover', function(client, args) {
            client.setText($(this).text());
            $('.confirm-copy').text('text copied at ' + $.now()).fadeIn();
        });
    });
});