DEV Community

Marco Poletto
Marco Poletto

Posted on

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.)

Top comments (0)