You can only copy the copy to the clipboard on a second click

What am I doing

I use clipboard.js to copy the url to the clipboard.

So, I start by rendering some HTML in PHP. The code looks something like this:

$copyToClipboard = "copyToClipboard(".$id.");";
echo "<a id='get-link-$id' class='small-button get-link' onclick='$copyToClipboard' data-clipboard-text='myText'><u>Get Link</u></a>";

This is done at the top of my page, before the tag <script>.

Here is what I have below in my script:

new Clipboard(".get-link"); // initialize clipboard elements
$(function() {
    new Clipboard(".get-link"); // initialize clipboard elements
});

function copyToClipboard(id) {
    new Clipboard(".get-link");
    new Clipboard("#get-link-" + id);
    $("#get-link-" + id).text("Copied!");
    setTimeout(function(){ $("#get-link-" + id).text("Get Link"); }, 2000);
}

I used it in excess new Clipboard(".get-link");to make it work.

All this code copies the link to the clipboard, then changes the text for 2 seconds, and then changes it.

Problem

It copies the link only to the clipboard after the second click on the tag a. I can’t understand why.

Edit

- JS Fiddle , . , .

+4
1

, ? :

$(document).ready(function(){
    new Clipboard(".get-link"); // initialize clipboard elements
});

https://jsfiddle.net/j8yLssy9/11/

0

All Articles