Index

NOTE: This document refers to release 1.2.1 of jsPlumb. jsPlumb underwent some fundamental changes starting from version 1.1.0. Should you need to use a version prior to 1.1.0 I suggest 1.0.4 - the last released version before 1.1.0. Documentation for version 1.0.4 is here.

06/29/10

Summary

jsPlumb allows you to connect elements on the screen with "plumbing", using a Canvas element when supported, and Google's ExplorerCanvas script to support older browsers.

It can be used with either jQuery or MooTools (or another library of your choice if you feel like implementing a plugin for it). Required versions are as follows:

jQuery

MooTools

For Canvas support in IE you also need to include Google's ExplorerCanvas script.

jsPlumb 1.2.1 has been tested on the following browsers:

Changes since version 1.2

Several new concepts have been introduced since version 1.2, and a few convenience methods have been added. The major changes are:

This other stuff has been done too:

Imports

jQuery

Example using jQuery 1.3.x or 1.4.x, jQueryUI 1.7.x or 1.8.x, and ExplorerCanvas:
<script type="text/javascript" src="http://explorercanvas.googlecode.com/svn/trunk/excanvas.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.0/jquery-ui.min.js"></script>
<script type="text/javascript" src="PATH_TO/jquery.jsPlumb-1.2.1-all-min.js "></script>

MooTools

Example MooTools 1.2.4, Drag.Move from MooTools More 1.2.4.4, and ExplorerCanvas:
<script type="text/javascript" src="http://explorercanvas.googlecode.com/svn/trunk/excanvas.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/mootools/1.2.4/mootools-yui-compressed.js"></script>
<script type="text/javascript" src="PATH_TO_MOO_TOOLS_MORE_1_2_4_4"></script>
<script type="text/javascript" src="PATH_TO/mootools.jsPlumb-1.2.1-all-min.js "></script>

jsPlumb Basic Concepts

There are four core concepts in jsPlumb: Connecting two elements - making a Connection - involves three steps:
  1. Create an Anchor for each of the two elements you wish to connect.
  2. Create an Endpoint for each of these Anchors, and assign them.
  3. Join the two Endpoints with a Connector.
Depending on whether or not you wish to be able drag new Connections, step 2 can be omitted.

Simple Connections

This section discusses Connections in which you do not need to support drag and drop.

The most simple connection you can make looks like this:
jsPlumb.connect({source:'element1', target:'element2'});
Note: if you're using jQuery, the 'connect' method is aliased with this shorthand (this applies to all the examples using the 'connect' method, but I won't mention it again):
$("#element1").plumb({target:'element2'});
In this example we have created a Connection from 'element1' to 'element2'. What happened to the three steps I mentioned above? Well, jsPlumb provides defaults for everything. So in this example, behind the scenes jsPlumb used default values for all of these things: Default values are discussed in detail in the Defaults section below.

The Basic Examples section below contains many more examples of how to create simple Connections.

Draggable Connections

To support draggable Connections, you are required to first create Endpoints, as it is Endpoints that the user drags to create new Connections. Endpoints are created by making an addEndpoint call, passing in the target element's id and an options object. There are quite a few things that can be set on the options object; all of these parameters are optional. Here's a simple example of how to create an Endpoint:
var endpointOptions = { isSource:true, isTarget:true };
var endpoint = jsPlumb.addEndpoint('elementId', endpointOptions);
This Endpoint will act as a source and target for new Connections, and will use the jsPlumb defaults for its own appearance and that of any Connections that are drawn from it.

Tip: use jsPlumb.extend

One thing that happens quite often is that you have an Endpoint whose appearance and behaviour is largely the same between usages on different elements, with just a few differences. In these cases it can be quite handy to use jsPlumb's 'extend' function. For example, here's a basic Endpoint:
var exampleGreyEndpointOptions = {
	endpoint:new jsPlumb.Endpoints.Rectangle(),
	style:{ width:25, height:21, fillStyle:'#666' },
	isSource:true,
	connectorStyle : { strokeStyle:"#666" },
	isTarget:true
};
Notice there is no 'anchor' set. Here we apply it to two elements, at a different location in each:
jsPlumb.addEndpoint('element1', jsPlumb.extend({anchor:jsPlumb.Anchors.BottomCenter}, exampleGreyEndpointOptions)); 

jsPlumb.addEndpoint('element2', jsPlumb.extend({anchor:jsPlumb.Anchors.TopCenter}, exampleGreyEndpointOptions));
Note: jsPlumb's 'extend' function is just a wrapper around the supporting library's implementation; you don't need to use it if you know the supporting library's corresponding method.

