Alexander Molodykh

How to write jQuery plugin

It is a quick step by step guide that show's how to create a simple jQuery plugin.

As example I've create table sorter plugin.

1. Create an empty jQuery plugin

It is the jQuery plugin's template.

(function($) {
 $.fn.sort_by_mag = function() {
     // constructor

Its called "sort_by_mag", as you might to guess.

2. Attach jQuery plugin.

Firstable you need to add the link to jQuery library.

To get the most recent version of jQuery in the 1.*.* family, use the following link:

<script src="" type="text/javascript"></script>

Then we need to refer to our plugin:

<script src="jquery.sort_by_mag.js"></script>

And attach our plugin to table that we are try to sort (with id = "#mag_sort").

You should be add plugins when the page is always loaded! That's why I use($(document).ready)

$(document).ready(function () {

3. Add some simple action to constructor

Select all first row cells in table for sorting ('tr:first th') and put some simple action on click. Let's show a simple message with number of column that was clicked.

var table_sort = this;
table_sort.find('tr:first td').each(function(i,element){
  alert("You click at table number " + i + ", elment = " + element);

Now you can see that is really works: See result.

4. Let's add some sort action

Let's change the action that we are hang to the table header to more interest.

Here we add ascending sort for our columns (fields.sort(cmp_asc)), and append it to the table.

// take array of rows (without first row becaus we don't need to sort header)
var fields = table_sort.find('tr:gt(0)');
// compare jQuery objects by column i ascending 
function cmp_asc(a, b) {
 a = jQuery(a).find('td:eq('+i+')').text();
 b = jQuery(b).find('td:eq('+i+')').text();
 if (a < b) return -1;
 if (a > b) return 1;
 return 0;
// take array of rows (without first row)
var fields = table_sort.find('tr:gt(0)');
// sort this array
// append rows
var ROW_COUNT = fields.length;      
for(var j = 0; j < ROW_COUNT; j++)

See result

5. Add reversive sort

Finally we need to add a reversive sorting feature, and other sweet things)

See result

All rights reserved.