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 |
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/.
JavaScript
function that tests for the availability of
the clipboard and uses it if available.