Drag Options

These are options that will be passed through to the supporting library's drag API. jsPlumb passes everything you supply here through, inserting wrapping functions if necessary for the various lifecycle events that jsPlumb needs to know about. So if, for example, you pass a function to be called when dragging starts, jsPlumb will wrap that function with a function that does what jsPlumb needs to do, then call yours.

At the time of writing, jsPlumb supports jQuery and MooTools, and each of those libraries uses different terminology. In addition, jQuery's API is more fully featured, providing easy support for setting the zIndex and opacity of elements being dragged, as well as the 'scope' for a drag/drop (allowing you to specify more than one type of drag/drop pair), and hover classes for when a draggable is on the move or over a droppable. If you're using jQuery you can of course just supply these values on the dragOptions; to make it easier, jsPlumb's MooTools adapter recognizes these options and adds appropriate callbacks for you.

Given that the options here are library-specific, and both jQuery and MooTools are well-documented, we're going to discuss just the three drag options that behave the same way in both (see below for hoverClass):

For more information about drag options, take a look at the jQuery or MooTools docs.

Drop Options

Drop options are treated by jsPlumb in the same way as drag options - they are passed through to the underlying library. MooTools does not have drop options like jQuery does; droppable functionality in MooTools is actually implemented by the Drag.Move class - the one used to initialise a draggable. But when you setup an Endpoint in jsPlumb you should ignore that fact, and treat droppables like you would in jQuery. jsPlumb wires everything up for you under the hood.

There are two jQuery droppable options that jsPlumb treats as shortcuts in MooTools:

For more information about drop options when using jQuery, see here.

Scope

jsPlumb borrowed the concept of 'scope' from jQuery's drag/drop implementation: the notion of which draggables can be dropped on which droppables. In jsPlumb you can provide a 'scope' entry in the dragOptions and dropOptions you provide when creating an Endpoint. Here's the example grey Endpoint example with 'scope' added:
var exampleGreyEndpointOptions = {
	endpoint:new jsPlumb.Endpoints.Rectangle(),
	style:{ width:25, height:21, fillStyle:'#666' },
	isSource:true,
	connectionStyle : { strokeStyle:"#666" },
	isTarget:true,
	scope:'exampleGreyConnection'
};
If you do not provide a 'scope' entry, jsPlumb uses a default scope. Its value is accessible through this method:
jsPlumb.getDefaultScope();
If you want to change it for some reason you can do so with this method:
jsPlumb.setDefaultScope("mySpecialDefaultScope");
You can also, should you want to, provide the scope value separately on the drag/drop options, like this:
var exampleGreyEndpointOptions = {
	endpoint:new jsPlumb.Endpoints.Rectangle(),
	style:{ width:25, height:21, fillStyle:'#666' },
	isSource:true,
	connectionStyle : { strokeStyle:"#666" },
	isTarget:true,
	dragOptions:{scope:'dragScope'},
	dropOptions:{scope:'dropScope'}
};

Multiple jsPlumb instances

jsPlumb is registered on the browser's Window by default, providing one static instance for the whole page to use. Should you need to, though, you can instantiate independent instances of jsPlumb, using the getInstance method, for example:
var firstInstance = jsPlumb.getInstance();
The variable 'firstInstance' can now be treated exactly as you would treat the 'jsPlumb' variable - you can set defaults, call the connect method, whatever:
firstInstance.Defaults.Connector = new jsPlumb.Connectors.Bezier(150);
firstInstance.Defaults.Container = "container1";
firstInstance.Defaults.Anchors = [jsPlumb.Anchors.TopCenter, jsPlumb.Anchors.BottomCenter];

firstInstance.connect({source:'element1', target:'element2', scope:'someScope'});
getInstance optionally takes an object that provides the defaults:
var secondInstance = jsPlumb.getInstance({
	PaintStyle:{lineWidth:3, strokeStyle:color3},
	Connector:new jsPlumb.Connectors.Bezier(30),
	Endpoint:new jsPlumb.Endpoints.Dot({radius:5}),
	EndpointStyle : { fillStyle: color3  },
	Anchor : jsPlumb.makeAnchor(0.5,0.5,1,1),
	Container:"container2"
});

secondInstance.connect({source:'element4', target:'element3', scope:'someScope'});
Notice the container directives that are set on the defaults. This tells jsPlumb to draw everything inside the container with the given id, giving you cleaner separation between instances. While not actually required in order to make multiple instances work together, you might find it easier. Using this concept you can, for example, drag an entire drawing area around as one.

