My favorites | Sign in
Project Logo
                
Search
for
Updated Oct 30, 2009 by jhuckaby
Labels: Featured
Instructions  


Overview

The Zero Clipboard JavaScript library provides an easy way to copy text to the clipboard using an invisible Adobe Flash movie. The "Zero" signifies that the library is invisible and the user interface is left entirely up to you.

This library is fully compatible with Flash Player 10, which requires that the copy operation initiated by a user click event inside the Flash movie. This is achieved by automatically floating the invisible movie on top of a DOM element of your choice. Standard mouse events are even propagated out to your DOM element, so you can still have rollover and mouse down effects.

Flash Player 9 is also supported.

Usage

The following subsections describe how to use the clipboard library.

Setup

To use the library, simply include the following JavaScript file in your page:

	<script type="text/javascript" src="ZeroClipboard.js"></script>

You also need to have the "ZeroClipboard.swf" file available to the browser. If this file is located in the same directory as your web page, then it will work out of the box. However, if the SWF file is hosted elsewhere, you need to set the URL like this (place this code after the script tag):

	ZeroClipboard.setMoviePath( 'http://YOURSERVER/path/ZeroClipboard.swf' );

Clients

Now you are ready to create one or more Clients. A client is a single instance of the clipboard library on the page, linked to a particular button or other DOM element. You probably only need a single instance, but if you have multiple copy-to-clipboard buttons on your page, potentially containing different text, you can activate an instance for each. Here is how to create a client instance:

	var clip = new ZeroClipboard.Client();

Next, you can set some options.

Setting Options

Once you have your client instance, you can set some options. These include setting the initial text to be copied, amongst other things. The following subsections describe all the available options you can set.

Text To Copy

This function allows you to set the text to be copied to the clipboard, once the user clicks on the control. You can call this function at any time; when the page first loads, or later in an onMouseOver or onMouseDown handler. Example:

	clip.setText( "Copy me!" );

Hand Cursor

This setting controls whether the "hand" or "arrow" cursor is shown when the mouse hovers over the Flash movie. Here is an example:

	clip.setHandCursor( true );

The only values accepted are true (show "hand" cursor), or false (show "arrow" cursor). The default is true. You can set this option at any time.

Gluing

Gluing refers to the process of "linking" the Flash movie to a DOM element on the page. Meaning, the library will automatically generate a movie that is the exact size of the DOM element, and float it just above the element. Since the Flash movie is completely transparent, the user sees nothing out of the ordinary.

The Flash movie receives the click event and copies the current text (last set with setText()) to the clipboard (a requirement of Flash Player 10 is that a user click event inside the movie must initiate the thread that interacts with the clipboard). Also, mouse actions like hovering and mouse-down generate events that you can capture (see Event Handlers below) and set CSS classes on your DOM element too (see CSS Effects below).

Here is how to glue your clip library instance to a DOM element:

	clip.glue( 'd_clip_button' );

You can pass in a DOM element ID (as shown above), or a reference to the actual DOM element object itself. The rest all happens automatically -- the movie is created, all your options set, and it is floated above the element, awaiting clicks from the user.

The glue system is an optional implementation. If you would prefer to handle your own implementation of the Flash movie, see Custom Implementation below.

Recommended Implementation

It is highly recommended you create a "container" DIV element around your button, set its CSS "position" to "relative", and place your button just inside. Then, pass two arguments to glue(), your button DOM element or ID, and the container DOM element or ID. This way Zero Clipboard can position the floating Flash movie relative to the container DIV (not the page body), resulting in much more exact positioning. Example (HTML):

<div id="d_clip_container" style="position:relative">
   <div id="d_clip_button">Copy to Clipboard</div>
</div>

And the code:

	clip.glue( 'd_clip_button', 'd_clip_container' );

Note that gluing to a container element does not work with the reposition() method (see next section).

Page Resizing

If the page gets resized, or something happens which moves your DOM element, you will need to reposition the movie. This can be achieved by calling the reposition() method. Example:

	clip.reposition();

A typical use of this is to put it inside a window.onresize handler.

If for some reason your DOM element was destroyed and recreated, you can pass the new ID or DOM element reference to the reposition() method. However please note that the new element must be the same size as the previous element. The library does not (yet) support elements that change size.

Note that repositioning only works if you glue using a single argument. If you glue to a parent container element, you cannot (and probably won't ever need to) call reposition().

Hiding and Showing

You can also show and hide the Flash movie on demand, if you have an AJAX web app that dynamically changes content, potentially obscuring the clipboard button. Examples:

	clip.hide();
	clip.show();

The show() function also calls reposition().

CSS Effects

Since the Flash movie is floating on top of your DOM element, it will receive all the mouse events before the browser has a chance to catch them. However, for convenience these events are passed through to your clipboard client which you can capture (see Event Handlers below). But in addition to this, the Flash movie can also activate CSS classes on your DOM element to simulate the ":hover" and ":active" pseudo-classes.

If this feature is enabled, the CSS classes "hover" and "active" are added / removed to your DOM element as the mouse hovers over and clicks the Flash movie. This essentially allows your button to behave normally, even though the floating Flash movie is receiving all the mouse events. Please note that the actual CSS pseudo-classes ":hover" and ":active" are not used -- these cannot be programmatically activated with current browser software. Instead, sub-classes named "hover" and "active" are used. Example CSS:

	#d_clip_button {
		width:150px; 
		text-align:center; 
		border:1px solid black; 
		background-color:#ccc; 
		margin:10px; padding:10px; 
	}
	#d_clip_button.hover { background-color:#eee; }
	#d_clip_button.active { background-color:#aaa; }

These classes are for a DOM element with an ID: "d_clip_button". The "hover" and "active" sub-classes would automatically be activated as the user hovers over, and clicks down on the Flash movie, respectively. They behave exactly like CSS pseudo-classes of the same names.

The CSS Effect system is enabled by default. To disable it, pass false to the setCSSEffects() method. Example:

	clip.setCSSEffects( false );

You can set this option at any time.

Custom Implementation

If you would prefer to instantiate the Flash movie yourself, and completely disable the entire glue and CSS systems, you can simply call the getHTML() method, which returns the actual OBJECT/EMBED tag for the Flash movie. Example:

	var html = clip.getHTML( 150, 20 );

The method requires that you pass in the desired pixel width and height of the movie. The returned HTML can then be inserted into a DOM element of your choice, or written to the page with document.write().

Note: Microsoft Internet Explorer seems to have a bug where the Flash External Interface (the communication layer between JavaScript and Flash) doesn't activate properly unless you insert the OBJECT tag into an element that is already appended to the DOM. So make sure you call appendChild() before you insert the HTML into the innerHTML property of your element.

Event Handlers

The clipboard library allows you set a number of different event handlers. These are all set by calling the addEventListener() method, as in this example:

	clip.addEventListener( 'onLoad', my_load_handler );

The first argument is the name of the event, and the second is a reference to your function. The function may be passed by name (string), an actual reference to the function object, or a PHP-style object/method array:

	clip.addEventListener( 'onMouseDown', [myObject, 'myMethod'] );

This allows you to get back into object context by calling a specific method on a specific object, as seen in PHP. However, I suppose you could just use the JavaScript bind() function to achieve the same effect.

The event names are not case sensitive, and the prefix "on" is optional. For example, the values "onLoad", "onload" and "load" all mean the same thing.

Your custom function will be passed at least one argument -- a reference to the clipboard client object. However, certain events pass additional arguments, which are described in each section below. The following subsections describe all the available events you can hook.

onLoad

The onLoad event is fired when the Flash movie completes loading and is ready for action. Please note that you don't need to listen for this event to set options -- those are automatically passed to the movie if you call them before it loads. Example use:

	clip.addEventListener( 'onLoad', my_load_handler );
	
	function my_load_handler( client ) {
		alert( "movie has loaded" );
	}

The handler is passed a reference to the clipboard client object.

onMouseOver

The onMouseOver event is fired when the user's mouse pointer enters the Flash movie. You can use this to simulate a rollover effect on your DOM element, however see CSS Effects for an easier way to do this. Example use:

	clip.addEventListener( 'onMouseOver', my_mouse_over_handler );
	
	function my_mouse_over_handler( client ) {
		alert( "mouse is over movie" );
	}

The handler is passed a reference to the clipboard client object.

onMouseOut

The onMouseOut event is fired when the user's mouse pointer leaves the Flash movie. You can use this to simulate a rollover effect on your DOM element, however see CSS Effects for an easier way to do this. Example use:

	clip.addEventListener( 'onMouseOut', my_mouse_out_handler );
	
	function my_mouse_out_handler(client) {
		alert( "mouse has left movie" );
	}

The handler is passed a reference to the clipboard client object.

onMouseDown

The onMouseDown event is fired when the user clicks on the Flash movie. Please note that this does not guarantee that the user will release the mouse button while still over the movie (i.e. resulting in a click). You can use this to simulate a click effect on your DOM element, however see CSS Effects for an easier way to do this. Example use:

	clip.addEventListener( 'onMouseDown', my_mouse_down_handler );
	
	function my_mouse_down_handler(client) {
		alert( "mouse button is down" );
	}

The handler is passed a reference to the clipboard client object.

onMouseUp

The onMouseUp event is fired when the user releases the mouse button (having first pressed the mouse button while hovering over the movie). Please note that this does not guarantee that the mouse cursor is still over the movie (i.e. resulting in a click). You can use this to simulate a click effect on your DOM element, however see CSS Effects for an easier way to do this. Example use:

	clip.addEventListener( 'onMouseUp', my_mouse_up_handler );
	
	function my_mouse_up_handler( client ) {
		alert( "mouse button is up" );
	}

The handler is passed a reference to the clipboard client object.

onComplete

The onComplete event is fired when the text is successfully copied to the clipboard. Example use:

	clip.addEventListener( 'onComplete', my_complete );
	
	function my_complete( client, text ) {
		alert("Copied text to clipboard: " + text );
	}

The handler is passed two arguments: a reference to the clipboard client object, and the text that was copied.

Destroying

You may want to completely destroy the clipboard client movie, for example after a successful copy-to-clipboard. This means that the user cannot click to copy additional text. To do this, simply call the destroy() method, as in this example:

	clip.destroy();

This will remove the Flash movie from the DOM, and completely reset the client clipboard object. If you want to reinitialize the object with another container, simply call glue() again (see Gluing above), or getHTML().

Note: For safety reasons, you may not want to call this method directly in your onComplete handler function. The reason is that the JavaScript thread originated from within the Flash movie, which you are attempting to destroy with the destroy() call. This can cause crashes in certain browsers (namely IE). Better to set a timer with setTimeout() and call destroy in its own, safe thread.

Examples

The following are complete, working examples of using the clipboard client library in HTML pages.

Minimal Example

Here is a quick example using as few calls as possible:

	<html>
	<body>
		<script type="text/javascript" src="ZeroClipboard.js"></script>
	
		<div id="d_clip_button" style="border:1px solid black; padding:20px;">Copy To Clipboard</div>
	
		<script language="JavaScript">
			var clip = new ZeroClipboard.Client();
			clip.setText( 'Copy me!' );
			clip.glue( 'd_clip_button' );
		</script>
	</body>
	</html>

When clicked, the text "Copy me!" will be copied to the clipboard.

Complete Example

