JavaScript Help: How to Select Textarea Input and Copy to Clipboard

Don't you love when you need a user to enter code or something that has to be EXACT only to find that they've misspelled it? So you think to yourself, "I can fix that", and you provide them with a complete code snippet to copy/paste. And then you find that they've failed to select the beginning or the ending line or character, and again, there's a problem. With one or two more steps you can make it as easy as possible for the user.

This example demonstrates the use of an HTML form input and JavaScript events to provide a code snippet for cut/pasting some hypothetical functionality. This scenario occurs frequently in web development projects and so I thought I'd share my approach here to speed along duplication. This particular example provides a link to include an interactive hangman game on a web page or blog supporting HTML.

The example (1) provides a working code snippet, (2) detects when a user enters the form input, and triggers automatic selection of the complete code snippet, and (3) if your (visitor's) browser supports it1 automatically copies that selected text into the clipboard buffer in order to make it available for pasting (CTRL-V in windows).

Try it out below:

  1. Click or tab your way into the textarea below, and observe that it highlights all of the text automatically
  2. If your browser supports it, a message indicating that the highlighted text has automatically been copied to the clipboard buffer will also appear (or if not, that you'll need to copy to buffer manually)

1
Copy this code to play hangman from your own site:
 
2
Paste sample code here:
3
HTML Rendering of Sample code above
(waiting for HTML in sample input)

Notes:

1 - Your visitor's browser must support the clipboardData2 object in order to automatically copy the highlighted text into the clipboard. This object is supported by Internet Explorer, and not much else. Anecdotally this could be 80% or more of your traffic if your visitation mirrors general Internet trends. If however, you are part of the non-IE crowd (lets face it, us web developers, our friends and family who's security we care about, and various other non-conformists and hobbyists ;-) then this means you'll have to manually copy to the buffer using CTRL-C, or right-clicking the highlighted text and selecting "Copy" from the context-menu that appears there.

2 - You can find more information about the clipboardData object here, http://msdn.microsoft.com/en-us/library/ms535220%28VS.85%29.aspx.

3 - If you want to explore an alternative that supports the copy to buffer functionality using a flash-based technique, here is a site which describes such a technique, http://www.jeffothy.com/weblog/clipboard-copy/.


Here is the JavaScript function that tests for the availability of the clipboard and uses it if available.