Hello there. I am Terry and I am a full-time undergraduate based in Singapore. I take photos, write a blog and design websites.

And no, I'm not a teddy bear.

Using Zeroclipboard for WordPress Comments

Using Zeroclipboard for WP comments

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:

  1. <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:

  1. 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:

  1. var clip = null;
  2. function init() {
  3. clip = new ZeroClipboard.Client();
  4. clip.addEventListener('mouseOver', my_mouse_over);
  5. clip.addEventListener( 'onComplete', my_complete );
  6. clip.glue( 'clipboard' );
  7. }

What happens when you hover your mouse over the button? Now that’s something we will be address here:

  1. function my_mouse_over(client) {
  2. clip.setText( document.getElementById('comment').value );
  3. }

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.

  1. function my_complete(client) {
  2. document.getElementById('clipboard').value = "Comment copied";
  3. document.getElementById('comment').focus();
  4. setTimeout ( "resetbutton()", 3000 );
  5. }

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):

  1. function resetbutton() {
  2. document.getElementById('clipboard').innerHTML = "Copy to clipboard?";
  3. }

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:

  1. function hoverreposition() {
  2. clip.reposition();
  3. }

If you combine everything, here’s what you should see:

  1. <script type="text/javascript" src="<?php bloginfo('stylesheet_directory'); ?>/js/ZeroClipboard.js"></script>
  2. <script type="text/javascript">
  3. ZeroClipboard.setMoviePath( 'http://www.teddy-o-ted.com/wp-content/themes/Teddyrisationeta/js/ZeroClipboard.swf' );
  4. var clip = null;
  5. function init() {
  6. clip = new ZeroClipboard.Client();
  7. clip.addEventListener('mouseOver', my_mouse_over);
  8. clip.addEventListener( 'onComplete', my_complete );
  9. clip.glue( 'clipboard' );
  10. }
  11. function my_mouse_over(client) {
  12. clip.setText( document.getElementById('comment').value );
  13. }
  14. function my_complete(client) {
  15. document.getElementById('clipboard').innerHTML = "Comment copied";
  16. document.getElementById('comment').focus();
  17. setTimeout ( "resetbutton()", 3000 );
  18. }
  19. function hoverreposition() {
  20. clip.reposition();
  21. }
  22. function resetbutton() {
  23. document.getElementById('clipboard').innerHTML = "Copy to clipboard?";
  24. }
  25. </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:

  1. <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:

  1. <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:

  1. <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:

  1. <form action="<?php echo get_option('siteurl'); ?>/wp-comments-post.php" method="post" id="commentform">
  2. ...
  3. <p><textarea name="comment" id="comment" cols="100%" rows="10" tabindex="4"></textarea></p>
  4. <p><input name="submit" type="submit" id="submit" tabindex="5" value="Submit Comment" />
  5. <?php comment_id_fields(); ?>
  6. </p>
  7. ...
  8. </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:

  1. <form action="<?php echo get_option('siteurl'); ?>/wp-comments-post.php" method="post" id="commentform">
  2. ...
  3. <p><textarea name="comment" id="comment" cols="100%" rows="10" tabindex="4" onmouseover="hoverreposition()"></textarea></p>
  4. <p<div id="clipboard">Copy to clipboard?</div>
  5. <input name="submit" type="submit" id="submit" tabindex="5" value="Submit Comment" onclick="resetbutton()" />
  6. <?php comment_id_fields(); ?>
  7. </p>
  8. ...
  9. </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!

Burn after reading » Now you're done reading. What's next?

Related

Related posts that might interest you:

Popular

Posts that are popular among visitors:

Share it

If you've enjoyed the post, or think that it might be useful to others, do share in on a social network site that you're using. Thank you!

  • Digg
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • StumbleUpon
  • Technorati
  • LinkedIn
  • Reddit
  • Design Float
  • Identi.ca
  • Live
  • Ping.fm
  • Print this article!
  • Twitter
  • Netvibes
  • HackerNews
  • Slashdot

