Editable list with Local Storage + shuffle
by yinyann
HTML
<ul id="todos" contenteditable="true">
<li>Do something</li>
</ul>
<input type="button" value="shuffle" id="shuffle" />
JavaScript
$(function (){
// sauvegarde du contenu lors du clic hors de la liste
var tobuy = document.getElementById('todos');
$("#todos").blur(function() {
localStorage.setItem('todosList', this.innerHTML);
});
$("#shuffle").click(function(){ $("#todos li").shuffle(); });
// récupération du contenu au chargement de page
if (localStorage.getItem('todosList')) {
tobuy.innerHTML = localStorage.getItem('todosList');
}
});
(function($){
$.fn.shuffle = function() {
var allElems = this.get(),
getRandom = function(max) {
return Math.floor(Math.random() * max);
},
shuffled = $.map(allElems, function(){
var random = getRandom(allElems.length),
randEl = $(allElems[random]).clone(true)[0];
allElems.splice(random, 1);
return randEl;
});
this.each(function(i){
$(this).replaceWith($(shuffled[i]));
});
return $(shuffled);
};
})(jQuery);