Here is a complete example which exercises every option and event handler:

	<html>
	<head>
		<style type="text/css">
			#d_clip_button {
				text-align:center; 
				border:1px solid black; 
				background-color:#ccc; 
				margin:10px; padding:10px; 
			}
			#d_clip_button.hover { background-color:#eee; }
			#d_clip_button.active { background-color:#aaa; }
		</style>
	</head>
	<body>
		<script type="text/javascript" src="ZeroClipboard.js"></script>
		
		Copy to Clipboard: <input type="text" id="clip_text" size="40" value="Copy me!"/><br/><br/> 
	
		<div id="d_clip_button">Copy To Clipboard</div>
	
		<script language="JavaScript">
			var clip = new ZeroClipboard.Client();
			
			clip.setText( '' ); // will be set later on mouseDown
			clip.setHandCursor( true );
			clip.setCSSEffects( true );
			
			clip.addEventListener( 'load', function(client) {
			 	// alert( "movie is loaded" );
			} );
			
			clip.addEventListener( 'complete', function(client, text) {
			 	alert("Copied text to clipboard: " + text );
			} );
			
			clip.addEventListener( 'mouseOver', function(client) {
				// alert("mouse over"); 
			} );
			
			clip.addEventListener( 'mouseOut', function(client) { 
				// alert("mouse out"); 
			} );
			
			clip.addEventListener( 'mouseDown', function(client) { 
				// set text to copy here
				clip.setText( document.getElementById('clip_text').value );
				
				// alert("mouse down"); 
			} );
			
			clip.addEventListener( 'mouseUp', function(client) { 
				// alert("mouse up"); 
			} );
			
			clip.glue( 'd_clip_button' );
		</script>
	</body>
	</html>

Browser Support

The Zero Clipboard Library has been tested on the following browsers / platforms:

Browser Windows XP SP3 Windows Vista Mac OS X Leopard
Internet Exploder 7.0 7.0 -
Firefox 3.0 3.0 3.0
Safari - - 3.0
Google Chrome 1.0 1.0 -

Adobe Flash Flash Player versions 9 and 10 are supported.


Comment by jhuckaby, Jan 09, 2009

There is no reason IE6 and Opera wouldn't work (in fact, I know that IE6 does work), but they're just not officially supported :-)

Comment by andreoua, Jan 15, 2009

Is pasting supported?

Comment by jhuckaby, Jan 15, 2009

Sorry andreoua, but as far as I know, Adobe doesn't allow a "paste" function.

However, if you want to simulate a paste from something previously copied using the clipboard library, you can grab the last text copied using client.clipText. So if you want to insert that into a text field, for example, you could:

document.getElementById('your_text_field_id').value = client.clipText;

However, this is really just smoke & mirrors, as it doesn't really take text from your PC's clipboard. Sorry I couldn't offer anything better.

Comment by scaban, Feb 06, 2009

It doesn't work on IE6 or IE7, the page doesn't load and it shows a pop-up error of Operation aborted

Comment by jhuckaby, Feb 06, 2009

Dear scaban,

I have tested ZeroClipboard in both IE 6 and IE 7, and it works just fine. The "Operation aborted" is a well known IE bug, and has nothing to do with ZeroClipboard. You can read more about it here:

http://support.microsoft.com/kb/927917

Good luck.

Comment by rottensod, Feb 10, 2009

Dear jhuckaby,

I think Zero clipboard is excellent. Thank you for solving a few problems for me.

However, I don't seem to be able to manage one (simple?) thing. Taking your test page (http://bowser.macminicolo.net/~jhuckaby/zeroclipboard/multiple.html) how can I set the background colour of an element that has been clicked on so it stands out as having been 'visited'?

RottenSod?.

Comment by jhuckaby, Feb 10, 2009
Comment by rottensod, Feb 10, 2009

Brilliant! Thanks Joe

Comment by dvishwa.devanand, Feb 19, 2009

Hi, It's excellent.

But I found one problem. I am using this in a widget code. When I am embedding the widget on any site(like blog), copy is working, but when the file containing widget code resides on our local disk, then it does not work.

Comment by snakeware95, Mar 06, 2009

I read something here about using AIR to do paste: http://www.senocular.com/air/tutorials/clipboardtext/

I don't have any Flash dev knowledge, so it may be off the mark.

Comment by superxain, Mar 16, 2009

ok, it seems the code works very well. Only one request. Can you make a simple version? The code is a little BIG for such a small job.

Comment by realmxyzptlk, Mar 18, 2009

Hi, it does work

the copy functionallity works on my page but de css i'm using on the button utilizes an image as background. Using visual studio's internal webserver the background is shown as expected but using iis the background images don't show up. Can you help me?

Comment by aaguilar, Mar 19, 2009

excellent solution. thank you for your hard work.

Comment by roohitadmin, Mar 21, 2009

I'm afraid I have to agree with what "scaban" said.

I ran into TWO problems:

  1. The operation aborted issue in IE. See the page at http://roohit.com/site/buttons0.php (a.)Given that my snippet has apostrophes, quotes and end script tags, I simplified it to just copy 0, 1, 2 etc. (b.)I also removed my custom event handling (c.) I specifically created a new DIV to contain the table and this JS code in; (d.) I created a new version at http://roohit.com/site/buttons1.php and I still got the same Operation Aborted in IE.
2. I also noticed that the flash movie placement is not quite right. See the placement for the movie on the first 2 buttons is to the LEFT, while it is fine for the other 5.
3. (Did I say two problems? ;) ) I also faced a problem with being able to "select" the text for my input fields.

Please do NOTE: that I am attaching the Flash to the text boxes and not the button images so they are all indeed the same size.

4. And, now as I am typing this it dawns on me that perhaps I could use just one object rather than having an array and set a different snippet on the OnClick?? right?

All in all this is excellent work, thanks so much!!

Comment by bernhard.schenkenfelder, Mar 24, 2009

Great job, thanks!

Comment by roohitadmin, Apr 02, 2009

After HOURS of debugging I have distilled this down to it's simples possible form and it still gives an 'Operation Aborted' Error in my IE7.