26 responses to “Using Zeroclipboard for WordPress Comments” » Leave a response

  1. NoktahHitamResponse

    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

  2. DaynaResponse

    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

  3. Eli JamesResponse

    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

    1. Eli JamesResponse

      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.

  4. DestinyResponse

    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

    1. DaynaResponse

      @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

  5. CynthiaResponse

    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.

  6. emberResponse

    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!

  7. sueResponse

    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!

  8. nikeshResponse

    well i just wanted to ask wether this can be used for copying the content in the posts , what are the required modifications

  9. The Ugliest Jerseys in NFL/NHL/NBA/MLB LeaguesResponse

    [...] online no prescription Other site about "Buy Tenormin tablets": Purchase Tenormin uk, Tenormin purchase, 25 Tenormin, Price Tenormin [...]

  10. Photoshop tutorials spotlight effectResponse

    After that website owner downloads available may be the thing you need. Acquiring things you need for the internet site in the free … nEed for PSD to be able to Drupal conversions ; web site preservation may accelerate your Websitepsd download

  11. Stop smoking foreverResponse

    Have you ever stop smoking cigarettes how can a hypnotist enable you to continue to be a new Non-Smoker? by simply Joanna Malinowskastop smoking

  12. Solution architect salaryResponse

    Desai, Bhavesh “Metallic Powder Coating Process – Problem & Solution.” Metallic Powder Coating Process – Problem & Solution EzineArticles.com. Http://ezinearticles.com/?Metallic-­Powder-­Coating-­Process-­-­-­Problem-­and-­Solution&id=3265449

  13. Blog john watsonResponse

    Create any news investigation to create brand-new lifestyle for your ArticlesPosition yourself as being a distinctive, major supply by revealing your current analysis of the at present appropriate reports celebration. nOt only can …Prywatna emerytura w Uk

  14. Stop smoking quitmeterResponse

    Some great benefits of preventing smoking begin to arise as early as twenty or so minutes out of your very last smoke. Your own hypertension and also heartbeat return to far more typical specifications.stop smoking

  15. serhoburwukResponse

    You could get these handbags for every occasion. There can be a huge variety for sale in these bags which may be bought at specific stores. Whether you might be a socialite or perhaps a working woman, http://www.goyardreplica.com
    offers Goyard bags for everyone. The internal designing is done in a smart way. There is certainly ample space to ensure you are able to place your valuable or documents in the proper way. You’ll have the ability to purchase a major handbag according to your need. These handbags have some of pockets so that you may carry your money, mobile, stationary and also other things separately in those pockets.

    Goyard handbags really are a popular accessory among women. You’ll have the ability to also gift this gorgeous asset in your friend, sister, mother or any lady to show your respect and love on any occasion. Other than Goyard handbags stores -http://www.goyard-tote.us
    , it can be done to also find these bags over the shopping websites. This is a simple approach to find out your best handbag in your case without confusion. It can be done to search for a number of models of these handbags and judge a suitable model. It is very simple to position a purchase order and make the payment because of these bags through shopping sites. Through this facility, you are able to find your favorite handbag for your desired http://www.goyardhandbags.us
    in few days only.

Leave a Response » Share your thoughts or Return to top

Your name is required. Why?

  • So that I can address you personally (which I'm more than happy to do).
  • Everyone loves their name to be called, right? Nobody wants to be referred to as 'a certain someone' or Mr X (X-Men members aside).
  • If your post too much spam, your name will be imprinted on a personalised voodoo doll, completely free of charge. I'm just joking!

Your email is needed. Why?

  • Your email is, and will, never be given out to any third party under any conditions (except for people sneaking up behind me when I'm on WP admin).
  • So that I can contact you personally in case of certain issues that I wish to address personally.
  • If you post too much spam, I'll email the same spam you've posted 10 times back to you, completely free of charge.

You can always leave a personal URL behind

  • It can be anything - most people put their blog URL, their facebook page, their Twitter URL, their MySpace or etc.
  • I give love back by saying NO to no-follow. All of your webbie links are dofollows instead.

Twitter. Twitter. Twitter.

  • What is Twitter?: Twitter is a social networking and micro-blogging service that enables its users to send and read other users' updates known as tweets. Tweets are text-based posts of up to 140 bytes in length.
  • What is my Twitter ID?: To get a Twitter ID, you simply have to sign up for an account at Twitter.com. Your ID will be in the format of your profile's URL - http://twitter.com/[userid].

Comment notes

  • Gravatar: You can register for one at Gravatar.com
  • XHTML: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">
  • Codes: Wrap them up with <code></code> tags.

Hello Easter Egg hunter! You've discovered the magic of the Konami Code!

Yea. You probably know what the Konami code is before getting to this page. So now what? Here is a randomised YouTube video on my favourites list... which includes Rickroll, if you're luck enough to get it.

You are currently watching Swat Team vs Wall. Loving it? You can even watch the video in its full screen glory :)

The Konami Code:
Konami Code sequence