Copy To Clipboard JavaScript Only

Posted on Wed, 9/30/2015
1 minute read

Just the other day Clipboard.js as released and I got super excited about not using Flash anymore to copy thing.

I looked through their code and they're just using Document.execCommand() to copy to clipboard. I figured I would play with it and did it myself in just a few lines of code. Here's the Pen of my work:

 

See the Pen Copy To Clipboard JS Only by Josh Fabean (@fabean) on CodePen.

 

The main magic of this is right on this one line of JavaScript:

document.execCommand('copy', false, document.getElementById('select-this').select());

I grab the input, select() it then run document.execCommand on it. Super easy, and fun to do. If you want to use this yourself you should probably use the full library as it has nice fallbacks and works in more cases anyways.

It ended up getting picked on CodePen so that's super cool too!

:wq