Go to homepage

Projects /

Copy To Clipboard

A Vanilla JavaScript plugin to copy content to the clipboard.

View Demo


How to

Use this plugin to copy content to the clipboard. Add the .js-copy-to-clip class to the button you want to use as trigger.

<button class="js-copy-to-clip">
  Click to copy content to the clipboard!

Content to copy #

To connect the copy button with the element whose content you want to copy, make sure the aria-controls value of first one is equal to the ID value of the second one.

<p id="content-to-copy">Content to copy</p>

<button class="js-copy-to-clip" aria-controls="content-to-copy">
  Click to copy

If no aria-controls attribute is set, the content of the .js-copy-to-clip element is copied to the clipboard.

Alternatively, you can use the data-clipboard-content attribute to pass the content you want to copy:

<button class="js-copy-to-clip" data-clipboard-content="This is the content to copy.">
  Click to copy

Tooltip #

We use the Tooltip component to show a tooltip element on hover and to display a success message once the content has been copied to the clipboard. For this to work properly, make sure to modify the .js-copy-to-clip element as follows:

  • add the js-tooltip-trigger class;
  • add a title: this is the content of the tooltip on hover (e.g., 'Click to copy');
  • add a data-success-title attribute: this is the success message (e.g., 'Copied!').
<button class="js-copy-to-clip js-tooltip-trigger" title="Click to copy" data-success-title="Copied!">
  <!-- ... -->

Make sure to check the Tooltip info page for additional options.

Custom Events #

Use the following events to detect when content is copied to the clipboard:

  • contentCopied: content has been successfully copied;
  • contentNotCopied: there was an issue while copying the content.
var copyTarget = document.getElementsByClassName('js-copy-to-clip');
if(copyTarget.length > 0) {
  copyTarget[0].addEventListener('contentCopied', function(event) {
    // success

  copyTarget[0].addEventListener('contentNotCopied', function(event) {
    // error

Additionally, when content is successfully copied to the clipboard, the .copy-to-clip--copied class is added to the .js-copy-to-clip element. 

Known issues #

This component requires a secure origin (e.g., HTTPS or localhost) to properly work. If you are not using a secure origin, check this issue.


Bug report & feedback

Component Github page ↗

Project duplicated

Project created

Globals imported

There was an error while trying to export your project. Please try again or contact us.