SortableDOM

by levchenko_d

HTML

<ul class="sortable">
  <li class="item" data-name="a" data-date="19.11.01" data-number="10">1</li>
  <li class="item" data-name="b" data-date="19.11.02" data-number="11">2</li>
  <li class="item" data-name="c" data-date="19.11.03" data-number="12">3</li>
  <li class="item" data-name="d" data-date="19.11.04" data-number="13">4</li>
  <li class="item" data-name="e" data-date="19.11.05" data-number="14">5</li>
</ul>

JavaScript

var Sortable = function(options){
	var _this = this;
  
	_this.options = options;
  _this.list = document.querySelector(_this.options.selector);
  _this.items = _this.list.querySelectorAll(_this.options.itemSelector || '.item');
  _this.itemsArr = Array.prototype.slice.call(_this.items);
};

Sortable.prototype.sortList = function(sortFn, descending){
	var _this = this;
  
  _this.itemsArr.sort(sortFn);
  
  if(descending) _this.itemsArr.reverse();

  for(var i=0; i<_this.itemsArr.length; i++){// Append Sorted List
  	var item = _this.itemsArr[i];
    item.parentNode.appendChild(item);
    
    if(_this.options.callback) _this.options.callback(_this.list);
  };
 
  return _this;
};

Sortable.prototype.byName = function(attribute, descending){
	var _this = this;
  
  _this.sortList(function(a, b){
  	var a = a.getAttribute(attribute).toLowerCase(),
				b = b.getAttribute(attribute).toLowerCase();
        
    if(a>b) return 1;
    if(a<b) return -1;
    return 0;
  }, descending);
  
  return _this;
};

Sortable.prototype.byNumber = function(attribute, descending){
	var _this = this;
  
  _this.sortList(function(a, b){
  	var a = parseFloat(a.getAttribute(attribute)),
				b = parseFloat(b.getAttribute(attribute));

    return a>b;
  }, descending);
  
  return _this;
};


var sortList = new Sortable({
	selector: '.sortable',
  itemSelector: '.item',
  callback: function(){ console.log('Sorting Done') }
});

sortList.byName('data-name', false);
sortList.byNumber('data-number', true);