-1

I have a page with a generated URL and I want to copy that URL to clipboard via a button. Is is not a problem if I write the URL in the element but if I choose to show a static text (in my example "Klicka för att ansluta till mötet") instead to hide the long URL I can only get the static text. Se image

Image with button and link

It is the href url I want to copy from the link "Klicka för att ansluta till mötet".

The html code:

<button class="btn" id="copy_button" onclick="copyToClipboard('#url')">Copy the link</button>

<code>
  <a id="url" class="url" href='' target="UrlGenerator"></a>
</code>

The script:

  <script>
    function copyToClipboard(element) {
      var $temp = $("<input>");
      $("body").append($temp);
      $temp.val($(element).text()).select();
      document.execCommand("copy");
      $temp.remove();
    }
  </script>

How can I get the href URL instead of the text showing on page?

I want to copy URL instead of the text showing. In my code the URL are generated byt it could be the same if the code where

<button class="btn" id="copy_button" onclick="copyToClipboard('#url')">Copy the link</button>

<a id="url" class="url" href="https://example.com">Klicka för att ansluta till mötet</a>

PelleH
  • 1
  • 1

1 Answers1

-1

Use the clipboard API like below. The document.execCommand("copy") is deprecated.

  const copyContent = async () => {
    try {
      await navigator.clipboard.writeText(text);
      console.log('Content copied to clipboard');
    } catch (err) {
      console.error('Failed to copy: ', err);
    }
  }

Parvez
  • 129
  • 1
  • 7