Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<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>
(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
You can’t perform that action at this time.