Copy to Clipboard Using Javascript

Priyantha Lankapura
Lanka‘s Blog
Published in
1 min readJan 29, 2018

Ever wanted to copy something to the clipboard programmatically using JavaScript? Here’s how to do it for few different use cases.

Simple Use Cases

We can use following simple function to copy any variable to clip board.

Advanced Use Cases

We can use clipboardjs to implement advanced requirements. You can set it up with few lines of code, it doesn’t have any external dependencies, and it’s only 3KB. More examples can be found on GitHub.

Important

  • Copy commands triggered from document.execCommand() will only work if the event is dispatched from an event that is trusted and triggered by the user.
  • Browser compatibility

Originally published at lankapura.net on January 29, 2018.

--

--