Javascript does not get a clicked link with the same ID

1

I'm putting a script to copy the link to clipboard, using the ZeroClipboard plugin. The problem is that I have a list with multiple links that comes from MySQL . And in the list loop always comes the id "copy-link" in <a> . When I click on the second or next link, then it does not copy to the clipboard, it is only copying the first one. I think the problem is ID because it's the same.

javascript

<script type="text/javascript">
            // main.js
            var client = new ZeroClipboard( document.getElementById("copy-link") );

            client.on( "ready", function( readyEvent ) {
              // alert( "ZeroClipboard SWF is ready!" );

              client.on( "aftercopy", function( event ) {
                // 'this' === 'client'
                // 'event.target' === the element that was clicked
                alert('Link copiado!');
              } );
            } );
        </script>

html

<a href="javascript:void(0);" id="copy-link" data-clipboard-text="AQUI VAI O LINK">Copiar Link</a>
    
asked by anonymous 19.06.2015 / 06:14

2 answers

1

If you have several anchors all with the same ID then document.getElementById("copy-link") will only return one element and will not work in the others ...

The correct way is to change these IDs by class. But doing this or you can not still fetch these elements via attribute data-clipboard-text .

Either way as they are more than a precise one cycle is to run the plugin on each element. Suggestion:

var links = document.querySelectorAll('a[data-clipboard-text]');
[].forEach.call(links, function (el) {
    var client = new ZeroClipboard(el);
    client.on("ready", function (readyEvent) {
        // alert( "ZeroClipboard SWF is ready!" );

        client.on("aftercopy", function (event) {
            // 'this' === 'client'
            // 'event.target' === the element that was clicked
            alert('Link copiado!');
        });
    });
});
    
01.08.2015 / 01:13
0

Try to use click event instead of ready , so this action is triggered every time a link click occurs.

<script type="text/javascript">
    // main.js
    var client = new ZeroClipboard( document.getElementById("copy-link") );

    client.on( "click", function() {
    // alert( "ZeroClipboard SWF is ready!" );

        client.on( "aftercopy", function( event ) {
            // 'this' === 'client'
            // 'event.target' === the element that was clicked
            alert('Link copiado!');
        } );
    } );
</script>
    
19.06.2015 / 06:59