Whenever I want to create a jQuery plugin, I always go to one of my old plugins and copy and paste the source code. That’s fine, but other developers may layout jQuery plugins slightly differently. I decided to try and create a jQuery Plugin “template” that does the hard work for you. But who should I follow? In the end I took my ideas from tutorials by Jeffrey Way, editor of nettuts.com who certainly knows a thing or do about jQuery. So I present the jQuery Plugin Template. There are probably enhancements to be made…if you see something you think should be different please say so!
(function($){
$.fn.pluginName = function(options) {
var
defaults = {
//here you should set your default options.
//example: backgroundcolor: red
},
settings = $.extend({}, defaults, options);
this.each(function() {
var $this = $(this);
//now use $this instead of $(this), makes jQuery do less work
});
// returns jQuery which allows for chaining
//eg $('div').yourPlugin().hide();
return this;
}
})(jQuery);
One Response
gero
25|Sep|2009You should also check if This is not empty.
No need to do all that hard work on nothing.
settings = $.extend({}, defaults, options);
If (!this.length){return this};
this.each(function() {
This should do the trick.
Leave a reply