Today I am gonna discuss about the Jquery Plugins .
How to write Jquery plugins
Still you are wondering how to write JQuery Plugins you can go through
JQuery website for Plugins
http://docs.jquery.com/Plugins/Authoring
Above documentation will be useful but I just want to make it Easy the
plug in structure
Plugin structure as followes
Step1:
() (jQuery)
Step2 :
(function($){
}) (jQuery)
Step3:
//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);
Step 4:
(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);
Step 5:
Now you have learnt the plugin structure. The following is the plugin I
created based on my previous tutorial. I have successfull convert the
standard jQuery script to a plugin that accepts 4 configurations:
animatePadding : Set the padding value for the animate effect
defaultPadding : Set the default padding value
evenColor : Set the color this color if index value is even number
oddColor : Set the color this color if index value is odd number
(function($){
$.fn.extend({
//plugin name - animatemenu
animateMenu: function(options) {
//Settings list and the default values
var defaults = {
animatePadding: 60,
defaultPadding: 10,
evenColor: '#ccc',
oddColor: '#eee'
};
var options = $.extend(defaults, options);
return this.each(function() {
var o =options;
//Assign current element to variable, in this case is UL
element
var obj = $(this);
//Get all LI in the UL
var items = $("li", obj);
//Change the color according to odd and even rows
$("li:even", obj).css('background-color',
o.evenColor);
$("li:odd", obj).css('background-color',
o.oddColor);
//Attach mouseover and mouseout event to the LI
items.mouseover(function() {
$(this).animate({paddingLeft: o.animatePadding}, 300);
}).mouseout(function() {
$(this).animate({paddingLeft: o.defaultPadding}, 300);
});
});
}
});
})(jQuery);
Here is sample Code that do menu animation
|
Comments