Programster's Blog

Tutorials focusing on Linux, programming, and open-source

HTML5 - Copy To Clipboard

Below is a code example that you can add to your site to have a code section with a button, that when clicked, will copy the code to the user's clipboard. I have done the same thing below, but with a hyperlink instead of a button.

<pre id="code-to-copy">
// This is some code
// Another line
</pre>

<p><button id="js-emailcopybtn">Copy to clipboard</button></p>

<script>
var copyCodeBtn = document.querySelector('#js-emailcopybtn');

copyCodeBtn.addEventListener('click', function(event)
{
    // Select the email link anchor text  
    var emailLink = document.querySelector('#code-to-copy');
    var range = document.createRange();
    range.selectNode(emailLink);
    window.getSelection().addRange(range);

    try
    {
        // Now that we've selected the anchor text, execute the copy command
        var successful = document.execCommand('copy');
        var msg = successful ? 'successful' : 'unsuccessful';
        console.log('Copy email command was ' + msg);
    } 
    catch (err)
    {
        console.log('Oops, unable to copy');
    }

    // Remove the selections - NOTE: Should use
    // removeRange(range) when it is supported
    window.getSelection().removeAllRanges();
});

</script>

Walkthrough Video

Here is a video of me demonstrating the code in use to prove it works.

Last updated: 7th May 2023
First published: 16th August 2018