in Javascript, jQuery

A jQuery plugin for the masses

Every wonder how to hit the ground running with a jQuery plugin? Here is the absolute complete basics for you (and me) to copy and paste…

First we need to define our Class. I’ll call mine Boom.


var Boom = function(element, options){
	this.init('boom', element, options);
};

So now we have something to focus our plugin at we can add a prototype method to it. This makes the ‘new Boom’ code super slick and gives us a better control over the ‘this’ variable because we can whack it inside a function…


Boom.prototype = {

	init:function(type, element, options)
	{
		// do stuff on create

		// makes it available almost anywhere as this.$element
		this.$element = $(element);

		// then maybe do something with the options
	},

	another_one:function()
	{
		// do some other clever stuff.
	}

};

And finally we need to connect it up to the jQuery bit…


$.fn.boom = function (options) {

	// return this makes it chainable
	return this.each(function ()
	{
		new Boom(this, options);
	});
};

$.fn.boom.Constructor = Boom;

Very basic, but worth having here for future use. You can now call it like so…


$('li.bang').boom();