Copy To Clipboard
A Vanilla JavaScript plugin to copy content to the clipboard.
Projects /
A Vanilla JavaScript plugin to copy content to the clipboard.
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!
</button>
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
</button>
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
</button>
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:
js-tooltip-trigger
class;title
: this is the content of the tooltip on hover (e.g., 'Click to copy');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!">
<!-- ... -->
</button>
Make sure to check the Tooltip info page for additional options.
When content is succesfully copied to the clipboard, the copy-to-clip--copied
class is added to the copy button. To use a custom class, add a data-clipboard-class
attribute to the button element:
<button data-clipboard-class="btn--copied" class="js-copy-to-clip js-tooltip-trigger" title="Click to copy" data-success-title="Copied!">
<!-- ... -->
</button>
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
});
}
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.