jquery-plugin

Overview

JQuery offers a very practical and easy way to build plugins, as well as a very good documentation on this subject. However, it could be useful to see how a plugin is written step-by-step.

Basic Structure

The basis of creating a plugin for jQuery is actually quite simple. You don’t have to be a jQuery ninja, nor do you have to sweat blood to make it work. It’s as easy as script writing!

Following the jQuery plugin authoring guidelines is a good idea. Bear in mind that 1) plugins files should be named jquery.PLUGINNAME.js and 2) always attach your plugins to jQuery instead of $, so aliases can be easily set using the noConflict() method.

The structure required to extend the jQuery.fn object is…

jQuery.fn.firstPlugin = function () {
return this.each (function () {
alert (this.id);
});
}

You’d now be able to call your plugin as you normally would call any other plugin

$('#test').firstPlugin ();

This would display a “nice” alert box showing the element id.

One Step Further: Parameters

Ok, I agree the above example was a bit lame, so let’s find out how a more complex plugin can be developed. You can code your plugin to require some parameters and accept other options as well. If your plugin needs two numbers, you could write it in the following way:

jQuery.fn.secondPlugin = function (number1, number2, options) {
myoptions = jQuery.extend ({
operation: "sum",
label: "The result is"
}, options);
 
$(this).html (myoptions.label + " (" + myoptions.operation + ")" + myoptions.number1+myoptions.number2);
}

In the above code, check out the way we provide default settings in case the two strings are not passed to the plugin function. This way we can call either

$('#test').secondPlugin (1, 2);

to get

<span id="test The result is (sum) 3</span>

or

$('#test').secondPlugin (1, 2, { operation: "sums two numbers together", label: "We got" });

if you prefer

<span id="test We got (sums two numbers together) 3</span>

The jQuery Object: Custom Functions and Selectors

Until now, we’ve messed with the jQuery.fn object, which is responsible for elements interaction, and we never mentioned the jQuery object itself, which handles internal processing. By extending it, we are thus allowed to create our own functions and even selectors for others to use! Here’s how new methods can be added:

jQuery.fn.extend ({
myFirstFunction : function () { alert ("first function") },
thisIsTheSecond : function (message) { alert ("2nd: "+ message) }
});

and then called without any problems

$.myFirstFunction ();
$.thisIsTheSecond ("hello");

In a very similar fashion you can create your own selectors, provided they don’t exist yet.

jQuery.expr[":"].startsWith = function (element, index, tokens) { 
if (!tokens[3]) return false;
return eval ("/^[/s]*" + tokens[3] + "/i").test ($(element).text());
};

As you can see, the function takes three arguments, being: 1) the matched element, 2) the index of the element and 3) an object that contains parse tokens; the first element of the array is the full filter string (including parameters), the second one is the “:”, the third one is the filter name and, finally, the fourth is the parameter.

You should always check whether the parameter has been passed or not, since the filter could stop working in the latter case.

Wrapping It Up

These are some tips to get you started writing your own jQuery plugins. It’s only by diving in that you’ll fully learn all the things you can do.

About the Author

Keen on geeky stuff, I tried everything from rocketry to weird game development adventures more than once. I love orange-colored things. I'd be a web developer with a passion for design but I find myself writing for some websites every now and then.

Visit Website

Join the discussion!

16 responses thus far

  1. Luis Lopez

    August 10, 2009

    Great tips, I’ll try my self but I am not really sure how is gonna finish, I am not eh best on Jquery but if I have any problem I will be here, looking for answers.
    .-= Luis Lopez´s last blog ..50+ Awesome Photos You Have Never Seen From Bogota – Colombia =-.

  2. web2000

    August 11, 2009

    Hey, thanks for posting this.. I will definitely be looking more into creating my own jquery plugins in the near future

  3. Bendesign

    August 11, 2009

    Thanks for posting this. Jquery plugins are very interesting. i have to read more about that.

  4. kurtopia

    August 14, 2009

    Thanks i learned a lot,

  5. Jeremy

    August 17, 2009

    Fifth! Good stuff here, this is a good primer. I’ll repost after I build a plugin.

  6. Polprav

    October 22, 2009

    Hello from Russia!
    Can I quote a post in your blog with the link to you?

  7. Andrew Houle

    October 23, 2009

    @Polprav – Sure, as long as you link back that would be perfectly fine, thanks for asking.

  8. Stanley

    November 6, 2009

    hey, I didn’t know where to contact you but your layout design looked rearranged on firefox and internet explorer. Anyways, i just suscribd to your rss.

  9. Statistics Homework Help

    November 12, 2009

    I was very pleased to find this site. I wanted to thank you for this great read!!

  10. Alaa Al-Hussein

    January 17, 2010

    I have problem with “this”

    When defining a plugin as $.fn.myPlugin
    then passing HTML element into it as follows:
    $(“#myElementID”).myPlugin

    How can I handle the html element? is it by using “this”?
    it didn’t work for me.

    Thanks

  11. Praveen

    February 2, 2010

    @Alaa Al-Hussein . You can achieve this if your method signature looks like this:

    (function($){
    $.fn. myPlugin= function() {

    //Do something here

    };
    })(jQuery);

    And call your plugin method same as before:
    $(“#myElementID”).myPlugin();

    And let me know if it helped.

    Thanks,
    Praveen

  12. Praveen

    February 2, 2010

    And also make sure that you have linked original JQuery file in the current page

  13. Javier Dorough

    April 27, 2010

    I enjoy coming back daily to see your musings. I have your page bookmarked on my favorite read list!

  14. Schrumpfschläuche

    April 28, 2010

    Thanks for the work.

  15. Ka0ticstyle

    June 16, 2010

    There is no, myoptions.number1 or .number2. So you would need to change that.
    The line should read:
    $(this).html (myoptions.label + ” (” + myoptions.operation + “)” + (number1+number2));

  16. Casti Moto

    June 21, 2010

    Thanks for the tut, I am starting my own JQ plugin just now, eager to see the outcome.