When creating plugins, itβs very easy to complicate things, so try to keep things beautiful and simple.
I have provided you with TWO strong> tippedOff plugin tippedOff . There is also a jsfiddle demo of both plugins here.
The first uses your source code as it is ( NO SIGNIFICANT CHANGE ):
$.tippedOff = function(selector, settings) { var config = { 'top':0, 'left':0, 'wait':3000 }; if(settings){$.extend(config, settings);} var $elem = $(selector); if($elem.length > 0) { $elem.each(function() { //bind mouseenter, mouseleave, click event $(this).css({"color":"#F00"}) .mouseenter(function(){ $(this).css({"color":"green"}); }) .mouseleave(function(){ $(this).css({"color":"#F00"}); }) .click(function(){ $(this).html('clicked'); }); }) } return this; };
This one, however, is based on your source code. Basically, I restored the source code using these tips . This is how I personally take care of this. I also provided you with a breakdown below the changes made. ( SIGNIFICANT CHANGES MADE ):
$.fn.tippedOff = function(settings) { var config = $.extend( { 'top':0, 'left':0, 'wait':3000, 'color': 'orange', 'hoverColor': 'blue' }, settings); return this.each(function() { $this = $(this); $this.css({ 'color': config.color}) .mouseenter(function(){ $this.css({ 'color': config.hoverColor }); }) .mouseleave(function(){ $this.css({ 'color': config.color }); }) .click(function(){ $this.html('clicked'); }); }); }
----------------------------------------
Structure:
Original code:
$.tippedOff = function(selector, settings) {
Modified by:
$.fn.tippedOff = function( settings ) {
Comments:
The difference between $.tippedOff and $.fn.tippedOff is huge! Adding your plugin to the $.fn namespace rather than the $ namespace will not let you provide a selector and make life easier.
I personally like this answer , in which @Chad states:
My rule I adhere to is: use $. when it is not related to the DOM (e.g. ajax) and uses $ .fn. when it works with elements captured by a selector (e.g. DOM / XML elements).
Original code:
if(settings){$.extend(config, settings);}
Modified by:
var config = $.extend( { 'top':0, 'left':0, 'wait':3000 }, settings);
Comments:
Having an if is redundant. .extend() does all the work for you.
Original code:
var $elem = $(selector); if($elem.length > 0) { $elem.each(function() { $(this).css({"color":"#F00"}); }) } return this;
Modified by:
return this.each(function() { $this = $(this); $this.css({ 'color': config.color}); });
Comments:
Using return this.each(function(){}) is good practice and supports binding. In addition, you no longer have to worry about the length of the selector .
* NOTE: If you want to add additional events, use another methods in your plugin: jQuery Doc Reference - Authoring Plugins .
I hope this helps, and please let me know if you have any questions!