A very basic jquery-plugin

This will be a short entry regarding how to create a very simple jquery plug-in. In this example I’ll create a plug-in which will lock text boxes to numeric input only (which can be useful if you want age input or something of the like).

The first thing you need to do is to create a ‘closure’ of the jQuery object. There are a lot of different libraries for javascript and the dollar sign can collide with these. So, to ensure that this won’t happen you can encapsulate it into a self-calling function, looking something like this:

(function($)
{
});

As we are writing a jQuery plug-in we’ll send the jQuery object as an argument. Without the self-caling it could also be written as:

function foo()
{
}

But then we’d had to call our plug-in our selves before we use it, and we don’t want that.
The plug-in itself will be added inside the encapsulation and it basically looks like this:

(function($)
{
	$.fn.numeric = function()
	{
		return this.each(function(idx, element)
		{
			$(element).bind('keydown', function(e)
			{
 
			});
		});
	}
})(jQuery);

$.fn.numeric = function(){} creates the plug-in. This is what you use on your element later (ex: $(‘.foo’).numeric()) to activate it.
It will loop through all elements it’s connected to and bind a keydown event to that element. Then we bind the keydown to each element it loops though and this is where we add our numeric-check, it looks like this:

...
$(element).bind('keydown', function(e)
{
	//8  = Backspace
	//46 = Delete
	if(e.keyCode == 46 || e.keyCode == 8) 
	{
		//Do nothing
	}
	else 
	{
		//48 = 0
		//...
		//57 = 9
		if(e.keyCode < 47 || e.keyCode > 58)
		{
			e.preventDefault();
		}
	}
});
...

We take in an event object from the keydown event. This object contains a property called keyCode. This property tells us which button it was that the user pressed to fire the event.
We check if the button is 46 (delete) or 8 (backspace) and if it is, we do nothing as these buttons are allowed (we could also have added ‘.’ if we want to allow decimals). Then we check if the key code is between 47 and 58 (0-9 key in the key code map) and if it isn’t, we exit the keydown event. This means that no command is sent to the end client (our input box).

The whole code, with bindings, looks like this:

(function($)
{
	$.fn.numeric = function()
	{
		return this.each(function(idx, element)
		{
		$(element).bind('keydown', function(e)
		{
			//8  = Backspace
			//46 = Delete
			if(e.keyCode == 46 || e.keyCode == 8) 
			{
				//Do nothing
			}
			else 
			{
				//48 = 0
				//...
				//57 = 9
				if(e.keyCode < 47 || e.keyCode > 58)
				{
					e.preventDefault();
				}
			}
		});
		});
	}
 
	$(document).ready(function()
	{
		$('.nummer').numeric();
	});
})(jQuery);

A demo can be found here: http://demo.maffelu.net/jquery/basicplugin.htm

Leave a Reply