Feb 13 2009

0

Visual Sorting Explained

Category: Mootools, UtilitiesTags: , , ,

I am getting the impression that my previous post was a bit esoteric. It has some valid uses and I want to help visualize how you might use the ‘visualSort’ method on Elements.

Lets first take a look at the demo I put up.

In the above image we have selected 5 elements. As you can see none of them are aligned and they actually overlap. However, the human eye discerns that there are 2 lines of elements. 3 on the top row, 2 on the bottom. The ‘visualSort’ method allows you to see elements like a users would in your code.

How visualSort solves this problem is two fold. First, it takes all the elements and sorts them by the ‘top’ coordinate. Once this sort is complete a second sort is performed. The first element is grabbed and an index is made based off the ‘tolerance’ (defaults to .5 or 50%). What this means is the height of the element is taken and multiplied by the ‘tolerance’. This result is added to the to the top value to get a tolerance range.

For example if chocolate had a top of 10px and was 20px in height. The tolerance would be within 10-20px. Any following element that has a top pixel within this range will be added to the same row. As an element is added to a row they are sorted by the left pixel to make sure they are in the correct order. If an element is not within that range a new row is created along with a new tolerance. The cycle repeats until all elements have been processed.


Using the illustration above, this is how the code would work.

 
$$(selected_elements).visualSort();
// returns [ [ 'chocolate', 'triumph', 'wisdom' ] , [ 'cataclysmic', 'love' ] ]
 
$$(selected_elements).visualSort(.5,true);
// returns $$([ 'chocolate', 'triumph', 'wisdom', 'cataclysmic','love' ])

Note: for illustrative purposes I returned the html value of each node. In reality visual sort returns the elements.

Things to consider when using this method. This method will perform very well if all elements are the same height. If there is a considerable difference in the height of the elements there could be some undesired results. Some of this can be remedied with the tolerance parameter. In order to handle a large degree of varying heights more logic would need to be added to the sort routine.

I see this piece of code being of use in drag and drop interfaces. I will be providing more code soon doing just that.

Tags: , , ,

Leave a Reply