Clipboard cut, copy and paste with JavaScriptby Andrew Pociu on Jul 11 2005 - 14:59Description: This tutorial will show you how to copy text to the clipboard, cut to the clipboard and paste, all these from a browser window. Content: JavaScript offers you the possibility to perform the typical operations on the client's clipboard: cut, copy and paste. Before going any further, I should mention that this code doesn't work with Firefox. Copy to the clipboardSometimes, when the user submits a form you may want to offer him the possibility to copy the content of a field (such as a textarea) to the clipboard so that if something goes wrong he doesn't lose what he just wrote. Another situation in which you can use this feature is when you have some cut & paste code, instead of letting the user select the text, right clicking and selecting copy or cut, he can do all this through a single click of a button. The following sample HTML page uses JavaScript to copy the selected text. Here is the JavaScript code:
And the HTML you need to make this work is:
Select all and copy to clipboardMost of the time you'll want the user to select the entire text in a textarea and then copy it to the clipboard. Using JavaScript you can automatically select all the content of the textbox and copy it, to simplify the process for the users. We use the same JavaScript and HTML we used in the earlier example and simply add 2 more lines to the JavaScript function CopyToClipboard():
The first line we added puts the focus on the textarea, and the second one selects all its content. After that, the text is ready to be copied in the clipboard. Paste from clipboardIn certain cases you may want to paste the content of the clipboard. This can be accomplished as easy as copying to the clipboard was. Here's the JavaScript you need to use for implementing both a copy button and a paste button:
And the HTML you need to make this work is:
Please note that when you paste this code, it is pasted in the textarea, and all the previous text is erased. To paste the text at cursor position, more code is involved. Cut from clipboardI'm not completely sure why you'd want to cut content from a page, but here it goes, the code needed for cutting content from a page, along with the earlier code (for copying and pasting):
And the markup:
Beware, anything from the document can be cut using this method, including the textarea and buttons. Source: Geekpedia URL: http://www.geekpedia.com/prog_ttrls.php?id=126 |