Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting Divs in jQuery by Custom Sort Order

I'm trying to re-sort the child elements of the tag input by comparing their category attribute to the category order in the Javascript variable category_sort_order. Then I need to remove divs whose category attribute does not appear in category_sort_order.

The expected result should be:

any
product1
product2
download

The code:

<div id="input">
<div category="download">download</div>
<div category="video">video1</div>
<div category="video">video2</div>
<div category="product">product1</div>
<div category="any">any</div>
<div category="product">product2</div>
</div>

<script type="text/javascript">
var category_sort_order = ['any', 'product', 'download'];
</script>

I really don't even know where to begin with this task but if you could please provide any assistance whatsoever I would be extremely grateful.

like image 376
lightyrs Avatar asked Oct 21 '09 21:10

lightyrs


2 Answers

I wrote a jQuery plugin to do this kind of thing that can be easily adapted for your use case.

The original plugin is here

Here's a revamp for you question

(function($) {

$.fn.reOrder = function(array) {
  return this.each(function() {

    if (array) {    
      for(var i=0; i < array.length; i++) 
        array[i] = $('div[category="' + array[i] + '"]');

      $(this).empty();  

      for(var i=0; i < array.length; i++)
        $(this).append(array[i]);      
    }
  });    
}
})(jQuery);

and use like so

var category_sort_order = ['any', 'product', 'download'];
$('#input').reOrder(category_sort_order);

This happens to get the right order for the products this time as product1 appears before product2 in the original list, but it could be changed easily to sort categories first before putting into the array and appending to the DOM. Also, if using this for a number of elements, it could be improved by appending all elements in the array in one go instead of iterating over the array and appending one at a time. This would probably be a good case for DocumentFragments.

like image 73
Russ Cam Avatar answered Oct 16 '22 11:10

Russ Cam


Just note,

Since there is jQuery 1.3.2 sorting is simple without any plugin like:

$('#input div').sort(CustomSort).appendTo('#input');
function CustomSort( a ,b ){
     //your custom sort function returning -1 or 1
     //where a , b are $('#input div') elements
}

This will sort all div that are childs of element with id="input" .

like image 39
Vaclav Kohout Avatar answered Oct 16 '22 11:10

Vaclav Kohout