Copy Text to Clipboard in HTML Page using JavaScript

Posted by in Software

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 to copy to clipboard.

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:

where trigger is a CSS selector.

[Thanks Gabriel Gularte].

Popup approach

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

  1. HTML
  2. JavaScript

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:

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

References

HTH,


A little experiment: If you find this post and ad below useful, please check the ad out :-)