56

Copy to Clipboard

This week I had to create a common “Copy to Clipboard” button, I’ve never created one before and I want to share how I made it.

This is a simple tip, this week I had to create a common “Copy to Clipboard” button, I’ve never created one before and I want to share how I made it. It’s easy, the bad thing is that we must add an <input/> with the text to be copied to the DOM. Then, we selected the content and execute the copy command with execCommand. execCommand('copy') will copy the actual selected content.

Also, this command that now is supported by all the latest version of browsers, allows us to execute another system commands like copy, cut, paste, and make changes like fonts color, size, and much more.

document.querySelector('#input').select();
document.execCommand('copy');
Playground
JS Bin on jsbin.com