Automatic Repaint

jsPlumb attaches a listener to the browser window and automatically repaints every connection when a window resize event occurs. You can disable this functionality, if you want to, with the following call:
jsPlumb.setAutomaticRepaint(false);
You can also provide your own function for jsPlumb to execute instead of its default behaviour:
var repaint = function() {
	// do some things, perhaps, and then...
	jsPlumb.repaintEverything();
};

jsPlumb.setRepaintFunction(repaint);
Notice the call to repaintEverything() here - a useful method.

Another example"

var repaint = function() {
	// completely start over
	jsPlumb.detachEverything();
	// paint all your connections
};

jsPlumb.setRepaintFunction(repaint);

Unloading jsPlumb

jsPlumb offers a method you can call when your page is unloading. You should do this to insure against memory leaks. You configure it like this:
<body onunload="jsPlumb.unload();">

...

</body>

jsPlumb.connect Options

These are the options you can specify on a call to the connect/plumb method:

Defaults

The easiest way to set a look and feel for your plumbing is to override the defaults that jsPlumb uses. If you do not do this you are forced to provide your overridden values on every call. Every argument to the plumb method has an associated default value in jsPlumb.

The defaults that ship with jsPlumb are stored in jsPlumb.Defaults, which is a Javascript object. Valid entries, and their initial values, are:
PaintStyle : { lineWidth : 10, strokeStyle : "red" }
DragOptions : { }
EndpointStyle : { fillStyle : null; }
EndpointStyles : [ null, null ]
Anchors : [ jsPlumb.Anchors.BottomCenter, jsPlumb.Anchors.TopCenter ]
Connector : jsPlumb.Connectors.Bezier;
Endpoint : jsPlumb.Endpoints.Dot;
Endpoints : [jsPlumb.Endpoints.Dot, jsPlumb.Endpoints.Dot];

Note that in EndpointStyle, the default fillStyle is 'null'. This instructs jsPlumb to use the strokeStyle from the attached connector to fill the endpoint.

Note also that you can specify either or both (or neither) of 'EndpointStyle' and 'EndpointStyles'. This allows you to specify a different end point for each end of a connection. 'Endpoint' and 'Endpoints' use the same concept. jsPlumb will look first in the individual endpoint/endpoint style arrays, and then fall back to the single default version.

you can override these defaults by including this in a script somewhere:
jsPlumb.Defaults.PaintStyle = {
	lineWidth:13,
	strokeStyle: 'rgba(200,0,0,100)'
}

jsPlumb.Defaults.DragOptions = { cursor: 'crosshair' };

jsPlumb.Default.Endpoints = [ new jsPlumb.Endpoints.Dot(7), new jsPlumb.Endpoints.Dot(11) ]

jsPlumb.Defaults.EndpointStyles = [{ fillStyle:'#225588' }, { fillStyle:'#558822' }];
after the jsPlumb script has been loaded of course! Here we have specified the following default behaviour:

Anchors

An Anchor models the notion of where on an element a plumb line should connect. jsPlumb has nine default anchor locations you can use to specify where the plumb lines connect to elements: these are the four corners of an element, the center of the element, and the midpoint of each edge of the element.

You can provide your own anchor locations if you need to. jsPlumb supports two ways of doing this:

Connectors

Connectors are the lines that actually join elements of the UI. jsPlumb has two connector implementations - a straight line and a Bezier curve. The default connector is the Bezier curve.

jsPlumb attaches the CSS class _jsPlumb_connector to Connectors that it generates.

Bezier Connector

The Bezier Connector provides a Bezier path between the two endpoints. You construct one like this:

var myConnector = new jsPlumb.Connectors.Bezier(curviness);

curviness, which is optional (and defaults to 150), defines the distance in pixels that the Bezier's control points are situated from the anchor points. This does not mean that your connector will pass through a point at this distance from your curve. It is a hint to how you want the curve to travel. Rather than discuss Bezier curves at length here, because they are a very complex topic, we refer you to Wikipedia.

Straight Connector

The Straight Connector draws a straight line between the two endpoints. You construct one like this:

var myConnector = new jsPlumb.Connectors.Straight();

Custom Connectors

You can provide your own connectors if you need to. A Connector consists of two functions, which work as a pair. First a call is made to the compute function:
this.compute = function(sourcePos, targetPos, sourceAnchor, targetAnchor, lineWidth) {
	...
	return dimensions;
}
which is expected to return a list that the paint function can make sense of. The first four entries in the list must be the [x,y,width,height] values for the canvas that the connector will be drawn on; jsPlumb will use this information to size the canvas prior to calling the Connector's paint function. Therefore it is the Connector's responsibility to ensure that the returned dimensions describe a large enough space for the line that will be drawn on it.

