0

I'm html-formatting my teacher union's new contract for our member website. We'd like to have a link icon (or the words 'copy link') after different sections (that have the name attribute). This will allow members to copy links to different sections to his/her clipboard.. and then direct others to specific sections of our very long contract. Can I do this with html code?

Here's my progress:

<script>
function myFunction() {
  var copyText = document.getElementById("myInput");
  copyText.select();
  copyText.setSelectionRange(0, 99999)
  document.execCommand("copy");
  alert("Copied the text: " + copyText.value);
}
</script>

<input size="20" type="text" value="https://www.example.com#ARTICLE2" id="myInput"><button onclick="myFunction()">Copy text</button>
bradfdlad
  • 29
  • 1
  • 1
  • 11

1 Answers1

3

So add querySelectorAll to select all the links you want to add it to. You might need to refine it if it selects too many. And add the item to click and copy it.

function copyIt(text) {
  var input = document.createElement('input');
  input.setAttribute('value', text);
  document.body.appendChild(input);
  input.select();
  var result = document.execCommand('copy');
  document.body.removeChild(input);
  return result;
}



document.querySelectorAll('a[name]').forEach(function (anchor) {
  anchor.addEventListener("click", function (){
    var page = window.location.href.replace(/#.*$/, '')
    copyIt(page + '#' + anchor.name);
  });
});
a[name]::after {
  content: '\2693';
  cursor: pointer;
}
<a name="ARTICLE5-1"></a>1
<p>a</p>
<a name="ARTICLE5-2"></a>2
<p>b</p>
<a name="ARTICLE5-3"></a>3
<p>c</p>
<a name="ARTICLE5-4"></a>4
<p>d</p>
<a name="ARTICLE5-5"></a>5
<p>e</p>
epascarello
  • 204,599
  • 20
  • 195
  • 236