Javascript does not take clicked link with the same ID

Asked

Viewed 143 times

1

I am putting a script to copy the link to clipboard using the plugin ZeroClipboard. The problem is that I have a list with several links that comes from MySQL. And in the loop of the list comes always the id "copy-link" on <a>. When I click the second link or the next ones, then it doesn’t copy to the clipboard, it’s just copying the first one. I think the problem is the ID is 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>

2 answers

1


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

The correct way is to exchange these ID for class. But doing this or you can’t still find these elements via attribute data-clipboard-text.

Anyway how are more than one need a cycle for to run the plugin on each elementto. 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!');
        });
    });
});

0

Try using the click Event instead of the ready, so this action is triggered each 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>
  • Did not solve, just copy the first link.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.