227

I know that in JavaScript the syntax is as follows:

function myfunction(param){
  //some code
}

Is there a way to declare a function in jQuery that can be added to an element? For example:

$('#my_div').myfunction()
multimediaxp
  • 9,348
  • 13
  • 49
  • 80
  • 7
    @RedEyedMonster - it makes *plenty* of sense. Ever used anything like jQuery datepicker? `$('#myDatePickerfield').datePicker();` – Jamiec Aug 23 '12 at 13:55
  • No I haven't but thanks for alerting me to it :) – Nigel B Aug 23 '12 at 13:58
  • 3
    @RedEyedMonster - You've probably used `$("#someElement").hide()` or `.addClass()`... – nnnnnn Aug 23 '12 at 13:59
  • 1
    @RedEyedMonster: the OP is describing jQuery plugins, which are actually pretty common in JavaScript. See http://docs.jquery.com/Plugins/Authoring – Paul D. Waite Aug 23 '12 at 14:00

14 Answers14

323

From the Docs:

(function( $ ){
   $.fn.myfunction = function() {
      alert('hello world');
      return this;
   }; 
})( jQuery );

Then you do

$('#my_div').myfunction();
Dennis Braga
  • 1,448
  • 3
  • 20
  • 40
Candide
  • 30,469
  • 8
  • 53
  • 60
89

In spite of all the answers you already received, it is worth noting that you do not need to write a plugin to use jQuery in a function. Certainly if it's a simple, one-time function, I believe writing a plugin is overkill. It could be done much more easily by just passing the selector to the function as a parameter. Your code would look something like this:

function myFunction($param) {
   $param.hide();  // or whatever you want to do
   ...
}

myFunction($('#my_div'));

Note that the $ in the variable name $param is not required. It is just a habit of mine to make it easy to remember that that variable contains a jQuery selector. You could just use param as well.

Paul D. Waite
  • 96,640
  • 56
  • 199
  • 270
Pevara
  • 14,242
  • 1
  • 34
  • 47
44

While there is a plethora of documentation / tutorials out there, the simple answer for your question is this:

// to create a jQuery function, you basically just extend the jQuery prototype
// (using the fn alias)

$.fn.myfunction = function () {
    // blah
};

Inside that function, the this variable corresponds to the jQuery wrapped set you called your function on. So something like:

$.fn.myfunction = function () {
    console.log(this.length);
};

$('.foo').myfunction();

... will flush to the console the number of elements with the class foo.

Of course, there is a bit more to semantics than that (as well as best practices, and all that jazz), so make sure you read up on it.

Richard Neil Ilagan
  • 14,627
  • 5
  • 48
  • 66
14

To make a function available on jQuery objects you add it to the jQuery prototype (fn is a shortcut for prototype in jQuery) like this:

jQuery.fn.myFunction = function() {
    // Usually iterate over the items and return for chainability
    // 'this' is the elements returns by the selector
    return this.each(function() { 
         // do something to each item matching the selector
    }
}

This is usually called a jQuery plugin.

Example - http://jsfiddle.net/VwPrm/

Richard Dalton
  • 35,513
  • 6
  • 73
  • 91
10

Yup — what you’re describing is a jQuery plugin.

To write a jQuery plugin, you create a function in JavaScript, and assign it to a property on the object jQuery.fn.

E.g.

jQuery.fn.myfunction = function(param) {
    // Some code
}

Within your plugin function, the this keyword is set to the jQuery object on which your plugin was invoked. So, when you do:

$('#my_div').myfunction()

Then this inside myfunction will be set to the jQuery object returned by $('#my_div').

See http://docs.jquery.com/Plugins/Authoring for the full story.

Paul D. Waite
  • 96,640
  • 56
  • 199
  • 270
9
$(function () {
    //declare function 
    $.fn.myfunction = function () {
        return true;
    };
});

$(document).ready(function () {
    //call function
    $("#my_div").myfunction();
});
JNYRanger
  • 6,829
  • 12
  • 53
  • 81
user1619962
  • 374
  • 2
  • 3
7

You can also use extend (the way you create jQuery plugins):

$.fn.extend(
{
    myfunction: function () 
    {
    },

    myfunction2: function () 
    {
    }
});

Usage:

$('#my_div').myfunction();
Novasol
  • 887
  • 10
  • 17
6

You can write your own jQuery plugins(function which can be called on selected elements) like below:

(function( $ ){
    $.fn.myFunc = function(param1, param2){
        //this - jquery object holds your selected elements
    }
})( jQuery );


Call it later like:

$('div').myFunc(1, null);
Michael
  • 1,067
  • 8
  • 13
4

Yes, methods you apply to elements selected using jquery, are called jquery plugins and there is a good amount of info on authoring within the jquery docs.

Its worth noting that jquery is just javascript, so there is nothing special about a "jquery method".

Jamiec
  • 133,658
  • 13
  • 134
  • 193
  • 1
    _'there is nothing special about a "jquery method"'_ - Yes there is: a "jQuery method" works on a jQuery object. (But yes, jQuery _is_ just JS...) – nnnnnn Aug 23 '12 at 13:57
4

Create a "colorize" method:

$.fn.colorize = function custom_colorize(some_color) {
    this.css('color', some_color);
    return this;
}

Use it:

$('#my_div').colorize('green');

This simple-ish example combines the best of How to Create a Basic Plugin in the jQuery docs, and answers from @Candide, @Michael.

Bob Stein
  • 16,271
  • 10
  • 88
  • 101
3

You can always do this:

jQuery.fn.extend({
   myfunction: function(param){
       // code here
   },
});
OR
jQuery.extend({
   myfunction: function(param){
       // code here
   },
});
$(element).myfunction(param);
2

It sounds like you want to extend the jQuery object via it's prototype (aka write a jQuery plugin). This would mean that every new object created through calling the jQuery function ($(selector/DOM element)) would have this method.

Here is a very simple example:

$.fn.myFunction = function () {
    alert('it works');
};

Demo

jbabey
  • 45,965
  • 12
  • 71
  • 94
1

Simplest example to making any function in jQuery is

jQuery.fn.extend({
    exists: function() { return this.length }
});

if($(selector).exists()){/*do something here*/}
Chintan Thummar
  • 1,462
  • 19
  • 32
0
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Define a function in jQuery</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function() {
    $.fn.myFunction = function() { 
        alert('You have successfully defined your function!'); 
    }
    $(".call-btn").click(function(){
        $.fn.myFunction();
    });
});
</script> 
</head>
<body>
    <button type="button" class="call-btn">Click Here</button>
</body>
</html>
Kamlesh
  • 5,233
  • 39
  • 50