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

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

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();

        // 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


Walkthrough Video

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