skip to content

JavaScript: DHTML Sorting Using OOP

 Tweet0 Shares0 Tweets

For a more detailed explanation of DHTML sorting, and the Bubble Sort algorithm, you should first visit the Bubble Sort demonstration page and follow the related commentary.

This page presents a JavaScript class that enables you to 'bubble sort' tables, lists, or custom sets of HTML elements. At the bottom of the page are links to equivalent classes for: Insertion Sort, Shell Sort and Quick Sort.

By using Object-Oriented Programming we remove the bulk of the code from the page where it's executed, and create an external JavaScript file that can be re-used on any page or website.

OOP Table Sorting

The following table demonstrates the dynamic sorting of a multi-column table using an OOP version of the Bubble Sort code which is included via an external JavaScript file.

How you 'trigger' the sort event is up to you. On this page we demonstrate a number of different options which will suit different situations and datasets. We also show how the sort can be applied not just to tables but to lists and other structures.

id colour random
1green82.38
2blue22.44
3yellow59.06
4blue82.94
5orange20.82
6purple67.15
7red80.27
8green36.28
9orange17.21
10purple41.44
11red25.84
12purple49.47
13yellow41.63
14purple38.01
15green71.97
16orange68.33
17red39.18
18orange91.34
19yellow40.81
20red95.61
Sort by DESC?

[View as stand-alone example]

Source Code

We first need to include the external JavaScript file. By this approach we make the code much more manageable and re-usable. We're also able now to work on the sort functionality without affecting any HTML or in-line JavaScript code.

An external JavaScript file can be included as follows (usually this is placed in the HEAD of your HTML page):

<script type="text/javascript" src="bubblesort.js"></script>

With the bulk of the code 'included', the in-line JavaScript becomes almost trivial.

The first step is to instantiate a new bubbleSort object based on the table defined by id="data":

// parent node for sorting rows must be TBODY and not TABLE var dataTable = document.getElementById("data"); if(dataTable.nodeName != "TBODY") { dataTable = dataTable.getElementsByTagName("TBODY")[0]; } myTable = new bubbleSort(dataTable, "TR", "TD");

The three parameters required are: the id of the parent node; the nodeName of the child nodes (in this case the table rows: TR); and the nodeName of the columns (the table cells: TD).

This code can be placed either: in-line in the body of the page after the TABLE has been defined; or elsewhere as a function called by the onLoad (or window.onload) event. It cannot, for what should be obvious reasons, be called before the HTML defining the TABLE has been loaded.

Actually sorting the table is then very simple:

// sort by the first column ascending myTable.sort(0, false); // sort by the second column descending myTable.sort(1, true);

As demonstrated on this page, the sort command can be triggered by: links, forms, buttons or any other event.

Note: A common mistake is to forget to wrap your column headers in a THEAD tag. A TBODY tag should also be present, but most (or all) browsers will insert it automatically. See the W3C specification Tables in HTML documents for more information.

Advanced Functionality

If you compare the code in the included file with that presented for the non-OOP Bubble Sort demonstration, you'll see a few new, and hopefully useful, features.

Defining your own sort values

One improvement is that the sort can be applied not just to a TABLE, but to lists and other grouped elements. More on that further down the page.

Another feature is the ability to provide your own 'sort values'. For example, if you wanted to sort by something more complicated than a number or string, such as date values, the results could be less than helpful.

Consider the following demonstration:

name dob dob with sort value
Drew 22/2/1975 22 February 1975
Eliza 30/12/1980 30 December 1980
Hermann 12/7/1972 12 July 1972
Alice 4/2/1948 4 February 1948
Bob 5/10/1954 5 October 1954

Clicking on name will sort by name, clicking again will reverse the sort - no problem here. Clicking on dob however will sort as if the dates were strings resulting in an alphabetical/numeric sort - not what we wanted.

In the third column (if you look at the HTML) there's an extra attribute on the TD's that is picked up during the sort process and used instead of the actual cell values to 'force' a correct sort.

To illustrate this, the first row is actually marked up as:

<tr> <td>Drew</td> <td>22/2/1975</td> <td sort="19750222">22 February 1975</td> </tr>

So all of a sudden you're not limited in cases where the way the data is sorted conflicts with how you want it displayed!

Sorting on a subset of the data

Another new feature is the ability to sort on the contents of a childNode of the 'child' nodes. For example, if a column of your TABLE contains links rather than text you probably want to sort based on the text inside the link.

The table below demonstrates both the problem and the solution:

# string link wrapper
1 Bubble Sort Bubble Sort Bubble Sort
2 Insertion Sort Insertion Sort Insertion Sort
3 Shell Sort Shell Sort Shell Sort
4 Quick Sort Quick Sort Quick Sort

The first two column contain 'plain text' so there's no difficulty in sorting them. The third column introduces a link which causess our script immediately to fail. The reason for this is that it's looking for a 'text' node' wheras those cells actually contain their own 'A' nodes which then contain the text to be sorted.

The code that we would normally use for sorting the third column (which obviously doesn't work) is:

myTable.sort(2, 0);

The way to implement a sort on data that is contained within another tag is used for the last column of the above table:

myTable.sort(3, 0, 'a');

The additional parameter tells the sort program to use the contents of the first 'a' tag within the cell rather than just the contents of the cell.

With careful use of this parameter you should be able to sort even the most complicated data. For example, you could insert 'dummy' tags such as <span> into the data to indicate which part of it to use for sorting, and pass 'span' as the extra parameter.

Or you can always define your own sort values as described above. The main advantage of this new method is that less HTML markup is required.

OOP List Sorting

This page demonstrates the dynamic sorting of a simple un-ordered list (UL) using an the same Bubble Sort code as for the TABLE demonstration above. All that changes is the way the class is called.

Source Code

Create a new bubbleSort object based on the list defined by id="data":

// initialise object for sorting myList = new bubbleSort(document.getElementById("data"), "LI", "");

Actually sorting the list is again very simple:

myList.sort(0, false); // sort ascending myList.sort(0, true); // sort descending

Note: This code fails when the list to be sorted also contains one or more child- or sub-lists. The fix would be to check that the items to be sorted have the correct 'parent' node.

Other OOP Sorting Algorithms

Each of the following files contains the functionality of one of the previously presented sorting algorithms. To use them in place of the Bubble Sort, all that is needed is to change the external JavaScript link and the instantiation.

ie. instead of "new bubbleSort(...)" you would use "new insertionSort(...)", and so forth...

The choice of which you use really depends on the task at hand. The Bubble Sort and Insertion Sorts are by far the simplest and most reliable, but very inefficient for large datasets.

The Shell Sort and Quick Sort are much faster but may not work in older browsers (Opera 7 and the Mac version of MSIE 5 for example). For the type of data typically presented on the web the Shell Sort seems to be the most effective.

< JavaScript

Send a message to The Art of Web:


used only for us to reply, and to display your gravatar.

CAPTCHA

<- copy the digits from the image into this box

press <Esc> or click outside this box to close

User Comments

Post your comment or question

12 June, 2008

I just wanted to say that I really appreciated the work you put in on the different sorting algorithms. I started playing with different options for visualizing the algorithms from this site and I though you might be interested in the result.

funkycss.s3.amazonaws.com/bubble-sort-panorama.html

Cheers, and thanks again.

That's fantastic! And great mountain panoramas as well

top