Eric Bergman-Terrell's Blog

Javascript / HTML Tip: How to Programmatically Copy Text from a Web Page to the Clipboard
October 7, 2015

I recently updated my Base64 Decoder/Encoder, JSON Pretty Print and XML Pretty Print utilities by adding a button that copies the text to the clipboard. The technique I used is to select the field containing the text, and then call document.execCommand('copy') to copy the field's text into the clipboard. The following code snippet first selects the <TEXTAREA> with an id of "Text", and then copies its text to the clipboard. It uses jQuery for the necessary client-side HTML manipulation.

Note, document.execCommand('copy') doesn't work on every browser, but I've verified that it works on Firefox, IE, and Chrome on the desktop, and on the Chrome browser on Android. That's why the call is inside of a try / catch block.

$(document).ready(function () {
    $('#copy').click(function() {
        $('#Text').select();

        try {
            var successful = document.execCommand('copy');
        } catch (err) {
            console.log('unable to copy: ' + err);
        }
    });
});

no-one can copy these good looks
No-one can copy my good looks!

Keywords: Javascript, jQuery, clipboard, document.execCommand('copy'), browser support, HTML

Reader Comments

Comment on this Blog Post

Recent Posts

TitleDate
.NET Public-Key (Asymmetric) Cryptography DemoJuly 20, 2025
Raspberry Pi 3B+ Photo FrameJune 17, 2025
EBTCalc (Android) Version 1.53 is now availableMay 19, 2024
Vault 3 Security EnhancementsOctober 24, 2023
Vault 3 is now available for Apple OSX M2 Mac Computers!September 18, 2023
Vault (for Desktop) Version 0.77 ReleasedMarch 26, 2023
EBTCalc (Android) Version 1.44 is now availableOctober 12, 2021