Identify anchor and copy URL to clipboard

I have long document pages in this format:

<div class="guides-chapter">
  <h3 id="oranges">Oranges are great</h3>
  <button class="clipboard-guide">Copy link</button>
  <div class="copied"></div>
</div>
...
<div class="guides-chapter">
  <h3 id="apples">Apples are great</h3>
  <button class="clipboard-guide">Copy link</button>
  <div class="copied"></div>

</div>
...

I’m trying to use jQuery to achieve the following when the button is clicked:

  1. Identify the title of H3 to use as an # anchor
  2. Remove any existing # anchor from the current URL before copying
  3. Put the URL + # in the clipboard
  4. Put the text ‘URL copied’ into div.copied

Re 2: This is necessary in case someone arrives at the page through an anchor (e.g. index.html#oranges) and then wants to copy the URL under #apples. In this case #oranges has to be removed first.

I’ve tried to use this script as a basis, but I’m pretty lost. Anyone able to help me?

Answer

You can get the URL without the current hash using a combination of window.location.origin and window.location.pathname. Then you can use $.siblings() to find the sibling <h3> and $.attr() to get its ID.

You’re on the right track with your copy, but you can do one better. I’ve created the copy as a function. It’s very similar to what you have in your pen, but it takes an argument for what text you want to copy.

If the copy fails for any reason, it will show a prompt with the text that the user can manually copy, and if that fails, it will silently log it to the console.

function copyText(text, elm)
{
  let textarea = document.createElement("textarea");
  textarea.value = text;
  textarea.style.position="fixed";
  textarea.style.opacity=0.01;
  document.body.appendChild(textarea);
  textarea.focus();
  textarea.select();
  
  try {
    let success = document.execCommand("copy");
    document.body.removeChild(textarea);
    if(success)
    {
      if(elm != undefined)
        elm.siblings(".copied").html("text copied!");
    }
    else
    {
      prompt("Press Ctrl+C to copy (Cmd+C on Mac)", text);
    }
  } catch (error) {
    console.log("Unable to copy", error);
  }
}

$(".clipboard-guide").on("click", function(){
  let url = window.location.origin + window.location.pathname;
  let toCopy = `${url}#${$(this).siblings("h3").attr("id")}`;
  copyText(toCopy, $(this));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="guides-chapter">
  <h3 id="oranges">Oranges are great</h3>
  <button class="clipboard-guide">Copy link</button>
  <div class="copied"></div>
</div>

<div class="guides-chapter">
  <h3 id="apples">Apples are great</h3>
  <button class="clipboard-guide">Copy link</button>
  <div class="copied"></div>

</div>