DEV Community

Marco Poletto
Marco Poletto

Posted on

4 3

Copy text on click with JS

Yesterday I've stumble upon a necessity of copy some text into clipboard with JavaScript and I thought it might be useful to share the method I've used with everyone else.

In detail I had to copy on click some hex value on colored swatches and I had to do it in plain JS.

My approach uses the "event" that's automatically passed on every click.

  • It selects the text inside the clicked element (event.target)
  • And copies it into the clipboard.
  • For demo purposes, it opens an alert box notifying the hex code selected

I found it particularly useful for sharing colors to a designer, but can, of course, be used in many other ways (e.g. dashboards, form pre-filling on click, etc.)

Reinvent your career. Join DEV.

It takes one minute and is worth it for your career.

Get started

Top comments (0)

This post blew up on DEV in 2020:

js visualized

🚀⚙️ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! 🥳

Happy coding!

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay