Sometimes it can be useful to copy some text or a URL to the Windows Clipboard, allowing the web page user to paste the text elsewhere – such as a Word doc, or email, etc.
Sure – the user could highlight the text, and click CTRL+C, or right-click and select “copy” – but you might have a reason to do so from “code”.
It follows that this needs “client side” code – as opposed to “server side” code – which would be no use copying to the clipboard on the server !!
window.clipboardData.setData(‘Text’, ‘This is some text’);
- Determine the “control” from the id value passed
- If the control wasn’t found (null), then show error
- Otherwise, grab the “value” – and set the clipboard text
var control = document.getElementById(controlId);
if (control == null)
alert(‘ERROR – control not found – ‘ + controlId);
//determine the value of the control
var controlValue = control.value;
//copy to clipboard
alert(‘Copied text to clipboard : ‘ + controlValue);
The following example shows this using both HTML controls, and ASP.NET controls :
- Input control (Textbox)
- Input control (Button)… OnClick, call the “CopyToClipboard” method
<h1>HTML Text Box</h1>
<input id=”HTMLTextBox” type=”text” />
<input id=”HTMLButton” type=”button” value=”button” onclick=”CopyToClipboard(‘HTMLTextBox’);” /><p>
A better “example” might be to include a “copy” button next to a text panel, or something like a calculation, or contact details – whatever the scenario requires, really !
The field controls are very much the same, but using “ASP” server side controls.
- ASP.NET TextBox
- ASP.NET Button
<h1>ASP.NET Text Box – client side CLICK</h1>
<asp:TextBox ID=”ASPNETTextBox” runat=”server” />
<asp:Button ID=”ASPNETButton” runat=”server” Text=”Click To Copy” />
Note that the “click” event is NOT specified above – there is a trick here, as the controls are actually “server side” – but we need the click event to run “client side”.
For this, the “OnClientClick” event is used – rather than the “Click” event. This means there WON’T be a PostBack event, and program code will run “client side”.
BUT – having said that – the best approach is to use some code behind to dynamically set the value for the “OnClientClick” event.
protected void Page_Load(object sender, EventArgs e)
ASPNETButton.OnClientClick = “CopyToClipboard(‘” + ASPNETTextBox.ClientID + “‘);”;
This could probably be included in the HTML Design for the page – but there may be a need to have the dynamic ClientID value – as opposed to hard-coding the ASP.NET field name.
Here’s the page :
Just need to enter some text, and click the button – will then copy the text to the clipboard, and also display a message.
NB – you might see the following message when using Windows Vista :
Click here to see the full source code for the page (HTML) – and code behind (C#).
This function and HTML could then be used in a SharePoint WebPart, or an ASP.NET application of some kind. Hope you can use it for your solution…