Cory Gwin
Cory Gwin

Reputation: 1243

jQuery plugin .fn question

I seem to be having some problems creating a jquery plugin. I am testing a simple plugin in firebug console and the function is not being defined as I would expect. Here is the code pattern I am using

jQuery.fn.test = function () {console.log("runs")}

I am trying to call the function with this call which is not working.

$.test()

But this call does

$.fn.test()

I don't think this is how it is supposed to work so I think I am doing something wrong, although all the documentation seems to agree that I should be correct. Any one have any advice?

Thanks, Cory

Upvotes: 3

Views: 2790

Answers (2)

cletus
cletus

Reputation: 625465

There are two ways of extending jQuery. The one you've chosen allows things like:

$("div").test();

although the code isn't in the correct form for that. To simply add a static method so you can call:

$.test();

do this:

jQuery.test = function() {
  ...
};

See Plugins/Authoring.

Upvotes: 1

Jake Wharton
Jake Wharton

Reputation: 76115

Try $('div').test()!

Give http://docs.jquery.com/Plugins/Authoring a read for a good introduction to jQuery plugins.


Ok here's some additional info while I'm here. When creating a plugin there three near absolute rules:

  • Always use an anonymous method when you define your plugin so you assure you get the jQuery object with $.
  • Always try to return the jQuery object again (for chaining).
  • Always iterate over elements since your selector likely matched more than one element.

So for convention's sake, start off like this:

(function($) {
  $.fn.test = function() {
    return this.each(function() {
      console.log("runs");
    });
  }
})(jQuery);

This will print "runs" for every item matched by your selector (a lot if you use just div). Try putting $(this).css('background-color', 'red'); in and see what happens.

Another good place to look would be various social coding sites (GitHub, BitBucket, Google Code, etc.) and search for "jQuery Plugin" to see how others are doing it.

Upvotes: 3

Related Questions