What I'm doing
I'm using clipboard.js to copy a 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 my <script>
tag.
Here's 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 was redundantly using new Clipboard(".get-link");
in an effort to make it work.
All this code does is copy the link to the clipboard, then change the text for 2 seconds, then change it back.
The problem
It only copies the link to the clipboard after the second click on the a
tag. I can't figure out why.
Edit
For some reason, this JS Fiddle shows my code working. Not sure why it doesn't work on my website.