How to write jQuery plugin.

Aug 07, 04:12 pm

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

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="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" 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 () {
       $('#mag_sort').sort_by_mag();
});

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){
 $(this).bind('click',function(event){
  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
fields.sort(cmp_asc);    
       
// append rows
var ROW_COUNT = fields.length;      
for(var j = 0; j < ROW_COUNT; j++)
{    
 table_sort.append(fields[j]);
}

See result

5. Add reversive sort

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

See result

Alexander Molodih

,

Commenting is closed for this article.

Molodih Alexander
Categories
Recent articles