Created
May 29, 2014 06:53
-
-
Save kotarok/bf786675a6ad7cf96a2a 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
var ListShuffler = function(targetExpr, itemExpr) { | |
this.targetExpr = targetExpr || ''; | |
this.itemExpr = itemExpr || 'li'; | |
this.targetEl = {}; | |
this.items = []; | |
this.init(); | |
this.do(); | |
} | |
ListShuffler.prototype.init = function() { | |
this.targetEl = document.querySelector(this.targetExpr); | |
var items = this.targetEl.querySelectorAll(this.itemExpr); | |
for (var i = items.length - 1; i >= 0; i--) { | |
this.items.push(items[i]); | |
}; | |
return this; | |
}; | |
ListShuffler.prototype.shuffle = function() { | |
var array = this.items; | |
for (var i = array.length - 1; i > 0; i--) { | |
var j = Math.floor(Math.random() * (i + 1)); | |
var temp = array[i]; | |
array[i] = array[j]; | |
array[j] = temp; | |
} | |
this.items = array; | |
}; | |
ListShuffler.prototype.clear_ = function() { | |
var el = this.targetEl; | |
while (el.firstChild) { | |
el.removeChild(el.firstChild); | |
} | |
}; | |
ListShuffler.prototype.put = function() { | |
for (var i = this.items.length - 1; i >= 0; i--) { | |
this.targetEl.appendChild(this.items[i]) | |
}; | |
}; | |
ListShuffler.prototype.do = function() { | |
this.shuffle(); | |
this.clear_(); | |
this.put(); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment