DEV Community

Chris Ebube Roland
Chris Ebube Roland

Posted on

Copy to Clipboard in JavaScript with just ONE Line of Code!

Hey devs! Have you ever needed to add a ‘Copy to Clipboard’ feature to your website but thought it might be complicated? Well, it's actually pretty easy and takes only ONE line of JavaScript!

Whether you’re building a portfolio site, blog, or an app with shareable links, this trick will save you time and improve the user experience.

I’ve also made a quick video to demonstrate how easy this is, you can check it out:

Step-by-Step Code

At the heart of this feature is the Clipboard API, which lets you copy text directly to the user’s clipboard. Here’s the one line you need:

navigator.clipboard.writeText("Hello, World!");

Enter fullscreen mode Exit fullscreen mode

And here’s how you can attach it to a button in HTML:

<button onclick="navigator.clipboard.writeText('Hello, World!')">Copy Text</button>
Enter fullscreen mode Exit fullscreen mode

Use Cases:

  • Add a "Copy Email" button to your portfolio.
  • Let users copy shareable links, crypto addresses, or discount codes with a single click.
  • Include this feature in blogs for copying code snippets.

Adding this small feature to your website improves usability and provides a smoother experience for your users. Plus, it’s quick, easy, and works natively in modern browsers!

If you found this useful, check out the full video above for a quick demo! Like and share this post if you think it could help someone else.
Let me know in the comments how you’re using this feature.

Top comments (0)