profile image linking to the home page
PostsCopy text to clipboard with vanilla JavaScript

Copy text to clipboard with vanilla JavaScript

This is an old post from 2020. I'm keeping it here for archival purposes.

This is how to copy text to clipboard with JavaScript. Or use the @compactjs/clipboard npm module. ✌

You first need to select text:;

Then you can copy it with:


warning "" Copying text does only work when following a user action, like a button press.

If you want to copy text without being visible to the user, we need to create an input field to copy from:

const inputElement = document.createElement('textarea');

Fix its position to prevent the window from scrolling: = 'position:fixed;top:0;left:0;';

Then we can add the text we want to copy:

inputElement.value = 'Awesome text!';

To copy the text we need to append it somewhere to the DOM:


Now just copy the text like shown above and afterwards we can just remove it again:


To make things easier, I made a quick JavaScript module called @compactjs/clipboard.

So, using npm, it's as easy as this:

npm install @compactjs/clipboard
import { clipboard } from '@compactjs/clipboard';

	.addEventListener('click', () =>
		clipboard('This text is going to be copied.')

Source code: GitHub

Remember: It needs to follow a user action to work!