Getting started with jsPlumb


The ori­ginal art­icle was pub­lished on 13 January 2013. It has been updated on 14 August 2014 to reflect the new­est ver­sions of jsPlumb and jQuery.

When you need to cre­ate schem­at­ics or dia­grams in your webap­plic­a­tion, or have your user cre­ate these, jsPlumb is a won­der­ful lib­rary to use. An example of a use case for some­thing like this is hav­ing the user cre­ate a flow dia­gram for a pro­cess he or she is modeling.

The jsPlumb-website has some great demos and a lot of doc­u­ment­a­tion. An easy guide to get star­ted is, how­ever, not avail­able. This art­icle will get you up and run­ning with jsPlumb in no time!

Setting up

You can choose to use jsPlumb with either jQuery, MooTools or YUI3. In this art­icle, we will use jQuery. When using jQuery, the jQuery UI lib­rary is also needed. 

We will use the fol­low­ing HTML to get star­ted. You can copy and paste this to test it on your own sys­tem. Make sure to alter the JavaScript-links to point to the cor­rect files.

It is import­ant to make sure that every div has a unique id. The id is used by jsPlumb to identify the parts that need to be connected.

We will add a bit of styl­ing to the doc­u­ment, so that our divs are vis­ible and we can do stuff with them.

Adding some plumbing

Now that we have our start­ing point com­pletely set up, we can add some jsPlumb fan­ci­ness to it. jsPlumb offers a method that is invoked as soon as the jsPlumb lib­rary has fin­ished load­ing. We will wrap everything we do in this function.

To con­nect our divs, we use jsPlumb’s makeSource and makeTarget func­tions. These allow you to turn any ele­ment into a source or a tar­get for a connection. 

As you can see, you can very eas­ily select which items to turn into a source or a tar­get by using the selector from jQuery.

The meth­ods makeSource and makeTarget take para­met­ers that you can use to cus­tom­ise the con­nect­ors. In this case, we have selec­ted a type of con­nector and a type of anchor.

Try this code and con­nect the divs to each other! We now have a decent start­ing point for work­ing with jsPlumb. In the next art­icle, we will look at jsPlumb in a bit more detail. We will cus­tom­ise some of the set­tings, and we will also make our divs drag­gable, so that they can be laid out by the user.

Download code

Download the code for this example from GitHub

All articles about jsPlumb

Further reading

After read­ing this art­icle, head over to the jsPlumb demos to see what this frame­work can do. There is a lot more than we have seen in this art­icle! Head over to the doc­u­ment­a­tion to have a look at how some of the other things work.