Main Structure //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); |
Example: The animateMenu Plugin * 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); |
#$(document).ready(function() {
# $('#menu').animateMenu({animatePadding: 30, defaultPadding:10});
#});
# ul id="menu"
# li>Home
# li>Posts
# li>About
# li>Contact
# ul
Ref link: http://www.queness.com/post/112/a-really-simple-jquery-plugin-tutorial
No comments:
Post a Comment