Created
September 5, 2016 15:33
-
-
Save andreasvirkus/f3cde6b4536e588efefcc75d42045be4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* A custom sort method to sort DOM nodes | |
* | |
* @param wrap {HTMLElement} direct parent of sortable elements | |
* @param filter {Function} A pre-filter to gather the comparable attributes into an array (because DOM comparison is costly) | |
* @param map {Array} Desired order of elements by their IDs | |
*/ | |
function sortModules(wrap, filter, map) { | |
var l = wrap.children.length, | |
arr = [], | |
par = wrap.parentNode, | |
ref = wrap.nextSibling; | |
for (var i = 0; i < l; ++i) { | |
arr[i] = [filter(wrap.children[i], map), wrap.children[i]]; | |
} | |
arr.sort(function(a, b) { | |
return a[0] - b[0]; | |
}); | |
par.removeChild(wrap); | |
for (var j = 0; j < l; ++j) { | |
wrap.appendChild(arr[j][1]); | |
} | |
par.insertBefore(wrap, ref); | |
} | |
// Usage | |
sortMap = ['i-come-first', 'second', 'i-am-third', 'random-fourth-id']; | |
sortModules( | |
document.getElementById('sortables'), | |
function(item, map) {map.indexOf(wrap.children[i].id}, | |
sortMap | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment