
If you’re here, I’m sure it’s no surprise jQuery is an easy library to use. jQuery may be easy, but it still has its quirks and can be difficult for some to grasp beyond basic functionality and concepts. No worries, I’ve got a simple guide here to help break down code, that may seem like overly complex syntax, into simple thoughts and patterns that can be easily understood.
Here, we’ve got a basic plugin layout:
// Shawn Khameneh
// ExtraordinaryThoughts.com
(function($) {
var privateFunction = function() {
// code here
}
var methods = {
init: function(options) {
return this.each(function() {
var $this = $(this);
var settings = $this.data('pluginName');
if(typeof(settings) == 'undefined') {
var defaults = {
propertyName: 'value',
onSomeEvent: function() {}
}
settings = $.extend({}, defaults, options);
$this.data('pluginName', settings);
} else {
settings = $.extend({}, settings, options);
}
// run code here
});
},
destroy: function(options) {
return $(this).each(function() {
var $this = $(this);
$this.removeData('pluginName');
});
},
val: function(options) {
var someValue = this.eq(0).html();
return someValue;
}
};
$.fn.pluginName = function() {
var method = arguments[0];
if(methods[method]) {
method = methods[method];
arguments = Array.prototype.slice.call(arguments, 1);
} else if( typeof(method) == 'object' || !method ) {
method = methods.init;
} else {
$.error( 'Method ' + method + ' does not exist on jQuery.pluginName' );
return this;
}
return method.apply(this, arguments);
}
})(jQuery);
You may notice the structure I’ve provided is significantly different from others. Plugins can vary depending on usage and needs. Here, it is my goal to explain the concepts in code well enough for you to understand and author a plugin in such a way that suits you best.
So, let’s break it down!
Continue reading →