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.
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.
When the button is clicked select the content of #url then copy it to the clipboard.
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.
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.
$("a #get-app-artwork").click(function(event) {
event.preventDefault();
navigator.clipboard.writeText($(this).attr("href"));
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With