Why Create a jQuery plugin

Sometimes its is useful to have a piece of functionality available throughout your code. Maybe you want a single function you can call on a jQuery selector that performs a specific action on such selector. Or maybe you wrote a utility function in one of your projects and now you want to be able to move it easily to other projects. In any case writing a plugin is your best option.

jQuery is great. It’s cross-browser, easy to learn, and helps you make very user-friendly interfaces. It also comes with a lot of useful plugins to do almost whatever you want.

But sometimes a lot is not enough, what if you can’t find just the right plugin to suit your needs? Or maybe there exist a plugin but its too large, and you just want part of it. The solution might be to roll up your selves and write your own stuff. After all it sound more complicated than it really is. This short tutorial will go through the process of writing a simple plugin, adding some options, and even perform a callback.

Setting Up

You can download the entire project from GitHub here

For this tutorial, we will be creating a simple accordion plugin. Let’s create a js file and put it in the “js” directory of our website. It’s tradition to start all js plugin’s files with “jquery dot” followed by the actual plugin name, so we’ll call ours “jquery.simple-accordion.js”.

– Our plugin file inside the js directory inside our website directory

Now we need to include our plugin file along with the jQuery library to our main HTML page (index.html). It is best practice to include the jQuery library directly from the the google api servers, since they are distributed across the world instead of your single server location: Closer servers usually means faster response times for the visitor. Another advantage of having jQuery included from Google, is that when a visitor comes to your site they may already have the jQuery script in their local cache. Pre-cached content usually means faster load times for the visitor.

1 2 <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script src="js/jquery.simple-accordion.js"></script>

The jQuery Plugin Structure

jQuery is packed with all the necessary hooks to aid you in the development of our plugin. But is good to keep up the JavaScript good practices, so we must make sure everything is kept inside a local scope. Let’s start with the basic shell of a jQuery plugin:

1 2 3 4 5 6 7 8 9 ( function ( $ ) { $. fn . simpleAccordion = function ( ) { //TODO: code for simple accordion plugin } } ( jQuery ) ) ;

Let’s quickly go through what’s going on here. By including everything in the (function() {}) self-enclosed JavaScript pattern, we’re making sure that all the variables in our plugin will stay safely outside of the global namespace. We don’t to run into conflicts with any other javascript running in this page, so we must isolate our code as we did above.

The other thing you might notice is that we’re defining our plugin as if jQuery was in it’s “no-conflict” mode. Again, we’re seeking to avoid colliding with other JavaScript on the page, and thus we want to make sure that our plugin isn’t reliant on the default $, which could be used by another library.

Finally, $.fn is jQuery’s way of allowing you to define our plugin, which we’ve named simpleAccordion. With all of our pieces in place, let’s get cooking!

Adding Functionalities to Our Plugin

What is great about jQuery is that it lets you use any selector you want. However, you must keep in mind that our plug-in can be dealing with several different element types. Using the “this” keyword lets our plug-in apply the associated functions by accessing each element in a loop regardless of the element type.

Getting The HTML Part Ready – Structuring The Accordion

Since we are building an accordion we are going to need to HMLT structure for it, so here we go:

1 2 3 4 5 6 7 8 9 10 <dl class="accordion" id="my-accordion"> <dt>Heading 1</dt> <dd> Cras dolor elit, porttitor ac diam bibendum, eleifend aliquam erat.</dd> <dt>Heading 2</dt> <dd> Donec blandit risus nec est tristique interdum.</dd> <dt>Heading 3</dt> <dd>Fusce sit amet arcu id justo malesuada faucibus. </dd> <dt>Heading 4</dt> <dd> Aliquam tincidunt lobortis sem at porttitor.</dd> </dl>

This is a simple accordion structure, defining four titles and their respective content areas. So the idea is that our plugin will turn this HTML code into a functional accordion, where an user can open and collapse different sections.

This is how it should look like for now:



Just to make it look pretty we should add some simple styles. So here we go:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 .accordion { width : 600px ; border : 1px solid #ccc ; border-bottom : none ; } .accordion dt , .accordion dd { border-bottom : 1px solid #ccc ; margin : 0px ; } .accordion dt { background : rgba ( 193 , 221 , 252 , 0.24 ) ; cursor : pointer ; padding : 8px 4px ; font-size : 14px ; font-weight : bold ; } .accordion dd { padding : 12px 8px ; }

Now our accordion structure should look like this:



The jQuery Part – Time To Make It Do Something!

To add functionality to our plugin we are going to edit the js file and add the following code:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 ( function ( $ ) { $. fn . simpleAccordion = function ( options ) { return this . each ( function ( ) { var dts = $ ( this ) . children ( 'dt' ) ; dts. click ( accordionClick ) ; dts. each ( reset ) ; } ) ; function accordionClick ( ) { $ ( this ) . siblings ( 'dt' ) . each ( hide ) ; $ ( this ) . next ( ) . slideDown ( 'fast' ) ; return false ; } function hide ( ) { $ ( this ) . next ( ) . slideUp ( 'fast' ) ; } function reset ( ) { $ ( this ) . next ( ) . hide ( ) ; } } } ) ( jQuery ) ;

Quickly let’s go over what this code is doing. First, you need to understand that jQuery is a library that extends the JavaScript language. When creating any jQuery plug-in, you’re essentially extending the jQuery library, which is extending JavaScript. Truly understanding how your plug-in extends the jQuery library requires an understanding of the JavaScript prototype property. Although it is not used directly, the JavaScript prototype property is used behind the scenes through the jQuery property fn, which is a jQuery alias for the native JavaScript prototype property.

So in simpler terms, you extend your plugin from jQuery by using fn.”your-plugin-name”

In addition, we could add options to pass to our plugin. A jQuery plug-in can include defaults and options. Options are arguments that you could pass to your plug-in. Rather than sending several arguments, with a options object you can send multiple properties, which is the standard jQuery practice. When allowing options in your plug-in, it is a best practice to set default options using the defaults object. Like options, defaults are an object literal that should include the properties you are allowing to be passed to your plug-in.

Let’s quickly add some options to our plugin to show how simple this is. We are going to pass an option parameter to open the first section of our accordion when it is first loaded.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ( function ( $ ) { $. fn . simpleAccordion = function ( options ) { var state = $. extend ( { } , { open : false } , options ) ; return this . each ( function ( ) { var dts = $ ( this ) . children ( 'dt' ) ; dts. click ( accordionClick ) ; dts. each ( reset ) ; if ( state. open ) $ ( this ) . children ( 'dt:first-child' ) . next ( ) . show ( ) ; } ) ; function accordionClick ( ) { $ ( this ) . siblings ( 'dt' ) . each ( hide ) ; $ ( this ) . next ( ) . slideDown ( 'fast' ) ; return false ; } function hide ( ) { $ ( this ) . next ( ) . slideUp ( 'fast' ) ; } function reset ( ) { $ ( this ) . next ( ) . hide ( ) ; } } } ) ( jQuery ) ;

If you notice, we are using default value of open:false, so if no option is passed, the plugin will assume that you want your accordion closed when first loaded. When the plug-in receives options, you can rely on the $.extend method to do the actual overriding. What the $.extend method does is that it merges two or more objects.

That’s it!

So there you have it your first jQuery plugin, very simple right. I hope you enjoyed this tutorial, and find it useful. You can download the entire project from GitHub here