Search code examples
javascripthtmlclipboard

Copy to clipboard for basic html


I am new to programming and I have basic HTML skills. I am creating a basic web site and I have information in a paragraph and the information is separated by <br> tags. I am looking to add a "copy to clipboard" button and function so that the 16 lines of information are saved to the clipboard.

<p>
this is the 1st line<br>
this is the 2nd line<br>
...
this is the 16th line [copy to clipboard]
<p>

Solution

  • In browsers supporting document.execCommand('copy') and document.execCommand('cut'), copying to the clipboard is very simple; you just do something like this:

    var copyBtn = document.querySelector('#copy_btn');
    copyBtn.addEventListener('click', function () {
      var urlField = document.querySelector('#url_field');
      // select the contents
      urlField.select();     
      document.execCommand('copy'); // or 'cut'
    }, false);
    <input id="url_field" type="url" value="http://stackoverflow.com/questions/32802082/copy-to-clipboard-for-basic-html">
    <input id="copy_btn" type="button" value="copy">

    The above is cribbed straight from JavaScript Copy to ClipBoard (without Flash) using Cut and Copy Commands with document.execCommand().

    Press Run code snippet above, then press the copy button. You’ll see that takes the URL in the input field there (the URL for this StackOverflow question), and copies it to your clipboard.