The next four elements must be the coordinates of the two endpoints of the line you are going to draw.

The remainder of the items in the returned list are arbitrary, and will vary between Connector implementations; this list is passed in to a Connector's paint function, so each implementation will put into the list whatever it needs to paint itself. For instance, the straight line connector only needs the [x,y] location of each end of the line it will paint, and that is one of the required entries, so it does not have to do anything extra, whereas the Bezier connector adds the location of the two control points. Other types of Connectors will do whatever is appropriate for their particular situation.

This is the method signature for the paint function:
this.paint = function(dimensions, ctx) { .. }
here, the 'dimensions' argument to the 'paint' function is the return value of the 'compute' function. The 'ctx' argument is the Canvas context; you will do all your drawing on this.

To change the connector from the default, specify it in your connect call:
jsPlumb.connect({source:'someWindow', target:'otherWindow', connector:new jsPlumb.Connectors.Straight()});

Endpoints

An Endpoint is the UI component that marks the location of an Anchor, ie. the place where a Connector joins an element. jsPlumb comes with three Endpoint implementations - Dot, Rectangle and Image.

To create your own Endpoint implementation, you need to implement a single method:

paint : function(anchorPoint, orientation, canvas, endpointStyle, connectorPaintStyle) { ... }
The arguments to this method are as follows:

It is your responsibility to size and locate the canvas to suit your needs. jsPlumb provides the following helper method to assist you:

jsPlumb.sizeCanvas(canvas, x, y, width, height);
Allows you to locate the canvas on screen and to size it.

Gradients

The Canvas element supports gradients, and jsPlumb can take advantage of this when painting your Connectors and/or Endpoints. Note: this does NOT WORK in IE, because we use ExplorerCanvas in IE and ExplorerCanvas does not support gradients.

There are two types of gradients available in Canvas - a 'linear' gradient, which consists of colored lines all going in one direction, and a 'radial' gradient, which consists of colored circles emanating from one circle to another. Because of their basic shape, jsPlumb supports only linear gradients for Connectors. But for Endpoints, jsPlumb supports both linear and radial gradients.

Connector gradients

To specify a linear gradient to use in a Connector, you must add a gradient object to your Connector's paintStyle, for instance:
jsPlumb.connect({
	source : 'window2',
	target : 'window3',
	paintStyle:{
		gradient:{
			stops:[[0,'green'], [1,'red']]
		},
		lineWidth:15
	}
});
Here we have connected window2 to window3 with a 15 pixel wide connector that has a gradient from green to red.

Notice the gradient object and the stops list inside it - the gradient consists of an arbitrary number of these "color stops". Each color stop is comprised of two values - [position, color]. Position must be a decimal value between 0 and 1 (inclusive), and indicates where the color stop is situated as a fraction of the length of the entire gradient. Valid values for the colors in the stops list are the same as those that are valid for strokeStyle when describing a color.

As mentioned, the stops list can hold an arbitrary number of entries. Here's an example of a gradient that goes from red to blue to green, and back again through blue to red:

jsPlumb.connect({
	source : 'window2',
	target : 'window3',
	paintStyle : {
		gradient:{
			stops:[[0,'red'], [0.33,'blue'], [0.66,'green'], [0.33,'blue'], [1,'red']]
		},
		lineWidth : 15
	}
});
Note: jsPlumb uses ExplorerCanvas for IE, which does not support gradients. On IE, jsPlumb will simply ignore the gradient directive so it is best to ensure you also supply a strokeStyle in your paintStyle object, to give jsPlumb something to fall back on. If you do not supply a strokeStyle your Connectors will be painted black. The previous example might look like this, for instance:
jsPlumb.connect({
	source : 'window2',
	target : 'window3',
	paintStyle:{
		strokeStyle:'red',
		gradient:{
			stops:[[0,'red'], [0.33,'blue'], [0.66,'green'], [0.33,'blue'], [1,'red']]
		},
		lineWidth:15
	}
});
Notice the strokeStyle:'red' directive at the beginning of the parameter list in paintStyle.

Endpoint gradients

Endpoint gradients are specified using the same syntax as Connector gradients. You put the gradient specifier either in the endpoint member, or if you are specifying different Endpoints for each end of the Connector, in one or both of the values in the endpoints array. Also, this information applies to the case that you are creating standalone Endpoints that you will be configuring for drag and drop creation of new Connections.

