Copy text on click with JS

polettoweb

Marco Poletto

Posted on June 20, 2019

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

💖 💪 🙅 🚩
polettoweb
Marco Poletto

Posted on June 20, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Copy text on click with JS
javascript Copy text on click with JS

June 20, 2019