Here's the simple test case HTMl file:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>RoohIt: Add an Instant Highlighter Button on your Own Blog, or Web Page</title>
<script type="text/javascript" src="ZeroClipboard.js"></script>
</head>
<body>
<script language="JavaScript">
var clipArr ;
</script>
<input id='text0' type='text' value='abc' readonly='readonly'/>
<script language="JavaScript">
        clipArr = new ZeroClipboard.Client();
        clipArr.setText('abc') ;
        clipArr.setHandCursor( true );
        clipArr.glue( 'text0' );
</script>
</body>
</html>
verbatim code block
Comment by jhuckaby, Apr 02, 2009

Hey roohitadmin,

Thank you for the distilled test case. However, I already know about this IE 7 bug, as does Microsoft, and they detail it here:

http://support.microsoft.com/kb/927917

And this is already written up in a ZeroClipboard? bug here:

http://code.google.com/p/zeroclipboard/issues/detail?id=4

Basically, you cannot call glue() while the page is still rendering in IE. You have to use an onLoad handler to wait for the page to complete before you can dynamically insert DOM elements (which ZeroClipboard? does).

Comment by roohitadmin, Apr 02, 2009

Thanks for your response. As I process the above and try it in my code...

Q1. can I call setText() dynamically AFTER the page has loaded to alter the to-copy-to-clipboard contents? FYI: Prior to your posting, I tried the same with and without the code inside a <table> and found that the simplest case wroks while not in the table and surrounding it with <table><tr><td> and </td></tr></table> gives the "Operation Aborted:

Q2. Placement issue mentioned in previous post, are you aware of it? Text-selection possible? Single clipObject will do the trick for multiple text inputs?

Thanks!!!

Comment by vishwasnadig, Apr 02, 2009

cool logic! wanted to know why this is not applicable in safari

thanks

Comment by krike06, Apr 03, 2009

hey

I get "thingy is null" (line 14 of the javascript file) and the script is not working because of that. What am I doing wrong?

grz krike

Comment by miclefebvre, Apr 07, 2009

Hello krike06,

The problem is because the parameter you entered in the clip.glue( 'd_clip_button' ) is invalid. Does a valid element with an id equals to the parameter name exists on your page ?

ex : <div id="d_clip_button"></div>

Good Luck!!

Comment by gmo...@accensio.com, Apr 07, 2009

Hello,

first of all, thanks for this great script! It solved my problems. I'm pretty clueless, but even I managed to get this to work.. Yay!

I'd love to be able to achieve the following: - have the text "copy to clipboard" change to "copied to clipboard" after a user clicks on "copy to clipboard". How exactly could I achieve that?

- auto-select the entire code in advance for people who'd rather right-click and do a manual copy, rather than click on the "copy to clipboard" button

Hopefully, a charitable soul can help a clueless guy ;)

Comment by plexml, Apr 09, 2009

Just to echo the unanswered question of dvishwa.devanand above, why doesn't the code work on local pages too? I saved the test page to a local file, and downloaded ZeroClipboard?.swf and ZeroClipboard?.js to the same folder as the file. The page appears OK but won't copy to clipboard. Neither does the "Copy to Clipboard" box change colour on mouseover. However if I upload all the items to a website it works fine.

Other clipboard copiers like http://cfruss.blogspot.com/2009/01/copy-to-clipboard-swf-button-cross.html work both online and locally.

Comment by krike06, Apr 09, 2009

hey miclefebvre

thanks for that, I did have it but he couldn't find it or something like that. I know it sounds weird but it's because I'm trying to integrate this into a module for a CMS system and it turns out to be more difficult then expected.

Now I don't have an error but when I click on it nothing happens. nothing get's copied, this is the code I'm using (the link to the script is not present into that page but into another page which is included, so that's not the problem):

<div id="d_clip_button" style="border:1px solid black; padding:20px;">Copy To Clipboard</div>

<script language="JavaScript">
var clip = new ZeroClipboard?.Client(); clip.setText( 'Copy me!' ); clip.glue( 'd_clip_button' );
</script>

Comment by hannerduw, Apr 11, 2009

Is it possible to replace existing listener? I need to replace onComplete listener every time I make reposition, not add a new one. In my case it causes multiplication of listeners.

Comment by navarun.jagatpal, Apr 15, 2009

Hi. Is there any way to use ZeroClipboard? on top of an HTML button, and make the button behave like a regular button? For example:

<button type="button" id="copyButton">Copy</button>

<script type="text/javascript">
	var clip = new ZeroClipboard.Client();
	clip.glue('copyButton');
</script>

The above code glues ZeroClipboard? to the button. I want to do something like that, and I also want the button to look like it's being pressed when the user clicks. Using just the above code, the button doesn't change in appearance at all when it's clicked. I tried using a mouseDown eventListener. But i couldn't figure out any way to make the button appear pressed by just using javascript. I realize this is a difficult thing to do, because there is a flash movie directly above the button, and the flash movie receives the click, and the button itself never actually receives the click. Also, I'd like to be able to do this in a cross-browser way (IE, Firefox, and Safari). Is anything like that possible with the current version of ZeroClipboard??

Comment by miclefebvre, Apr 21, 2009

Hello Krike06, to be able to use it, I added a listener to the button :

clip.addEventListener('mouseDown', function(client) {

clip.setText('copy me');
});

Hope this will help!

Comment by plexml, Apr 22, 2009

Hi navarun.jagatpal,

there is a page at http://nerveplexus.com/Copy_to_Clipboard.htm using ZeroClipboard?.swf that changes the button or link clicked to red on mousedown and back to blue on mouse up. You could easily change that by editing the zc_events() function. There is no ZeroClipboard?.js file. All the code is in the page and is function based rather than using the clip object which I found too involved to modify. Starting at STARTUP in the code it should be fairly easy to follow what is going on.

All you need in the ZeroClipboard? object is ZeroClipboard?.dispatch which is used by ZeroClipboard?.swf as a pointer to the event handler. In this case it is set to zc_events() which then routes the mousedown (click) event to zc_click() and this sets the text you want to copy to the clipboard.

Comment by plexml, Apr 22, 2009

To answer the point by dvishwa.devanand and myself about ZeroClipboard? not working for local files it will work if you make your local folder or file location trusted in your Flash security settings here http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04a.html

Comment by miclefebvre, Apr 22, 2009

Hello navarun.jagatpal,

You should try something like this : <button type="button" id="copyButton" onClick="copyFunction">Copy</button>

<script type="text/javascript">

var clip = new ZeroClipboard?.Client(); //Don't glue on your button
function copyFunction() {
clip.setText('copy me');
}

</script>

Comment by standsongrace, Apr 23, 2009

Would it be possible to add the HTML by javascript when the document loads? I'm trying to use this in a Greasemonkey script.

Comment by navarun.jagatpal, Apr 23, 2009

plexml and miclefebvre, thanks for your responses. But neither of those solutions are working for me.

plexml, the code in the page you linked to doesn't seem to be doing anything extra that ZeroClipboard? already does. For example, it has something like this in the zc_events function:

if(eventName=='mouseDown') {  // clicked down on the button
   document.getElementById('zc_but_'+idNum).style['color'] = 'red'
}

That can already be done with plain old ZeroClipboard?, if I write something like this:

clip.addEventListener( 'mouseDown', function(client) {
	document.getElementById('zc_but_'+idNum).style['color'] = 'red'
} );

Also, let me clarify with an example. If the user is using IE or Firefox under Windows XP, I want the button to look like this before they click it:

and I want the button to look like this when they click it:

I don't think that's possible to do by just changing the CSS style attributes.


miclefebvre, I tested your example and it didn't work. If you don't glue the button to anything, then there is no way for the text to actually be put on the clipboard, right? If I understand correctly, when you call clip.setText(), that doesn't put the text on the clipboard. That just sets a variable inside the flash movie. When the user actually clicks the flash movie, that's when the clipboard gets changed. Isn't that right?

Comment by r...@oasiz.net, Apr 25, 2009

Hello,

This may help some people that experience an issue with Firefox and the flash not being "clickable". Simply add the following to the glue function.

style.overflow = 'auto';

Regards,

Rob

Comment by tehutimaat, Apr 26, 2009

Thank you, Jhuckaby, for a great script.

Now, if I may, a quick question.

I want to add the window.open() function as an onComplete event handler. It's quite easy:

clip.addEventListener( 'onComplete', my_complete ); function my_complete( client, text ) { window.open('URL','windowname','width=400,height=200'); }

The problem is, I'm using ZeroClipboard? to handle multiple elements on a single page. The above code only works with one element per page. Can you or anyone else please tell me how I can get a different URL to open in a new window for each element?

Comment by plexml, May 05, 2009

Hi navarun.jagatpal,

I couldn't quite get it the same as you want but please have a look at the button now on http://nerveplexus.com/Copy_to_Clipboard.htm.

As soon as you style a standard button it loses it's rounded look. Not sure if that can be fixed. Here's the button HTML:-

<button id="zc_but_4" type="button" style="color:black; border:1px outset gray; background-color:#f1f1f1">Copy Button</button>

and here's the javascript bit in zc_events():-

var style = document.getElementById('zc_but'+idNum).style
if(eventName=='mouseDown') { // clicked down on the button
   zc_click(idNum)
   // Turn the background color darker
   style['backgroundColor'] = '#e1e1e1'
   style['borderStyle'] = 'inset'
} 
else if(eventName=='mouseUp') { // Clicked up on the button
   // Turn the background back to usual
   style['backgroundColor'] = '#f1f1f1'
   style['borderStyle'] = 'outset' 
}
Comment by plexml, May 05, 2009

Hi tehutimaat,

See if what I did at http://nerveplexus.com/Copy_to_Clipboard.htm is what you mean. There are 5 buttons each with a different ZeroClipboard? movie and each button opens a new and different window after the complete event.

It's not programmed using the clip object since I couldn't follow all that object stuff. Instead it's function based but the operation should be the same.

zc_events() receives all the events from all the 5 movies and it's easy to edit to requirements. I just added:-

else if(eventName=='complete') {  
   my_complete(idNum, args) 
}

and then your function modified slightly:-

function my_complete(client, text) {
// Client is effectively idNum and the copied text is args.
// There are 5 buttons on the page with idNum's 1 to 5.
// Each button has a different flash movie.
var URL = 'test' + client + '.htm'
window.open(URL, 'windowname'+text, 'width=400,height=200')
return} 
Comment by sullof, May 11, 2009

@Joseph Thanks a lot for your great library.

@navarun.jagatpal At Passpack I use ZeroClipboard? in Passpack 7 putting the flash object into a div and moving the div over the icon associated with the entry fields using a mouseover event. With this simple trick, I can instance just one object and dinamically change what it copies and the callback function. I suggest you to adopt a similar approach.

Comment by matrym, May 28, 2009

To those that run into the same problem I did:

The problem: Any time I generated a new clickable flash area, although I'd already hidden the css for the div, the old flash click location remained (albeit invisibly).

The solution: Generate the clickable area only once (on load) and when you want to hide it, move the css left -1000px, then reposition the flash, so that it's off the page, but such that you can move it back on (without creating a new flash element).

I recognize that you should be able to destroy and then regenerate a new clip, but for whatever reason I was unable to do that without bugs. Good luck out there!

(And thanks for the sweet script!)

Comment by ganivojjala, Jun 11, 2009

Hi plexml,

If i have like 100 buttons on each page..will your code open new window for each click? function my_complete(client, text) {// Client is effectively idNum and the copied text is args.// There are 5 buttons on the page with idNum's 1 to 5.// Each button has a different flash movie.var URL = 'test' + client + '.htm'window.open(URL, 'windowname'+text, 'width=400,height=200')return}

like Joseph's code is not doing that i guess?

Can we have open a new window for each click on the box?

clip.addEventListener( 'onComplete', my_complete );

function my_complete( client, url ) {
window.open(url,'blank')
}

the above code is works fine for 1st time but if i click 5th box its opening all 5 windows?

is there any other way to do this?

Thanks

Comment by jaivuk, Jun 14, 2009

Hello jhuckaby,

I have this problem with Zero Clipboard - I generate output in javascript which contains multiple lines. The output can be copied to the clipboard by zeroclipboard. However there is a problem under Windows XP (and Firefox 3.0.10) - if I paste the output to notepad, new lines are displayed as strange characters. However copy/paste to word or to wordpad works so it tells me Zero Clipboard is using Unix style newlines?

I tried to use '\n\r' and '\r\n' as well as suggested in other comment but it did not work. Do you please have any hint how I can make it work with notepad?

Thank you very much!!!!

Comment by jhuckaby, Jun 14, 2009

Hey jaivuk, try this:

http://bowser.macminicolo.net/~jhuckaby/zeroclipboard/dos_line_endings.html

This is the code to convert any text to use DOS line endings (which plays nice with Windows Notepad):

clip.setText( $('fe_text').value.replace(/([^\r])\n/g, "$1\r\n") );
Comment by pierrefar, Jun 20, 2009

Hi

Can you please give us a full example of using the getHTML in a page? I tried doing this:

document.write(clip.getHTML( 150, 20 ));

And that completely destroys the page: it all goes blank with just the flash object showing, and Firefox stalls with loading the page.

Cheers, Pierre

PS - We exchanged emails about ZC back in January if you want my email address.

Comment by pedzsan, Jun 21, 2009

Hi,

I tried to use this in a page that was served up as xhtml:

<meta http-equiv="content-type" content="application/xhtml+xml;charset=UTF-8" />

In firefox 3.0.11 and I got this error:

"Component returned failure code: 0x80004003 (NS_ERROR_INVALID_POINTER) [nsIDOMNSHTMLElement.innerHTML?" nsresult: "0x80004003 (NS_ERROR_INVALID_POINTER)" location: "JS frame :: http://localhost/condor/javascripts/ZeroClipboard.js?1245498836 :: anonymous :: line 120" data: no]

I tried poking at the code some. For example, I tried making the if test in getHTML true so I would use an object tag and its the same result.

This may be the same as why Google ad words does not work. The solution there is to put an object in the original page that is of type html.

Comment by Terry.Jolley, Jun 24, 2009

Any way to use this script, and then after it copys to the clipboard, to close the window it was run from?

Comment by shLandry, Jul 20, 2009

This works ok except that from time to time in firefox, there is a problem with focus. The movie sometimes needs focus to be changed on the page to make it work properly.

Comment by crossthei.thet, Jul 23, 2009

I'm having problems using this offline. I downloaded the latest version and extracted the gz. I opened test.html, and clicked the copy button, but it wouldn't copy. However, when I uploaded it to my site and tested it, it worked fine - I uploaded test.html, ZeroClipboard?.js, and ZeroClipboard?.swf.

Thanks for the help, and thank you for creating this library. I've been looking for a cross-platform way to copy text to the clipboard, and this library does just that.

Comment by jhuckaby, Jul 23, 2009

Hey crossthei.thet, the reason you cannot use ZeroClipboard? offline is due to a Flash permission thing. You have to edit your Flash settings and allow access for your local page. See this comment posted earlier on this page:

To answer the point by dvishwa.devanand and myself about ZeroClipboard? not working for local files, it will work if you make your local folder or file location trusted in your Flash security settings here:

http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04a.html

Thanks, and good luck!

- Joe

Comment by crossthei.thet, Jul 23, 2009

Awesome, thanks! Sorry I missed the previous response. I searched for "offline", but I guess "local" should have been the keyword I seached for.

Thanks again.

Comment by geigreg, Jul 29, 2009

I simply wish to use the button in a flash website- no html. I am a beginner with actionscript. Can someone suggest how I would use this code with a button instance in Flash timeline? Thanx.

Comment by jhuckaby, Jul 29, 2009

geigreg, I googled for "actionscript copy to clipboard". The first search result has your answer:

http://www.flashmove.com/forum/showthread.php?t=25204

Comment by geigreg, Jul 29, 2009

ah, thanks so much. i was googling "flash" when i should have used "actionscript"...that's how i discovered this thread...i will try this one. thanks again!

Comment by boba899, Aug 05, 2009

I have table that lists shortened URLS. In the table is a delete button and a copy to clipboard button. I can glue a seperate instance to each copy button, which grabs the correct URL from the table. I can also delete the appropriate instance of ZeroClipboard? if the corresponding row is deleted. What I'm having trouble with is repositioning every remaining instance. I know I can reposition individual instances like so:

ZeroClipboard?.clientsinstanceNumber?.reposition();

But how could I change this command so that every remaining instance is repositioned?

Cheers, Alex

Comment by boba899, Aug 06, 2009

Ah, I just counted the number of elements that I had glued ZeroClipboard? to (they all had the same class, so I used jQuery's size() function) and then ran a for loop, with i=0; i<totalNumberOfElements; i++ and then var count = i + 1; ZeroClipboard?.clientscount?.reposition();

Comment by gmacgregor, Aug 15, 2009

Thanks for the script! I've been struggling to get this to work with jQuery (yes, I've checked out the multiples example page). Here's what I've got:

<a href="http://www.google.com" class="copy">copy</a>
<a href="http://www.bing.com" class="copy">copy</a>

<script type="text/javascript"> 
    var clip = null;
    $(function() {
        clip = new ZeroClipboard.Client();
        clip.setHandCursor(true);
        $('.copy').mouseover(function() {
            var txt = $(this).attr("href");
            clip.setText(txt);
            if (clip.div) {
                clip.receiveEvent('mouseout', null);
                clip.reposition(this);
            } else {
                clip.glue(this);
            }
            clip.receiveEvent('mouseover', null);
        });
    });
</script>

On hover the <a> gets the class name of "hover" and the clip.div positions itself appropriately. But two things don't happen:

1. on click nothing is ever copied to the clipboard 2. the mouse cursor isn't rendered as a hand despite this CSS rule:

a.copy.hover {
    cursor: pointer !important;
}

Any ideas what the problem is? Many thanks!

Comment by jhuckaby, Aug 15, 2009

gmacgregor: I have never been able to glue to inline elements such as an anchor (because these don't necessarily occupy a rectangle -- they could span lines). You need to glue to a block element such as a "DIV".

Don't assign the "cusror" CSS property to a subclass like ".hover". Just assign it to "a.copy".

a.copy { cursor: pointer }

Good luck.

Comment by gmacgregor, Aug 15, 2009

Thanks for the reply. I should note that the anchor mentioned above is styled as an inline-block. Regardless, I tried this code in a completely different file:

$(document).ready(function() {
    $('#copy').mouseover(function() {
        var txt = $(this).attr("rel");
        clip = new ZeroClipboard.Client();
        clip.setHandCursor(true);
        clip.setText(txt);
        clip.glue(this);
        clip.addEventListener('complete', function(client, text) {
            $('#copied').text(text + ' copied to the clipboard!').fadeIn("slow").fadeOut(2000);
        });
    });
});

<div id="copied" style="display: none;"></div>
<div id="copy" rel="ZeroClipboard Test!">copy</div>

...and everything works as expected! So I guess the issue in my other file is somehow related to a styling.

Comment by gmacgregor, Aug 17, 2009

Turns out my problem was the path to ZeroClipboard?.swf was not set correctly. Let my hours of hair pulling be a lesson: make sure you set your ZeroClipboard?.moviePath correctly!

Comment by nadoshi, Aug 19, 2009

hi everyone, Is there any reason that this would work in Firefox and not Explorer (on a Windows machine)? The code I am using is as follows....I'd appreciate any help (as I'm clearly a JavaScript? amateur).

<html>
<head>
<style type="text/css">
  1. clip_button {
  2. text-align:center; border:1px solid black; background-color:#ccc; margin:2px; padding:2px;
width: 40px;
}
  1. clip_button.hover { background-color:#eee; }
  2. clip_button.active { background-color:#aaa; }
</style>
</head> <body>
<script type="text/javascript" src="https://sitemaker.umich.edu/lesbianhistories/files/ZeroClipboard.js"> ZeroClipboard?.setMoviePath( 'https://sitemaker.umich.edu/lesbianhistories/files/ZeroClipboard.swf' );</script>

Copy to Clipboard: <input type="text" id="clip_text" size="40" value="Copy me!"/><br/><br/>
<div id="d_clip_button">Copy</div>
<script language="JavaScript">
var clip = new ZeroClipboard?.Client();
clip.setText( '' ); // will be set later on mouseDown clip.setHandCursor( true ); clip.setCSSEffects( true );
clip.addEventListener( 'load', function(client) {
// alert( "movie is loaded" );
} );
clip.addEventListener( 'complete', function(client, text) {
alert("Copied text to clipboard: " + text );
} );
clip.addEventListener( 'mouseOver', function(client) {
// alert("mouse over");
} );
clip.addEventListener( 'mouseOut', function(client) {
// alert("mouse out");
} );
clip.addEventListener( 'mouseDown', function(client) {
// set text to copy here clip.setText( document.getElementById('clip_text').value );
// alert("mouse down");
} );
clip.addEventListener( 'mouseUp', function(client) {
// alert("mouse up");
} );
clip.glue( 'd_clip_button' );
</script>
</body> </html>

Comment by kevin.laevers, Aug 26, 2009

I have a JSP page that reads the URL to be copied from a Java Bean (value set by another component).

What I wish to achieve is that the JSP loads into a pop- up window, displaying the URL that is copied to the window, followed by a 'close' button. So this means the copy to clipboard has to be done on the initial load of the JSP, not by clicking a 'DIV' item or the close button on the page.

How can this be done, as I don't have a 'glue' element that has to be clicked?

Many thanks!

Comment by loujanwen, Sep 03, 2009

help!

i have a big problem,on my computer,there are ie8,oper10.00,firefox3.5,zeroclipboard cannot work at all,but when i visit the sample you give,it is ok,and i could copy the content,even though copy the entire code from you example(i see the source code),it does not work either,i still don not know the reason,and i get these error info from firebug:
1.not well-formed file:///D:/JavaProjects/YUI/WebRoot/examples/ZeroClipboard.js Line 1 2.syntax error file:///D:/JavaProjects/YUI/WebRoot/examples/ZeroClipboard.swf Line 1

hope any guys can give some useful advice,thanks advance!

Comment by reszli, Sep 09, 2009

hi everyone!

i have a little problem with zeroClipboard: when i visit the sample you give everything is OK but when i copy-paste the code it does not works for me - i have the .swf and .js files in place, - they are included properly, - the flash object shows up in place, - but it does nothing on click the event handlers seems to have no effect... any suggestions?

Comment by paul.selker.1, Oct 05, 2009

Thanks for some wonderful work here. One really weird bug I had a tremendous amount of trouble resolving had to do with IE7 - and only IE7, 8 was fine - somehow letting the padding-top of a large div (the boundary of which was nowhere near the button div or the swf) push down the swf object below the div it was glued to. So if you moused over below the div, the hover state was activated but no dice otherwise.

I don't understand why this would be - perhaps it's just my own ignorance but it may also be a very obscure bug. (I fixed it with some conditional statements that took off the padding-top in IE7 and used margin-top for internal elements...)

Anyhow, if you'd like to see the code, shoot me an email at pselker at burnesscommunications dot com.

Comment by nils.laumaille, Oct 08, 2009

Thanks for your great plugin!

One question or suggestion: how to add a tooltip to the glued DOM element?

Indeed when you glue the DOM element, the "title" is no more available. Which is not really smart when the button used to copy in clipboard is an image/icon for example.

Thanks for your work

SliN

Comment by ibnbasit, Oct 21, 2009

following is my code, which works fine in firefox and chrome, but giving bug in IE7.. i dont know what im doing wrong, can you please guide me

$("input[name='htmlcode'], input[name='directlink'], input[name='emaillink'], input[name='imgcode']").live('mouseover', function() {
		
		clip = new ZeroClipboard.Client();
		clip.setHandCursor(true);
		clip.setText($(this).val());
		
		var width = $(this).width();
		var height =  $(this).height()+10;
		var flash_movie = '<div>'+clip.getHTML(width, height)+'</div>';
		
		flash_movie = $(flash_movie).css({
			position: 'relative',
			marginBottom: -height,
			width: width,
			height: height,
			zIndex: 101
		})
		.click(function() { 
			$(this).next('input').indicator({className: 'copied', wrapTag: 'div', text: 'Copied!', fadeOut: 'slow', display: 'after'});
		})
		.insertBefore(this);
	});
Comment by renardpolaire, Oct 22, 2009

It seems ZeroClipboard? doesn't work in ie8. I have the following error : In french : "Erreur d'exécution Microsoft JScript: Cet objet ne gère pas cette propriété ou cette méthode" I have translated the error to english : "Runtime Error Microsoft JScript: Object does not support this property or method"

this is for the following Javascript code. try { document.getElementById("ZeroClipboardMovie?_1").SetReturnValue?(flashtoXML(ZeroClipboard?.dispatch("1","load",null)) ); } catch (e) { document.getElementById("ZeroClipboardMovie?_1").SetReturnValue?("<undefined/>"); } The '}' before the catch is highlighted by the debugger.

This is very strange. I have version 10.0.22.87 of Flash player installed.

It works well in another "real" browser like FF or Chrome.

Comment by powermikee, Nov 14, 2009

Hi thanks for the great code...i have a few issues and would be very grateful if anyone can help. Its working so far, but i have noticed that it didn't work in any IE browsers is there any reason for that? Also when i use it with a hidden div similar to what you have on your comment input, as you click a div appears. The problem is everything gets position 20px lower but the flash movie stays in the same spot? Can you help.

Here's part of the code

<div id="btn_container" style="position:relative;>
<input type="submit" value="Copy" class="shorten_btn" id="copy" /></div>

<script type="text/javascript" src="ZeroClipboard.js"></script> <script>

var val = document.getElementById('textarea').value; var clip = new ZeroClipboard?.Client(); 
clip.setText( val ); clip.glue( 'copy', 'btn_container' ); </script>
Comment by jhuckaby, Nov 14, 2009

Hey everyone. I have been receiving multiple reports that ZC is not working in IE. I cannot reproduce, and would like to have more information (i.e. what Flash version, etc.) to help track down the issue. Here are screenshots of ZC 1.0.5 working in IE6, IE7 and IE8.

Thanks!

Hey powermikee, regarding movie position: If you are having trouble getting the movie to position itself properly, please consider not using the glue() method, but instead just grab the raw HTML for the Flash move using getHTML(), and position it yourself wherever you like. Good luck!

Comment by jukka.hautakorpi, Nov 15, 2009

Hello! This is indeed nice script! I'm using it for making large form that has multiple text inputs with dynamic text inside (read only) to copy each inputs separately. Form is generated by php.

Is it possible to copy varying content that is generated by ajax ? How should i make the glue to each varying element? Or does this even support copying ajax generated multiple text element copying ?

Comment by laomingliu, Nov 19, 2009

I got this to work in Firefox but not Safari in 10.5.8 -- is there anything I can do to make it work in Safari?

Comment by marklacas, Nov 20, 2009

Is it possible to send a click event to the flash object or does it only work when a user clicks? I would like to bind a key to copy.

Thanks, -ml

Comment by icex...@vip.qq.com, Nov 28, 2009

when send glue is not id,it get mistakes in ie6.7. my code

clip.blue($(h1)[0])
//i use JQuery

Please give me a help.

Comment by robertrivas, Nov 30, 2009

Hello and thank you for the script. It is very useful and a powerful thing to have.

I have gotten your code to work for every scenario I can think of but I what I'm doing in the end is basically copying the html content within a <div> to the clip board. Unfortunately I do not get the same affect as one would get when you just highlight and copy a html onto an email. When doing a manual copy you bring along the styles with the copy and paste but while using this script you will get the actual code rather than an html entity.

Thanks for your help and again, great script.

Comment by recaffeinated, Dec 09, 2009

Does anyone have an example using ZeroClipboard? on a page with multiple instances? I'm assuming there's an implementation without re-instantiating a new ZeroClipboard? object for each item. I've noticed some browsers crash on a large number of instances.

Comment by jhuckaby, Dec 09, 2009

@recaffeinated: Yes, there is a link to a demo on the main project page, which does what you want. URL:

http://bowser.macminicolo.net/~jhuckaby/zeroclipboard/multiple.html

Comment by and...@ordinaryradical.ca, Dec 16, 2009

I can't get this to work in IE or the new Chrome beta, but the copying is working on FF3.5. I'm running WinXP 64-bit.

Comment by a.bergm...@it-bergmann.de, Dec 25, 2009

Hi, great work. But I don't understand the sample: The texterea has an event onchange="clip.setText(this.value)". But the text will only be set after the button click... Is there also a way to use something like onchange to set the text?

Comment by akilligelisim, Jan 03 (3 days ago)

Hello,

I'm trying to implement this to my blog (I want to create a button, which gets the current page's URL text and copies it to clipboard).

I've managed to get the url text via a php code but couldn't get this flash work.

I've tried the sample codes on this page, and they work. When I put the same code to wordpress single.php file movie does not load.

I'm putting the movie to the same location with single.php but it does not work. (but test code works)

can anyone help me? I've spent hours but could not solve the problem.


Sign in to add a comment
Hosted by Google Code