TrOnNe
TrOnNe

Reputation: 1772

copy link to clipboard with jquery

I've been following some post about this, but I'm unsure why is not working. It creates the input with the correct info, but it doesn't copy to the clipboard, I'm not sure if it has something to do wit being generated dynamically

Script

//copy to clipboard
$(document).on('click', '[data-action=copy]', function (){
    /* Create input */
    $('[data-action=copy]').after('<input class="hide" value="'+$(this).attr("data-url")+'" id="share-url">');

    /* Get the text field */
    var copyText = document.getElementById("share-url");

    /* Select the text field */
    copyText.select();

    /* Copy the text inside the text field */
    document.execCommand("copy");

    /* Alert the copied text */
    alert("copied");
});

html

<a data-action="copy" data-url="whatever to copy" href="#">
    <img src="{{ cdn('/img/social/link.png') }}" >
</a>    

Upvotes: 1

Views: 1336

Answers (1)

pepe pepe
pepe pepe

Reputation: 184

the problem is that you can't hide the input to copy it. Try this little hack instead style="position: absolute; left: -1000px; top: -1000px"

Upvotes: 1

Related Questions