How to create a jQuery function (a new jQuery method or plugin)?
From the Docs:
(function( $ ){
$.fn.myfunction = function() {
alert('hello world');
return this;
};
})( jQuery );
Then you do
$('#my_div').myfunction();
How to create a jQuery plugin with methods?
According to the jQuery Plugin Authoring page (http://docs.jquery.com/Plugins/Authoring), it's best not to muddy up the jQuery and jQuery.fn namespaces. They suggest this method:
(function( $ ){
var methods = {
init : function(options) {
},
show : function( ) { },// IS
hide : function( ) { },// GOOD
update : function( content ) { }// !!!
};
$.fn.tooltip = function(methodOrOptions) {
if ( methods[methodOrOptions] ) {
return methods[ methodOrOptions ].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof methodOrOptions === 'object' || ! methodOrOptions ) {
// Default to "init"
return methods.init.apply( this, arguments );
} else {
$.error( 'Method ' + methodOrOptions + ' does not exist on jQuery.tooltip' );
}
};
})( jQuery );
Basically you store your functions in an array (scoped to the wrapping function) and check for an entry if the parameter passed is a string, reverting to a default method ("init" here) if the parameter is an object (or null).
Then you can call the methods like so...
$('div').tooltip(); // calls the init method
$('div').tooltip({ // calls the init method
foo : 'bar'
});
$('div').tooltip('hide'); // calls the hide method
$('div').tooltip('update', 'This is the new tooltip content!'); // calls the update method
Javascripts "arguments" variable is an array of all the arguments passed so it works with arbitrary lengths of function parameters.
How can we add our custom function in jquery?
If you are attempting to define a function at jQuery
, or jQuery alias $
use $
without .fn
, which attaches function to an object or selector chained to jQuery()
call.
function myFunction() { alert("test");}
jQuery.myFunction = myFunction;
jQuery.myFunction(); // called on `jQuery` object
jQuery.fn.myFunction = myFunction;
jQuery({}).myFunction(); // `$.fn` chained to `jQuery()` call
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
How to create simple jQuery plugin?
For plugin authoring try this way, much more solid:
Edit:
Here is working jsFiddle example.
PLUGIN:
(function($){
$.fn.extend({
YourPluginName: function(options) {
var defaults = {
howMuch:'600',
animation: '',//users can set/change these values
speed: 444,
etc: ''
}
};
options = $.extend(defaults, options);
return this.each(function() {
var $this = $(this);
var button = $('a', $this);// this represents all the 'a' selectors;
// inside user's plugin definition.
button.click(function() {
$this.animate({'top':options.howMuch});//calls options howMuch value
});
});
})(jQuery);
USER'S DOCUMENT:
$(function() {
$('#plugin').YourPluginName({
howMuch:'1000' //you can give chance users to set their options for plugins
});
});
<div id="plugin">
<a>1</a>
<a>2</a>
<a>3</a>
</div>
creating a jquery plugin with multiple functions
If you look at the design of some of the other jQuery plugins and jQuery UI, what they do is they have a single function $('#div').myplugin({options})
, and then they can do different functions by passing a string instead of an object $('#div').myplugin('performdifferenttask')
which can in turn call a helper function that is hidden from the user.
For an example look at http://jqueryui.com/demos/progressbar/#methods
Here is an example that will hopefully alleviate your confusion:
(function($) {
$.fn.myplugin = function(options) {
if(options == 'function1')
function1();
else if(options == 'function2')
function2();
else {
//do default action
}
}
function function1() {
//do something
}
function function2() {
//do something else
}
}
Then in use:
$.myplugin({option1: 4, option2: 6}); //does default behavior
$.myplugin('function1'); //calls function1()
$.myplugin('function2'); //calls function2()
How to add public method to jQuery plugin based on this jQuery plugin pattern
There is multiple way to do this, but the one I prefer is like that :
$.fn.extend({
pluginName: function( options ) {
this.defaultOptions = {};
var settings = $.extend({}, this.defaultOptions, options);
return this.each(function() {
var $this = $(this);
//Create a new Object in the data.
$this.data('pluginName', new pluginMethods($this)) //pluginMethod are define below
});
}
});
function pluginMethods($el){
//Keep reference to the jQuery element
this.$el = $el;
//You can define all variable shared between functions here with the keyword `this`
}
$.extend(pluginMethods.prototype, {
//Here all you methods
redFont : function(){
//Simply changing the font color
this.$el.css('color', 'red')
}
})
$('#el').pluginName();
//Public method:
var instance = jQuery('#el').data('pluginName');
instance.redFont();
The disadvantage with that is pluginMethods is accessible by everyone. But you can solve that by moving it in the same closure that the plugin declaration like that :
(function($){
$.fn.extend({
pluginName: function( options ) {
this.defaultOptions = {};
var settings = $.extend({}, this.defaultOptions, options);
return this.each(function() {
var $this = $(this);
$this.data('pluginName', new pluginMethods($this))
});
}
});
function pluginMethods($el){
//Keep reference to the jQuery element
this.$el = $el;
}
$.extend(pluginMethods.prototype, {
//Here all you methods
redFont : function(){
this.$el.css('color', 'red')
}
})
})(jQuery);
Related Topics
Chrome, JavaScript, Window.Open in New Tab
Failed to Execute 'Postmessage' on 'Domwindow': Https://Www.Youtube.Com !== Http://Localhost:9000
Removing an Anonymous Event Listener
How to Watch for Array Changes
JSON.Stringify Doesn't Work with Normal JavaScript Array
Jquery Disable Form Submit on Enter
Onclick Function Runs Automatically
Why Is Requestanimationframe Better Than Setinterval or Settimeout
Vanilla JavaScript Event Delegation
Find and Remove Objects in an Array Based on a Key Value in JavaScript
Unexpected Behavior Using Array Map on an Array Initialized with Array Fill
Prototype Based VS. Class Based Inheritance
Get Time Difference Between Two Dates in Seconds
What Is the Instanceof Operator in JavaScript
What's the Difference Between Window.Location= and Window.Location.Replace()