This is very simple to write our own plug-in. Following is the syntax to create a method:
The guideline recommended by the jQuery team is as follows:
- Any methods or functions you attach must have a semicolon (;) at the end.
- You should use this.each to iterate over the current set of matched elements - it produces clean and compatible code that way.
- Your method must return the jQuery object, unless explicity noted otherwise.
- Prefix the filename with jquery, follow that with the name of the plugin and conclude with .js.
- Always attach the plugin to jQuery directly instead of $, so users can use a custom alias via noConflict() method.
Structure of Plugin
//You need an anonymous function to wrap around your function to avoid conflict
(function($){
//Attach this new method to jQuery
$.fn.extend({
//This is where you write your plugin's name
pluginname: function() {
//Iterate over the current set of matched elements
return this.each(function() {
//code to be inserted here
});
}
});
//pass jQuery to the function,
//So that we will able to use any valid Javascript variable name
//to replace "$" SIGN. But, we'll stick to $ (I like dollar sign: ) )
})(jQuery);
Plugin with options
(function($){
$.fn.extend({
//pass the options variable to the function
pluginname: function(options) {
//Set the default values, use comma to separate the settings, example:
var defaults = {
padding: 20,
mouseOverColor : '#000000',
mouseOutColor : '#ffffff'
}
var options = $.extend(defaults, options);
return this.each(function() {
var o = options;
//code to be inserted here
//you can access the value like this
alert(o.padding);
});
}
});
})(jQuery);








Post a Comment