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

Top comments (0)

11 Tips That Make You a Better Typescript Programmer

typescript

1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields

...

Read the whole post now!