Copying Text To The Clipboard In Pure Javascript

So sometimes you want to be able to just copy text to the clipboard in a web page. This can be more difficult that you first assume. There are going to be two main steps for this process. First, selecting the text that you want to copy to the user’s clipboard. There is no way around this due to the way that the second step works. The second step is copying the selected text to the user’s clipboard.

Alright so with a little bit of googling we can find that there is the Javascript function.

document.execCommand('copy');

This line of code very quickly copies any selected text to the clipboard but first, we have to select the text to copy it. This is where most of the work comes in. The basic select and copy code will look something like this. Well, that’s it. You can change and edit the little bit to fit your needs but that is really the core of it. Select the text then copy it.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s