ZeroClipboard Multiple Times on a Single Page

Took my first look at ZeroClipboard the other week and I have to say I like it a lot.

What is ZeroClipboard?

So, what is it?  It’s a small (important), free (very important) and cross-browser (very, very important) library which uses an invisible Adobe Flash movie and JavaScript interface that lets you easily copy text from your website to the clipboard.

It’s available via NuGet, GitHub or directly from the ZeroClipboard website.

Purpose of this post?

Although the library is fairly well documented, the one thing I did have trouble working out was how to apply the library across multiple elements on one web page.  Thankfully it turned out to be very straightforward and here’s how you do it:

Installation

First off, get it into your asp.net web application.  I’ve used NuGet for convenience and easy management of the package but install it manually if you like:

Install ZeroClipboard via NuGet

This will install the bits and bobs that make up ZeroClipboard into the Scripts folder.  If you open that up you’ll see three new files:

  • ZeroClipboard.js
  • ZeroClipboard.min.js
  • ZeroClipboard.swf

Installing ZeroClipboard this way will also mean you get a nice little readme.txt presented to you when the installation is complete covering pretty much all you need to know except for how to implement it multiple times on a single page which is, after all, what I’m attempting to cover in this post!

So, enough already Craig just get to the point!

Applying ZeroClipboard to Multiple Elements on a Single Page

So it transpires all you need to do is pass the ZeroClipboard constructor a comma separated list of elements you want to apply the functionality to. Duh! (at least that’s what I thought when I figured it out)

As per most of the examples I’ve seen online you’d create a single instance of ZeroClipboard as follows:

// Assume we're applying this to an image with the ID clipboard_image.
var clip = new ZeroClipboard($("#clipboard_image"));

And if you want to pass multiple items either pass in a comma separated list or use a jQuery regular expression as below:

<ul>
<li><img id="clipboard_image_01" src="[image source goes here]" /></li>
<li><img id="clipboard_image_02" src="[image source goes here]" /></li>
<li><img id="clipboard_image_03" src="[image source goes here]" /></li>
<li><img id="clipboard_image_04" src="[image source goes here]" /></li>
</ul>

$(document).ready(function () {
// apply ZeroClipboard to all images that have an ID starting with
// "clipboard_image_"
var clip = new ZeroClipboard($("img[id^='clipboard_image_']").each(function () { }), {
moviePath: '[path to]/ZeroClipboard.swf'
});

And there you have it.  Nice and easy but incredibly useful.

Enjoy!

2 Comments ZeroClipboard Multiple Times on a Single Page

Comments are closed.