DEV Community

Cover image for Click to Copy!
Mohd Shahid
Mohd Shahid

Posted on • Updated on

Click to Copy!

Hey Guys πŸ‘‹

Ever wondered how some websites have "click to copy" functionality?

  • You can also do just that, whether you're building an e-commerce website where you want user to click on share button to write the url of the product on their website.
  • or you are building some website/documentation where people can click somewhere and copy the code snippet.

In this article I will explain how you can mess around with the user's clipboard πŸ˜„.

Let's get started πŸš€

To explain this better, I will create a demo project. You can follow along if you want to.

  • Make a folder and name it whatever you like.
  • In that folder make two files
    • 1. index.html
    • 2. app.js

Add the following HTML code in index.html.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Copy to Clipboard πŸ“‹</title>
    <style></style>
  </head>
  <body>
    <h2>Implementing copy to clipboard with a simple click πŸ“‹</h2>
    <button>Click to copy</button>
    <script src="./app.js"></script>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode
  • Now select h2 and button element in app.js:
const h2 = document.querySelector('h2');
const button = document.querySelector('button');
Enter fullscreen mode Exit fullscreen mode

Preview the index.html in your browser.

Side note: This demo will not work in IE

It should look something like this πŸ‘‡
preview of  raw `index.html` endraw


Now to alter the user's clipboard we have to use Clipboard API.

The clipboard object is exposed by the navigator.clipboard property.

Add the following code in the app.js file:

const cb = navigator.clipboard;
Enter fullscreen mode Exit fullscreen mode
  • console.log(cb) will look something like this πŸ‘‡

Preview of clipboard

πŸ‘‰ Remember: Clipboard API is asynchronous, means every method will return a promise which will resolve or reject.
To consume the promise we can either use async/await syntax or .then/.catch.


Reading text from clipboard πŸ“‹

  • To read the text from clipboard I will add a click event listener to the button:
  • In the event listener I will call a method called readText(), which is available on the cb object we accessed earlier:
button.addEventListener('click', async () => {
  const text = await cb.readText();
  console.log(text);
    // output will be whatever you last copied, 
    // or empty string if the
    // copied data is not of type text.
});
Enter fullscreen mode Exit fullscreen mode
  • To read the text from clipboard user must grant read permission, otherwise the operation will fail. πŸ‘‡ clipboard_permissrion
  • If permission is denied πŸ‘‡ permission_denied

You can check if the user granted the permission or not using the Permission API.

To learn more about Permissions API read my article here.


Writing text to clipboard πŸ“‹

  • To write the text to user's clipboard we use writeText() method available on the cb object.
  • Writing permission is given automatically by the browser.

Write the following the code in the app.js:

button.addEventListener('click', async () => {
  // const text = await cb.readText();
  // console.log(text);

  // writing the inner text of the h2 element
  // to the user's clipboard.  
    cb.writeText(h2.innerText).then(() => {
        console.log('text written to clipboard')
    })
});
Enter fullscreen mode Exit fullscreen mode

That's it for this article guys.

See, how easy it is you mess with the user's clipboard πŸ˜‚.

Thanks ❀️ for giving it a read, I hope you found it useful.

For concise tips and tricks, please follow me on Twitter

Happy Coding πŸ’š

Top comments (10)

Collapse
 
frontender profile image
Frontender

Good explanation, thank you, you added something new to my knowledge😁

Collapse
 
sidmirza4 profile image
Mohd Shahid

glad you liked it ✨,
follow me on twitter for more: twitter.com/sidmirza4

Collapse
 
hasnain190 profile image
Hasnain Sikandar

Thanks

Collapse
 
meo3w profile image
Phil Hasenkamp

Awesome job explaining this!

Collapse
 
polgarj profile image
Jozsef Polgar

Thanks, it was a good read. I saved it for later :)

Collapse
 
sidmirza4 profile image
Mohd Shahid

welcome buddy, many more to come πŸ’―

Collapse
 
frulow profile image
Frulow

Something new! Thanks for it.

Just found a small typo: asnychronous

Collapse
 
sidmirza4 profile image
Mohd Shahid

thnks for pointing out πŸ˜…, I have corrected the typo

Collapse
 
chemart profile image
Chema-R-T

Very well explained. πŸ‘ Thank you. I will use.

Collapse
 
sidmirza4 profile image
Mohd Shahid

welcome buddy