76

What's the easiest way to define a new jQuery member function?

So that I can call something like:

$('#id').applyMyOwnFunc()

6 Answers 6

121

Please see "Defining your own functions in jQuery" by Basil Goldman:

In this post, I want to present how easy define your own functions in jQuery and using them.

Modified, based on the code in the blog post linked above:

jQuery.fn.yourFunctionName = function() {
    // `this` is the jQuery Object on which the yourFunctionName method is called.
    // `arguments` will contain any arguments passed to the yourFunctionName method.
    var firstElement = this[0];

    return this; // Needed for other methods to be able to chain off of yourFunctionName.
};

Just use:

$(element).yourFunctionName();
5
  • 5
    More than that, the article on the other end of that link isn't that great.
    – mkoistinen
    Mar 9, 2013 at 20:50
  • 1
    Yes and no. You should actually make use of the extend() function to be safe... There is an answer by RageZ that gives what I consider the correct answer. Oct 19, 2014 at 11:04
  • 6
    this refers to the jQuery object, in this case its length is 1 because the selector is an ID which should be unique. Then you take the HTMLElement using this[0]. Then you rewrap it in jQuery with $(this[0]). Why?
    – Yeti
    Oct 23, 2015 at 19:44
  • @AlexisWilke Why should you make use of extend to be safe?
    – xr280xr
    Feb 25, 2021 at 5:28
  • 2
    @xr280xr Because over time the interface (how to add new functions) can change. It could break your code when you upgrade to a newer version of jQuery. Feb 25, 2021 at 18:03
35

This is the pattern that I prefer to define my own plugins.

(function($) {

    $.fn.extend({
        myfunc: function(options) {
            options = $.extend( {}, $.MyFunc.defaults, options );

            this.each(function() {
                new $.MyFunc(this,options);
            });
            return this;
        }
    });

    // ctl is the element, options is the set of defaults + user options
    $.MyFunc = function( ctl, options ) {
         ...your function.
    };

    // option defaults
    $.MyFunc.defaults = {
        ...hash of default settings...
    };

})(jQuery);

Applied as:

$('selector').myfunc( { option: value } );
1
  • 2
    I think line 8 should be new $.MyFunc($(this),options);
    – Red Taz
    Aug 20, 2013 at 11:06
19

The jquery documentation has a section on plugin authoring, where I found this example:

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

Then you'd be able to call it this way:

$("div p").debug();
2
  • 1
    what to do if I want to access the new method directly from $ like $.newMethod() not its selector like $("dev").newMethod(), how to accomplish that? May 18, 2020 at 12:22
  • 1
    $.newMethod = function(){ <insert function stuff here> };
    – PRMan
    Jan 20, 2021 at 23:34
15

jQuery has the extend function to do that

jQuery.fn.extend({
  check: function() {
    return this.each(function() { this.checked = true; });
  },
  uncheck: function() {
    return this.each(function() { this.checked = false; });
  }
});

you can see the documentation there

2

Here's a plugin, in it's simplest form...

jQuery.fn.myPlugin = function() {
  // do something here
};

You'll really want to consult the documentation though:

http://docs.jquery.com/Plugins/Authoring

-1
/* This prototype example allows you to remove array from array */

Array.prototype.remove = function(x) {
var i;
for(i in this){
    if(this[i].toString() == x.toString()){
        this.splice(i,1)
    }
  }
 }


----> Now we can use it like this :

var val=10;
myarray.remove(val);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.