Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy the link href itself to the clipboard when clicked

I'm trying to create a link that users can click on it, and then the href itself will be copied to the clipboard. Since I'm new to JS, I couldn't do it with the information I found, because I saw examples where people would click on a button to copy the url, or it would copy the URL of the address bar.

Here is my code, and + artworkUrl + is dynamically filled.

<a id="get-app-artwork" href="' + artworkUrl + '" target="_blank">Copy the cover URL</a>

How can I make this url be copied to the clipboard on click? Every option I found uses different approaches. As I'm new to this, I don't know how to apply to this situation, where I have a link and want to copy the URL of it when clicked.

like image 588
Henrique Barcelos Avatar asked Feb 14 '19 21:02

Henrique Barcelos


People also ask

How do I copy a link in href?

Here's how to do it in 3 easy steps: Right-click the URL you want to copy. Select 'copy' from the popup menu. Navigate to wherever you wish to share the link, right-click then paste.

How do I copy Onclick link?

When the button is clicked select the content of #url then copy it to the clipboard.

How do I copy something to the clipboard in HTML?

writeText() function. This function writes the data fed to it as a parameter into the clipboard. We can use this to copy any text to the clipboard. First, we select the text to copy to the clipboard whether it is from a div or from an input box using document.


2 Answers

Use the Clipboard API, specifically the writeText function.

<a href="' + artworkUrl + '" onclick="copyURI(event)">Copy cover URL</a>
function copyURI(evt) {
    evt.preventDefault();
    navigator.clipboard.writeText(evt.target.getAttribute('href')).then(() => {
      /* clipboard successfully set */
    }, () => {
      /* clipboard write failed */
    });
}

EDIT 18/07/2020 : There is a missing ) to properly close the writeText( function.

like image 86
Effective Robot Avatar answered Oct 23 '22 04:10

Effective Robot


With jquery

$("a #get-app-artwork").click(function(event) {
    event.preventDefault();
    navigator.clipboard.writeText($(this).attr("href"));
 });

like image 1
iambr Avatar answered Oct 23 '22 04:10

iambr