4

How can I write a plugin/function and then be able to call it like this(no selector required)?

$.function()

now I'm writing my plugins something like this:

(function($){
 $.fn.extend({
 //function name
 myFunction : function(){
 //...........
 }
 });
})(jQuery);
Oualid KTATA
1,11610 silver badges20 bronze badges
asked Oct 24, 2009 at 15:04

2 Answers 2

10

While the "extend" jquery function is the correct way to extend the library, it has two forms.

$.fn.extend which is what you are using in your example is used to add additional functions to actual DOM objects. So for example your "myFunction" function could be used like this if you wanted to take an action on the "document" object in the dom. $(document).myFunction()

To extend the static namespace of jQuery, you need to use the $.extend function instead (note the lack of fn)

(function($){
 $.extend({
 //function name
 myFunction : function(){
 //...........
 }
 });
})(jQuery);

should be what you are looking for.

answered Oct 24, 2009 at 16:06
Sign up to request clarification or add additional context in comments.

Comments

7

Simply like this:

(function($){
 $.myFunction = function(){
 //...........
 }
})(jQuery);

Or just:

jQuery.myFunction = function() { ... };
answered Oct 24, 2009 at 15:07

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.