Search code examples
javascripthtmlbuttonhrefclipboard

How to use a button in HTML/JS to copy to the Clipboard the href link from an Anchor?


I have an html file with a table collecting in every row several web links (url), and in the same table I would like to have a button for every row, that copies to the Clipboard the link of that row (embedded as 'href' in an anchor tag), giving to the user a feedback popup.

I've tried in several ways but it seems that most of the available examples show how to achieve that just for input fields, moreover with hard-coded functions that do not receive as a parameter the reference id for the text to be copied.

Any ideas?

-UPDATE- I solved my problem thanks to the suggestion of Maassander. Unfortunately the suggested thread was not specific enough for my issue: How do I copy to the clipboard in JavaScript?


Solution

  • The most basic version of this would look something like this I guess:

    var rows = document.getElementsByClassName('table-row');
    
    for (var i = 0; i < rows.length; i++){
      var button = rows[i].querySelector('button');
      
      button.addEventListener('click', function(e){
        var link = e.target.closest('tr').querySelector('a');
        var tempText = document.createElement('textarea');
        tempText.value = link.href;
        document.body.appendChild(tempText);
        tempText.select();
        document.execCommand('copy');
        document.body.removeChild(tempText);
      });
    }
    <table>
      <tr class="table-row">
        <td><a href="https://www.google.com">Google</a></td>
        <td><button type="button">Copy</button></td>
      </tr>
      <tr class="table-row">
        <td><a href="https://stackoverflow.com/">Stack Overflow</a></td>
        <td><button type="button">Copy</button></td>
      </tr>
    </table>