Search code examples
jquerytextcopyjquery-selectorszclip

zclip copy next text present in element


I would like to copy text present in the next element but it doesn't work normaly : http://jsfiddle.net/tj7ZX/8/

$(document).ready(function () {

    $('.copy').zclip({
        path: 'http://www.steamdev.com/zclip/js/ZeroClipboard.swf',
        copy: $(this).next().text(),
        beforeCopy: function () {
            $(this).next().css('background-color', 'grey');
            $(this).children().css('background-position', '-108px -90px');
        },
        afterCopy: function () {
            $(this).children().css('background-position', '-54px -37px');
        }
    });
});

I don't know why


Solution

  • The problem is the following statement:

    copy: $(this).next().text()
    

    It will be applied once when you call zclip. At that point in time, this equals to document. In other words, as soon as the page is ready, every .copy gets told to copy the text of document's next sibling, which naturally doesn't exist.

    What we need to do is pass copy a function, in which we can dynamically grab the next element's text whenever .copy is clicked on:

    copy: function() {
        return $(this).next().text();
    }
    

    Here's a working fiddle.