Jquery/javascript copy to clipboard

Stofke picture Stofke · Mar 31, 2011 · Viewed 11.4k times · Source

I'm using http://www.steamdev.com/zclip/#usage to copy some text to the clipboard and that code is working just fine. It uses flash to create a crossbrowser solution and it is based on ZeroClipboard, which seems to be considered to be the best working solution at the moment.

However I would like to have multiple copy to clipboard buttons or links on my page. Here is an example.

http://jsfiddle.net/stofke/TB23d/

This code works, it copies the text of the coupon code to the clipboard and opens up a new page with the correct link. How can I use that code on other links without having to duplicate it for each and every link / id.

Using just the class

$(function() {
$('.copy').zclip({
    path: 'http://shopsheep.com/js/ZeroClipboard.swf',
    copy: $(this).text(),
    afterCopy: function() {
        window.open($(this).attr('href'));
    }
});

});

doesn't work: as you can see here: http://jsfiddle.net/stofke/EAZYW/ if you remove the afterCopy function you'll see that $(this).text() will return the whole page instead of just the text between the link tag.

doing something like this

$(function() {
$('a.copy', this).zclip({
    path: 'http://shopsheep.com/js/ZeroClipboard.swf',
    copy: $('a.copy', this).text(),

});

});

slightly improves upon it but returns all text between the link tag as you can see here. http://jsfiddle.net/stofke/hAh3j/

Answer

mplungjan picture mplungjan · Mar 31, 2011

UPDATE: This no longer works but I cannot delete the post

This seems to work - someone might be able to make it more elegant

http://jsfiddle.net/5nLw6/7/

$(function() {
    $('.copy').each(function() {
        var linkId = $(this).attr("id");
        $(this).zclip({
        path: 'http://shopsheep.com/js/ZeroClipboard.swf',
        copy: $("#"+linkId).text(),
        afterCopy: function() {
            window.open($('#'+linkId).attr('href'));
        }
    });
  });
});