SortableDOM ALT

by levchenko_d

HTML

<!-- DEMO -->
<div>
  <span>Sort by: </span>
  <button id="by-name">name</button>
  <button id="by-date">date</button>
  <button id="by-sort">'data-sort'</button>
</div>
<br>
<!-- DEMO END -->


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

JavaScript

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

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

  for(var i=0; i<listSize+1; i++){// Append Sorted List
  	if(i < listSize){
    	var item = _this.itemsArr[i];
      item.parentNode.appendChild(item);

      if(_this.options.each) _this.options.each(item);
    } else if(i === listSize){
    	if(_this.options.callback) _this.options.callback(_this.list);
    }
  	
  };
 
 
  return _this;
};

Sortable.prototype.sort = function(attribute, descending){
	var _this = this,
  		attr = attribute || _this.sortBy,
      oldDescending = _this.descendingHistory[attr];
  
  _this.descendingHistory[attr] = descending === 'toggle' ? !oldDescending : descending;
  
  _this.sortList(function(a, b){
  	var a = a.getAttribute(attr).toLowerCase(),
				b = b.getAttribute(attr).toLowerCase();

    if(a>b) return 1;
    if(a<b) return -1;
    return 0;
  }, _this.descendingHistory[attr]);
  
  return _this;
};




//Example:

var sortList = new Sortable({
	selector: '.sortable', //list selector, Default '.sortable'
  itemSelector: '.item', //selector of items that should be sorted. Default '.item'
  sortBy: 'data-sort', //itemSelector atribute. default 'data-sort'
  each: function(item){ console.log('Item Sorted') },
  callback: function(list){ console.log('Sorting Done') }
});

sortList.sort(null, true);


//Demo:
document.getElementById('by-name').onclick = function(){ sortList.sort('data-name', 'toggle') }
document.getElementById('by-date').onclick...