HOWTO: Build Your Own jQuery Plugin

Share: Twitter Facebook LinkedIn

jquery tip

After enough time of working with jQuery code and sites, you might start to notice that you have similar jQuery code in a bunch of projects. You always include some scrolling, or animations to various similar link styles, etc.

If only there was some way to create a “library” that you can then just include into all your projects with a single snippet…

Turns out – you can with jQuery Plugins.

jQuery Object Methods

Before we go through the process of creating a plugin, let’s dig a little into how jQuery actually works to begin with.

Let’s look at a small snippet:

1
$(".panel").css("color", "blue");

This is a simple enough sliver of jQuery code. We’re binding to all elements of the class panel and modifying the CSS color attribute to blue. Whenever you use the $ function to select elements, it’s returning a jQuery object. This particular object contains all of the methods that you have been regularly using (eg. .css(), .click(), .show(), .hide(), etc) and all of the elements that fit the given selector.

The jQuery object obtains these methods from the$.fn object. This object contains all of the jQuery object methods, and any other methods from any jQuery plugin that is also being loaded by the site.

In other words, we want to attach any of our own plugin code to the $.fn object so that it’s accessible throughout the site.

Let’s test this out. We can add an object function called bordify:

1
2
3
4
5
6
7
  $.fn.borderify = function() {
    this.attr({ "style": "border: dotted 1px red"});
  };
  
  // then somewhere in our code we can do...
  $("a").borderify();
  

NB: note that to use the .attr() method, we can use this directly, rather then wrapping it with $(this). That is because the borderify function is now a part of the same object as .attr().

Making Chainable

The borderify object function “works”, but there are a few problems if we released this “as is” to the world. One issue is that we internally break the object chaining that the existing jQuery methods support and promote.

For example, it’s not uncommon to link (chain) together 3 or 5 functions onto a single selector.

This is allowed, because almost all of the $.fn object methods return the original jQuery object.

Let’s update our borderify to support proper chaining:

1
2
3
4
5
6
7
8
  $.fn.borderify = function() {
    this.attr({ "style": "border: dotted 1px red"});
    return this;
  };
  
  // then somewhere in our code we can now do...
  $("a").borderify().addClass("notice");
  

Protecting the $

We still have an additional problem. While most JavaScript libraries now avoid ALSO using the $, we are building our code, based on the assumption that $ IS the jQuery $ and NOT a different library.

To make sure our plugin stays properly working within any environment we drop this script into, we need to stick our method into an IIFE (Immidiately Invoked Function Expression) - which is a body of JavaScript that is executed immidiately upon being parsed by the browser JavaScript interpreter.

1
2
3
4
5
6
(function($) {
  $.fn.borderify = function() {
    this.attr({ "style": "border: dotted 1px red"});
    return this;
  };
} (jQuery));

Privacy

We’re on a good track now with our plugin. Because our code is within an IIFE, we can now make use of our own private variables or functions that won’t be exposed outside of this block.

1
2
3
4
5
6
7
8
9
10
11
12
(function($) {
  var border_color = "#6495ed";
  
  function some_other_private_function(a, b) {
     return a + b;
  }
  
  $.fn.borderify = function() {
    this.attr({ "style": "border: dotted 1px " + border_color });
    return this;
  };
} (jQuery));

Staying Safe

It can quickly become tempting to create addition methods within our library, and attach them all to the $.fn object. However, you have to consider (and remember) that your plugin code could be dropped into a site with dozens of other jQuery plugins. All of them appending themselves to the $.fn. As such, there is a possibility that another plugin will try using the same object name as you, which will then override your plugin code with the other plugin.

To be as safe as you can, try to attach only one object function to the $.fn object within your plugin.

Allowing for Options

Depending on the complexity of your plugin, it might be a good idea to allow some customization by accepting an options object. One of the simplest ways is to allow the use of a JavaScript object literal.

Let’s take a look:

1
2
3
4
5
6
7
8
9
10
11
12
(function($) {
  $.fn.borderify = function( options ) {
    var settings = $.extend({
       // These are the defaults
       borderStyle: "dotted",
       borderWidth: "1px",
       borderColor: "#6495ed"
    }, options );
    this.attr({ "style": "border: " + options.borderStyle + " " + borderWidth + " " + border_color });
    return this;
  };
} (jQuery));

That Wraps it Up

This wraps up our simple guide to making your own jQuery plugin. Hopefully it’s sparked some ideas for you. Feel free to let us know what plugin you end up creating! Go for it!

Like what you see? Share it with your friends!

Comments

You are seeing this because your Disqus shortname is not properly set. To configure Disqus, you should edit your _config.yml to include either a disqus.shortname variable.

If you do not wish to use Disqus, override the comments.html partial for this theme.