Skip to content

Copy Text to Clipboard in HTML Page using JavaScript

May 1st, 2014 - Software(1 min)

I’ve got a problem on one of my sites:

I have a unique identifier displayed on one page, which I need to make it easy

After looking online, I’ve found three approaches using only JS.

Clipboard.js

Clipboard.js is a new (September 2015) approach which uses only JS to copy the text transparently (using the Selection/execCommand APIs).

The code is as simple as:

new Clipboard('.trigger')

where trigger is a CSS selector.

[Thanks Gabriel Gularte].

This method opens a dialog box with a text. The code is as follows:

  1. HTML

    <div id="test">Some text here</div>
  2. JavaScript

    function copyToClipboard(text) {
      window.prompt('Copy to clipboard: Ctrl+C, Enter', text)
    }
    
    // Use JQuery
    //
    $('#test').click(function() {
      copyToClipboard('bobo')
    })

When the text is clicked, a dialog with ‘bobo’ will pop up. The beauty of it is that text is already selected; all you need is CTRL+C (CMD+C on macs) and ENTER to close the dialog.

Select in control

I can display my UID in an <input /> code. If I write it as a read-only field, then I can select it. A code like this:

<input onclick="this.select();" type="text" value="---some UID---" />

will do it. Adding a helper text under (to tell people to perform a CTRL+C) should solve the problem (too).

References

HTH,

Share on
Reddit
Linked in
Whatsapp

A little experiment: