
Using Zeroclipboard for WP comments
When Adobe introduced the new Flash 10 a few months back, it led to a rather huge, grand backlash from the online community for breaking various uploading tools on many websites, including WordPress and Flickr, for screwing with SWFUpload. Not only that, it also breaks the default “copy to clipboard” functionality offered by many javascript resource sites on the Internet, frustrating millions out there. The reactions from Internet users, although varied, are more or less the same – they wanted Flash 10 the work the same way as Flash 9 does, when it comes to clipboard copy and uploading.
It’s a fix, not a bug
Adobe didn’t budge for a simple reason – the fix is meant to be a fix and not a bug. The security measure implemented in Flash 10 means that instead of blindly allowing any interactions between javascript and a flash file, users with the new Flash 10 installed have to click on the Flash player itself to initiate any action. A very good way to thawrt malicious scripts from fooling around with loopholes, but also a very good way to break the web (although not as bad as the transition from IE6 to IE7 and now, IE8).
A few months after the introduction of Flash 10, both WordPress and Flickr have came out with genious ways to fix their uploader, so it shouldn’t be a very huge problem to all. That only solves part of the problem – what about copy to clipboard functions? Check it out after the jump:
Using Zeroclipboard
Believe me or not, this tutorial is going to be very simple, given the fact that I’m not that well-versed when it comes to Javascript. I even had to look up for a list of eventhandlers because I’ve forgotten most of them *weak smiles*
The interest in restoring the “copy to clipboard” function was rekindled in me over the weekend when I realized how important is it to offer your commentators an option to copy their comment to their clipboard, just in case anything goes wrong. On the other hand, there are also other reasons why one might want to offer such a feature – for example, copying a permalink, a shortened url, a piece of text and etc. Zeroclipboard is one of the easiest solution to the broken function caused by Flash 10. Having jQuery installed will be handy, so be sure that you have it – if you’re using WordPress, you will most probably not need to worry about that.
More detailed and all-encompassing usage of Zeroclipboard is available at their Google Code ‘Instruction’ page.
Getting started
Obviously, Step 0 is as simple as downloading the library. Upload the following two files from the unzipped directory to a certain directory on your site:
- ZeroClipboard.js
- ZeroClipboard.swf
Let’s say that we will be uploading it to a theme folder, http://www.domain.com/wp-content/themes/wp-theme/js. Of course some of you have your own ways to organize your files, such as directly uploading them to the js folder located in the root directory, but since I wanted it to be theme-specific, I’ve decided to throw it into my theme’s js folder.
First of all, you will need to have the Zeroclipboard loaded. To specify the directory of the theme currently in use, we can use the following PHP-Javascript hybrid:
<script type="text/javascript" src="<?php bloginfo('stylesheet_directory'); ?>/js/ZeroClipboard.js"></script>
Given the example above, <?php bloginfo('stylesheet_directory'); ?> will give us http://www.domain.com/wp-content/themes/wp-theme/.
Appending functions
The following lines are to be added between the <script type="text/javascript"> ... </script> tags, unless otherwise mentioned.
Since we’re talking about a WordPress blog over here, the javascript file will usually not be located at the root directory of the page you’re viewing. Zeroclipboard comes with a handy function that allows you to specify the exact location of the file:
ZeroClipboard.setMoviePath( 'http://www.domain.com/wp-content/themes/wp-theme/js/ZeroClipboard.swf' );
Now this part is gonna be a mouthful:
- You will have to declare and set the value of a variable called ‘clip’, and call for a new client – you will usually need only one unless you want to have multiple instances of the clipboard copy button on the same page.
- We also need an event listener such that whenever a certain action occurs to the button, we will copy whatever content that is inside a specified element to the clipboard.
- If you want to let the visitor know that the text has been successfully copied to clipboard, you might want to change the value of the button.
- Last, but not least, we need to do some gluing fun. Gluing will generate a flash movie of an identical size to the DOM element you’ve specified by the element id.
Summarizing what is in the list above, you arrive at the initialization function:
var clip = null;function init() {clip = new ZeroClipboard.Client();clip.addEventListener('mouseOver', my_mouse_over);clip.addEventListener( 'onComplete', my_complete );clip.glue( 'clipboard' );}
What happens when you hover your mouse over the button? Now that’s something we will be address here:
function my_mouse_over(client) {clip.setText( document.getElementById('comment').value );}
Informing the commentator that his/her comment has been successfully copied to clipboard, you don’t want to use an alert box – that’s something that might annoy them. You can change the value of the button so that it displays a success message when the copying is done. A setTimeout function can be added if you want the innerHTML to be reset back to the original ‘Copy to Clipboard?’ text. Also, helping them to refocus back to the comment textfield will be handy too.
function my_complete(client) {document.getElementById('clipboard').value = "Comment copied";document.getElementById('comment').focus();setTimeout ( "resetbutton()", 3000 );}
Another issue to deal with – the button sticks to the value of “Comment copied” after clicking the button. We need an extra mechanism to make sure that the value is reset to the original value of the button. There are definitely more sophisticated ways to store and then redisplay the original value of the button, but I’m still new to Javascript so we’ll have to do it the idiot-proof way (again):
function resetbutton() {document.getElementById('clipboard').innerHTML = "Copy to clipboard?";}
Now this is the optional part. If you’re having a WordPress plugin that changes the position of the button, what should you do? Do note that the absolute positioning of the flash movie over the DOM element (in this case, the button) is done when the page loads. It does not track live changes in the button’s position after the page is loaded. The button on my current theme changes position because I have WP Thread Comment plugin activated – if a commentator chooses to respond to another’s comment, the comment form will be nested in the original comment to facilitate cross referencing.
If that’s the case, we will have to create another function that will reposition the button. I am not very javascript savvy, so I don’t know a simpler way to do it, but my idiot-proof method will be appending the onmouseover eventhandler to the <form> element. It will instruct to reposition the button when the user hovers around the form (which will be the case when the form dynamically switches position across the page). Thank goodness, they have a reposition function included in the library. All we need to do is call for it:
function hoverreposition() {clip.reposition();}
If you combine everything, here’s what you should see:
<script type="text/javascript" src="<?php bloginfo('stylesheet_directory'); ?>/js/ZeroClipboard.js"></script><script type="text/javascript">ZeroClipboard.setMoviePath( 'http://www.teddy-o-ted.com/wp-content/themes/Teddyrisationeta/js/ZeroClipboard.swf' );var clip = null;function init() {clip = new ZeroClipboard.Client();clip.addEventListener('mouseOver', my_mouse_over);clip.addEventListener( 'onComplete', my_complete );clip.glue( 'clipboard' );}function my_mouse_over(client) {clip.setText( document.getElementById('comment').value );}function my_complete(client) {document.getElementById('clipboard').innerHTML = "Comment copied";document.getElementById('comment').focus();setTimeout ( "resetbutton()", 3000 );}function hoverreposition() {clip.reposition();}function resetbutton() {document.getElementById('clipboard').innerHTML = "Copy to clipboard?";}</script>
Possible modifications to this script will be directly inserting the javascript commands into comments.php, and you can even save the file as ZeroClipboard-functions.js and import it using the following code:
<script type="text/javascript" src="<?php bloginfo('stylesheet_directory'); ?>/js/ZeroClipboard-functions.js"></script>
If you’re concerned about the weight of the JS file(s), you can always use the Javascript Compressor to help you zip everything up. Now you’re almost done with the javascript part!
Preparing your page
For simplicity reasons, I will be using the default Kubrick theme as our reference.
You have all the essential javascript functions in place. What you need to do now is to load the function to get everything working smoothly by loading the first function into your document body. In addition, you do not want the init function to be loaded when the page doesn’t contain a comment form. Head over to header.php now and search for the <body> tag. Replace it with this:
<body<?php if (is_single()) { ?> onload="init()"<?php } ?>>
Note: If you have comments enabled on your pages as well, you will need to use this instead:
<body<?php if (is_single() || is_page()) { ?> onload="init()"<?php } ?>>
Of course, there might be instances when you have comment forms elsewhere on your blog – on the index page and etc. There are a whole list of conditional comments available at the WordPress Codex to help you with this.
Modifying comment.php
We’re dealing with copying a comment entered in the WP comment form, so you will probably see the following HTML code (or something similar) in your comments.php file:
<form action="<?php echo get_option('siteurl'); ?>/wp-comments-post.php" method="post" id="commentform">...<p><textarea name="comment" id="comment" cols="100%" rows="10" tabindex="4"></textarea></p><p><input name="submit" type="submit" id="submit" tabindex="5" value="Submit Comment" /><?php comment_id_fields(); ?></p>...</form>
We will now add a new button to the bottom of the comment form such that it will allow your visitor to copy his/her comment to the clipboard. Now you might be thinking, why did I choose to use a block-level element <div> instead of using <input>? Here are two simple reason (thanks to the author for replying to my question):
- It is not a block-level element, so measuring its actual size is next to impossible
- The library cannot propagate mouse events to simulate the mouse down state
The reason is simple – it is almost impossible for the .Don’t forget to call for the resetform function on the submit button:
<form action="<?php echo get_option('siteurl'); ?>/wp-comments-post.php" method="post" id="commentform">...<p><textarea name="comment" id="comment" cols="100%" rows="10" tabindex="4" onmouseover="hoverreposition()"></textarea></p><p<div id="clipboard">Copy to clipboard?</div><input name="submit" type="submit" id="submit" tabindex="5" value="Submit Comment" onclick="resetbutton()" /><?php comment_id_fields(); ?></p>...</form>
We’re done!
So now you will have a neat new button in your comments section that allows your commentators to copy their comment if they see the need to. I hope you find this tutorial useful! I’m not some javascript guru, so if there’s anyone out there who finds that there are mistakes/problems in this tutorial or there are easier ways to achieve the effect, do drop a comment to notify me. Thanks!



















Funny, I never came to realize this ‘fix’. Well, maybe because I’m tied up to an older web standards, I couldn’t be bothered to update my flash version (it’s still v7).
The funniest thing, IE5! Who in the world uses IE 5.5 these days? LoL!
Check out NoktahHitam’s latest blog post » I Don’t Really Enjoy Futsal
@NoktahHitam: Oh, maybe it’s time to do some upgrading! Flash 10 offers a lot of new functionality (such as 3D rotation stuff, I’m not very sure about how it works). However, I’m still having Flash 9 installed because some of the sites I’m going are yet to change their flash-javascript upload combination (which doesn’t work in Flash 10).
You’re using IE5.5? Wow! That’s ancient, teehee!
Hey Teddy, I have tried this tutorial this morning. It’s working on my site already! Thanks so much for this tutorial. It really make things easier without constantly pressing the ctrl-a and ctrl-c.
Anyway, I tried the JavaScript you posted above as followed but it didn’t work. I took the code from your source code and that one works. The JS is a bit different in your source and from the tutorial above. Instead of using script type=”text/language”, I use script type=”text/javascript” and I took the rest of the code from your source code. Hope you don’t mind as I was trying to figure it out.
And I think you might also wish to add which files to upload, the ZeroClipboard.js and the ZeroClipboard.swf. Initially I thought it was weird to upload everything when only 2 files are used in the JS, some people might just upload everything ;)
Overall, a great tutorial! :D
Check out Dayan’s latest blog post » I love Mr Chewy
@Dayna: You’re welcome! Although I’m currently running Zeroclipboard on my blog too, sometimes I still instinctively select everything in the texxtarea and copy them without realizing that I have a handy button in place now.
I’m sorry about the error in the code, thanks for pointing it out! It should be
<script type="text/javascript">instead. OH, and I’ve added an extra line to the my_complete function such that the cursor will be refocused to the comment field when the copying is done.Oh yea, the files to upload :P just the two files will do. I’m too forgetful!
I could still copy and paste from your commenting section, Teddy. I mean, it’s not flash, right? And both the right click commands work, as well as the keyboard shortcuts.
Check out Eli James’s latest blog post » Bookmarked! 12th Feb
@Eli James: O, Zeroclipboard doesn’t change the textarea at all. It only appends an invisible, floating flash movie to the ‘Copy to clipboard’ button (or any button that is intended to serve the same function) so that when a visitor clicks on a button, he/she is actually clicking on the flash movie. The click will instruct the flash movie to copy whatever you have in the textarea to the clipboard.
Try right clicking the ‘Copy to clipboard?’ button and you’ll see a typical context menu of a flash file.
p/s: Never knew you had another blog out there!
Okay I’m a bit puzzled by this threaded comment thing, so bear with me if this comment appears in a weird place.
Okay, lemme get this straight. Before this, a copy to clipboard command was done with just Flash, but now you’ve got to do a workaround for the same thing? Ergh … always wondered at the usefulness of such buttons … I’d just hit ctrl+A and ctrl+C … ;-)
PS: Yeah I’ve been running a blog about the online fiction sphere for some time now. Acts as a rally point for the Internet fiction-writing community. And yeah. Accidentally put in the link there – I usually leave my personal blog link for friends. Sorry bout that.
@Eli James: I’m sorry about the quirky comment reply steps! I’ve limited the nesting level so that comments will not nest in the previous one indefinitely :P but it’s also a little confusing.
For Flash 9 (previously) and 10 (now), copying is done with a Flash movie. What is different is that in Flash 9, a user can click on a button with a javascript call function, i.e.
<div onclick="copytoclipboard()">Copy?</div>and the Flash movie can just be embedded anywhere in the page. The javascript will then instruct the Flash movie to execute the copying command.However, things changed in Flash 10 – as a security measure, Adobe has made it such that the user cannot ask the Flash movie positioned anywhere on the page to execute a command issued by a javascript function. Instead, the user has to explicitly click *on* the Flash movie to do it.
So for this tutorial, we will use a javascript that searches for the DOM element with an id of ‘clipboard’, and dynamically sizes and positions a Flash movie above the button, so that when the user clicks on the ‘Copy to clipboard?’ button, he/she is actually clicking on a Flash movie.
I hope this explains the case, heh.
p/s: Oh, I’m glad that you’ve accidentally typed the URL in because I’m having a lot of fun reading it (hope you don’t mind). Teehee.
Thanks for the tutorial!! These things are always a blast to take a look at. I find sometimes I do have to copy my comments, I hate the sites where they have those ridiculous captcha crap, that you don’t even see on their page and then there goes your comments…
Check out Destiny’s latest blog post » Superstitions: Feng Shui
@Destiny: I agree with this. Captcha is okay as long as I can read what’s on the image. It’s ridiculous that even though I’m a human, I can’t even read what’s the text on the captcha image. I always copy and paste the comment when that happens, just in case. ;)
Check out Dayna’s latest blog post » I love Mr Chewy
@Destiny: “I hate the sites where they have those ridiculous captcha crap” – well said. There are sites where the captchas are almost indecipherable and when I ask for alternatives (like a sound file), it’s either the sound fails to play, or I couldn’t make up what’s being pronounced. Meh.
As a good habit I will always copy my entire comment to the clipboard before submitting my comment. Sometimes there might be a nasty server timeout on you and you’ll find yourself ripping your hair off.
@Dayna: I can completely understand your situation. It sucks that sometimes captcha are not even human readable. I always try to avoid it because sometimes people with certain problems when it comes to deciphering patterns and words are disadvantaged. That probably explains why I stuck to the idiot-proof Math Comment Spam input method.
I think I’m on the same page as Eli J… :P I’ve never used the button to copy and pasta, I always use A+C.
And when was 10 released? Man, I’m so behind, LOL.
@Cynthia: Yea, sometimes I do that too even when I know the button is there. On some sites, successful copying to the clipboard elicits no response or whatsoever, so I’m not sure whether is it copied or not.
Flash 10 was released a few months back I think, breaking a whole bunch of Flash+Javascript uploaders in its wake.
Interesting. I can’t believe I missed the whole Flash 10 mess. Probably because I wasn’t actively using Flickr before this and neither do I use WP’s native flash uploader. (FTP FTW!) But I use them both now so, heh.
If I’m not mistaken you had an auto-copy-to-clipboard feature before this right? I wondered a while ago where that went. Nonetheless, I might try to implement this on my blog sometime!
It’s definitely a very useful feature. I’m only wondering why doesn’t WordPress bundle it out-of-the-box.
Although I’m with a few of you who’s already accustomed to Ctrl+A then Ctrl+C-ing. =P
Check out ember’s latest blog post » Happy Lunar New Year!
@ember: LOL! Good for you! When I first updated to Flash 10, the SWFUploader in my WP installation was broken and it scared the hell out of me because I thought I’ve done something else that broke my WP. If the latter is for real, I will have to do a fresh installation which is definitely very, very frustrating.
Yeap, you’re right that I had a feature that automatically copies your comment to the clipboard when you submit your response. The problem with the script is that it doesn’t work with Flash 10 and… for some people, there might be really important stuff currently residing in their clipboard and by giving them no option to disable the feature, it’s absurd.
This button is pretty much a trivial issue since I believe everyone had a bad experience with a wrong captcha entry or a random server timeout upon comment submission, so they’re more or less conditioned to copy their comment before submission. That’s what many blog authors assume that commentators are doing. Well, most do, but not every single one of them.
Before anyone can blame you for server timeouts, you can shove this button in their face :D
0.0 blurrrr.. im such a flash noobie! although i did fiddle with it when it was under macromedia flash nx or sth like that.. but it was fun tho!
firstly thanks alot for commenting about my pictures =D i love those comments! hehe tells where im good at and not.
oh and about the tripod unsteadyness problem, i usually lean my camera on something =) i mean for added stability, but sometimes u just gotta hold ur breath!
PS: i dont know which bokeh effect u talking about but i only have kitlens (18-55) and 50mm f1.8 =D
pssst: i hope my pictures improved! did they?
Check out sue’s latest blog post » I love Char Kuey Teow!
@sue: Ah relax! This tutorial has nothing to do with Flash at all. It’s just making use of it to help you copy stuff. It comes prepackaged with the library, so you don’t actually need to do anything to the Flash movie but just upload it.
You’re welcome! It’s my pleasure. I hate it that my cheap tripod wobbles from time to time (especially in strong winds), so I have to weigh it down with my own body weight or something. Pretty inconvenient!
The bokeh effect I was talking about is found in the ‘Hut’ photo.
p/s: Your photos are always so nice!
well i just wanted to ask wether this can be used for copying the content in the posts , what are the required modifications
Hi. It is possible to get the innerHTML content of a post. Let’s say that your post is wrapped using a <div> tag with a unique ID. All you have to do is change this line:
clip.setText( document.getElementById('comment').value );… to this:
clip.setText( document.getElementById('[post-ID]').innerHTML );fnsq [url=http://chamberware.com/thomas-sabo-uk.html]thomas sabo sale[/url] [url=http://www.spritz.it/Swarovski-uk.html]buy swarovski crystal sale[/url] nqox
[url=http://chamberware.com/thomas-sabo-uk.html]thomas sabo sale[/url] [url=http://www.spritz.it/Swarovski-uk.html]http://www.spritz.it/Swarovski-uk.html[/url] vatl
[url=http://chamberware.com/thomas-sabo-uk.html]cheap thomas sabo charms outlet[/url] [url=http://www.spritz.it/Swarovski-uk.html]swarovski crystal[/url] zwwb
[url=http://chamberware.com/thomas-sabo-uk.html]thomas sabo bracelet[/url] [url=http://www.spritz.it/Swarovski-uk.html]swarovski crystal[/url] bjtj
twdk
acsv
fdsm [url=http://chamberware.com/thomas-sabo-uk.html][/url] [url=http://www.spritz.it/Swarovski-uk.html][/url]
& xed 05 mustange 05 roadstar & vacances village port bourgenay 05 spec v 05 mazdaspeed miata 05 mercedes kompressor 05 suzuki drz 400 [url=http://www.louboutinmenzusale.com/ルブタン-スリングバック-セール-5.html ]ルブタン 新作 [/url] 06 autoloader 06 07 forum snowboards 050624 05120 06 charger srt
05 xsv 05 siverado 05 infinity g35 coupe 05 playoffs 05 nhl standings [url=http://www.nikeshoxdiscountsale.com/ナイキ-ショックス-シューズ-c-2.html ]ナイキ アイアン [/url]06 07 ride bindings && true 06 07 bindings &dagger 05064033af inmotion
05 q45 05 kawasaki prairie 360 05 kawasaki prairie 05 oz to grams 05 waterblock [url=http://www.viviennewestwoodcheaponline.com ]ヴィヴィアン [/url]&’trousers 05556 05d2 11d1 83fc 00a0c9089c5a inprocserver32 refers to a missing 050622 0554 aix
05941 06 600 exhaust gsxr &fitch 05420 frydaddy electric 05621 0516 1182 usr sbin mkvg && and php 05171
cash master men\’s watches niaspan 500mg sony short wave radio sale tupperware quitting smoking soundgarden bx80532pg3000d [url=http://www.hermesbagsinnsakujp.com/]エルメス バーキン[/url]
[url=http://www.chanelbagsjpnow.com/]シャネル ミニ[/url]
radar detector pop penile implants pictures of mp3 players ps2 backups for sale ad tech heat vent self talk cd 4″ digital indicators fender watch pl cezanne biography [url=http://www.louisvuittonjpto.com/]ルイヴィトン トランク [/url]
nintendo we michael jordan retro shoes selling house by owner nature creation hoover runabout vacuum cannon powershot a20 river plate soccer phosphatidylserine ps