This is an example of an Endpoint gradient that is different for each Endpoint in the Connector. This comes from the main demo; it is the Connector joining Window 2 to Window 3:

var w23Stroke = 'rgb(189,11,11)';
jsPlumb.connect({
	source : 'window2',
	target : 'window3',
	paintStyle:{
		lineWidth:8,
		strokeStyle:w23Stroke
	},
 	anchors:[ jsPlumb.makeAnchor(0.3,1,0,1), jsPlumb.Anchors.TopCenter ],
 	endpoint:new jsPlumb.Endpoints.Rectangle(),
 	endpointStyles:[
 		{ gradient : {stops:[[0, w23Stroke], [1, '#558822']] } },
    	{ gradient : {stops:[[0, w23Stroke], [1, '#882255']] } }
    ]
});
The first entry in the gradient will be the one that is on the Connector end of the Endpoint. You can of course have as many color stops as you want in this gradient, just like with Connector gradients.
Applying the gradient in Endpoints
Only the Dot and Rectangle endpoints honour the presence of a gradient (and, remember, not in IE). The Image endpoint of course ignores a gradient as it does no painting of its own.

The type of gradient you will see depends on the Endpoint type:

Animation

jsPlumb offers an 'animate' function, which wraps the underlying animation engine for whichever library you happen to be using and inserts a callback for jsPlumb to repaint whatever it needs to at each step. You could of course do this yourself; it's a convenience method really.

The method signature is:

jsPlumb.animate : function(el, properties, options) 
The arguments are as follows:

CSS Class Reference

jsPlumb attaches classes to each of the UI components it creates:
componentcss class
connector_jsPlumb_connector
endpoint_jsPlumb_endpoint
You would typically use these to establish appropriate z-indices for your UI.

Basic Examples

These examples are all for creating a static interface, ie. one in which you cannot drag to create new Connections. See Draggable Connections Examples if that's what you're looking for.

The basic syntax of a call is that you execute 'connect', providing a source and a target, and optionally a paintStyle and preferences for where you want the plumbing to be anchored on each element, as well as the type of connector to use. Note that in all of the following examples, if you are using jQuery, you can substitute jsPlumb.connect with $('#someElement').plumb, where 'someElement' is the id of the element you would pass as 'source' to the connect call.

Draggable Connections Examples

This is a list of examples of how to use jsPlumb to create Connections using drag and drop.

The basic procedure is:

  1. Create Endpoints and register them on elements in your UI
  2. Drag and Drop
That's all there is to it. Of course there are plenty of options you can set when doing this...it will be easier to show you some examples:

Retrieving Connection Information

jsPlumb offers one fairly versatile method - getConnections - to retrieve information about the currently managed connections.

Before you use this method you should understand jsPlumb's notion of 'scope' - documentation is here

getConnections optionally takes an object specifying filter parameters, of which there are three:

Each of these three parameters may be supplied as a string, or a list of strings - see the examples below.

The return value of a call to getConnection is a dictionary whose keys are scope names, and whose values are lists of sourceId/targetId pairs, for example:

{
	"_jsPlumb_DefaultScope" : [
		{sourceId:"window1", targetId:"window2"},
		{sourceId:"window5", targetId:"window3"}
	],
	"someCustomScope": [
		{sourceId:"window6", targetId:"window2"},
		{sourceId:"window4", targetId:"window13"},
		{sourceId:"window2", targetId:"window10"}
	]
}

The following examples show the various ways you can call this method: Note that the return value is always a dictionary and not an array, even if you specified a single scope in the getConnections call. So you always have to get the array you need by looking it up in the dictionary:
var c = jsPlumb.getConnections({scope:"myScope", source:"mySourceElement"});
var conns = c["myScope"];  
The array may be null. If you have not registered any connections with that scope, it will be. Code defensively!

Advanced: jsPlumb internals

Which files are which?

In development, jsPlumb is broken up into three main scripts: These three files are packaged together to form the scripts that people use, for example:

Pluggable Library Support

Out of the box, jsPlumb can be run on top of jQuery or MooTools. This is achieved by delegating several core methods - tasks such as finding an element by id, finding an element's position or dimensions, initialising a draggable, etc - to the library in question.

To develop one of these, your test page should include the first two scripts discussed above, and then your own script containing your library specific functionality. The two existing implementations should be documented well enough for you to create your own. If you do this, it would be great to share it with everyone...