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();

Considering local, dev and live environments

When you develop a website for a client you should usually be considering three or even four (if you also include staging) environments where one code base may be used. Local, development and live.

In this case you may want the code to behave slightly differently depending on where it’s being used.

A good example I regularly come across is when and where to send any emails that a system generates. When you are testing locally or on a development server you certainly don’t want to send out emails to people who have no knowledge of the system.

Continue reading

Code 365

I do some sort of coding pretty much every day. It might be a tweak to a site’s design, some hardcore php Yii coding or even a bit of applescript on my mac, but I usually have something I can write, explain or rant about.

Code 365 is an attempt by me to publish a post to this blog each day through to 1st July 2013. It may be that some posts are very short and I queue several up occasionally, but the plan is generally for one each day.

I’ll be posting them to my @hjbme twitter account if you want to keep up with what I’m banging on about.

So coming up shortly, day 1 of 365. Let me know how I’m getting on.