Last active
August 29, 2015 13:57
-
-
Save HaNdTriX/9622354 to your computer and use it in GitHub Desktop.
This file contains 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
<div data-display-viewport="500" class="reorder-elements"> | |
<div data-display-order="99">99</div> | |
<div data-display-order="999">999</div> | |
<div data-display-order="12">12</div> | |
<div data-display-order="11">11</div> | |
<div data-display-order="10">10</div> | |
<div data-display-order="9">9</div> | |
<div data-display-order="3">3</div> | |
<div data-display-order="2">2</div> | |
<div data-display-order="1">1</div> | |
<div data-display-order="9999">9999</div> | |
</div> |
This file contains 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
(function($) { | |
function OrderedNode(element) { | |
this.$element = $(element); | |
this.maxViewport = parseInt(this.$element.data(this.maxViewportName)); | |
this.saveOldState(); | |
this.decide(); | |
if (this.maxViewport) { | |
// Todo: Throttle | |
$(window).resize($.proxy(this.decide, this)); | |
} | |
} | |
OrderedNode.prototype = { | |
dataAttrName: 'display-order', | |
dataAttrBkpName: 'display-order-backup', | |
maxViewportName: 'display-viewport', | |
saveOldState: function(){ | |
var _this = this; | |
this.$element | |
.children() | |
.each(function(index, element){ | |
$(this).data(_this.dataAttrBkpName, index); | |
}); | |
}, | |
decide: function() { | |
if (!this.maxViewport) { | |
// Reorder | |
return this.order(true); | |
} else if (this.maxViewport >= window.innerWidth) { | |
// Reorder | |
return this.order(true); | |
} else { | |
// Undo Reorder | |
this.order(false); | |
} | |
}, | |
order: function(newState) { | |
var dataAttrName = newState ? this.dataAttrName : this.dataAttrBkpName; | |
var i = 0; | |
// Detach and Sort Elements | |
var sorted = this.$element | |
.children() | |
.detach() | |
.sort(function(a, b) { | |
console.log('sort', dataAttrName); | |
a = parseInt($(a).data(dataAttrName), 10); | |
b = parseInt($(b).data(dataAttrName), 10); | |
++i; | |
if (a > b) { | |
return 1; | |
} else if (a < b) { | |
return -1; | |
} else { | |
return 0; | |
} | |
}); | |
// Retach newly sorted Elements | |
this.$element.append(sorted); | |
} | |
} | |
$('.reorder-elements').each(function(index, element) { | |
new OrderedNode(element); | |
}) | |
})($ || jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment