How To Write jQuery Plugins

By: Ryan Kienstra on: February 7, 2015  in: JavaScript

Write jQuery PluginsYou’ve written complex jQuery code.

And you’d like it to be clearer, or more flexible.

Maybe you’ve heard how easy it is to extend jQuery.

Here’s why and how to write jQuery plugins.

Why Write jQuery Plugins?

1. Use 1 less argument

jQuery plugins could be plain functions.

But they’d have to take a jQuery collection as an argument.

2. No naming collision

jQuery plugins are methods attached to jQuery.

So they won’t pullute the global namespace.

3. Method chaining

jQuery code often uses method chaining.

By creating a plugin, you can call methods one after another.

jQuery( '.bar-selector' ).myPlugin()
                         .show() 
                         .myOtherPlugin();

What is a jQuery Plugin?

A method that a jQuery collection can use.

jQuery( '.foo-selector' ).myNewPlugin();

It works like other methods, like .css or .attr.

It operates on the collection that calls it.

myNewPlugin() operates on the collection jQuery( '.foo-selector' ).

Example Problem

In my Adapter Widget Rows WordPress plugin, I needed a complicated function.

I had to take a collection of widgets, reorder them, and insert them before an item.

The function’s arguments were:

  • The widget collection
  • The new order
  • Where to put them

The function was:

awrInsertInGivenOrderBeforeElement( widgets , order , element );

But 3 arguments are too many.

Solution: Write a jQuery Plugin

Here’s the function as a plugin. $widgets is a jQuery collection.

$widgets.awrInsertInGivenOrderBeforeElement( order , element );

The plugin is easier to understand.

Because there are only two arguments, you know what the plugin does.

The name suggests the arguments: awrInsertInGivenOrderBeforeElement

  • InsertInGivenOrder suggests the first argument, order
  • BeforeElement suggests the second argument, element

How To Write jQuery Plugins

Wrap the plugin definition in a module. This will ensure that $ is jQuery.

( function( $ ) {
      // plugin definition
      
} )( jQuery )

You might read more about this in my guide to JavaScript Modules for WordPress.

If your file is already wrapped in a module, there’s no need to create a new one.

Here’s the plugin:

// module wrapper
( function( $ ) {

        // plugin definition
        $.fn.awrInsertInGivenOrderBeforeElement = function( order , element ) {
	        var index , widgetId , $elementToInsert ,
	            widgets = [];

	        for ( index in order ) {
		        widgetId = order[ index ];
		        $elementToInsert = this.filter( '[id=customize-control-widget_' + widgetId + ']' );
		        widgets.push( $elementToInsert.detach() );
	        }

	        widgets.map( function( widget , index ) {
		        widget.insertBefore( element );
	        } );

                return this;
        };

// end of module wrapper
} )( jQuery )

(See the entire file on GitHub)

To write a jQuery plugin, start with $.fn. followed by the name of the plugin.

$.fn.awrInsertInGivenOrderBeforeElement

Then, assign a function to it.

$.fn.awrInsertInGivenOrderBeforeElement = function( order , element ) {

Access the collection from within the function by using this.

$elementToInsert = this.filter( // omitted

End the plugin with return this;

Returning this allows method chaining.

To use the plugin:

jQuery( '.foo-selector' ).awrInsertInGivenOrderBeforeElement( order , element );

More jQuery Plugin Examples

Conclusion

Consider writing jQuery plugins instead of complex stand-alone functions.

Your code will be clearer.

And you can chain methods.

Do you have functions that could be converted to plugins?

Are you having any challenges in writing jQuery plugins?

Leave a comment below.

  • This field is for validation purposes and should be left unchanged.

Leave a comment

Get Free Updates

  • This field is for validation purposes and should be left unchanged.