Shuffle - embaralhando listas e arrays com jQuery
Por Guilherme Serrano em Internet, Programação,
Plugin jQuery para embaralhar (randomizar) listas de html ou arrays de javascript.
Faz tempo que quero lançar uma nova versão da Vitrine Fácil Buscapé, e isso está sendo desenvolvido. Como agora estudei e domino um pouco mais jQuery isso está facilitando muito os testes e desenvolvimento de novas ferramentas.
Uma das idéias era permitir a exibição randômica de produtos, para isso pesquisei sobre arrays em javascript (é, eu não sei nada de js mesmo) e acabei descobrindo um interessante plugin desenvolvido por Ca Phun Ung (thanks!).
O plugin (shuffle) serve para embaralhar um array ou todos os children dentro de um elemento HTML (listas, parágrafos, imagens...).
Shuffle
/*
* jQuery shuffle
*
* Copyright (c) 2008 Ca Phun Ung
* Dual licensed under the MIT (MIT-LICENSE.txt)
* and GPL (GPL-LICENSE.txt) licenses.
*
* http://yelotofu.com/labs/jquery/snippets/shuffle/
*
* Shuffles an array or the children of a element container.
* This uses the Fisher-Yates shuffle algorithm
*/
(function($){
$.fn.shuffle = function() {
return this.each(function(){
var items = $(this).children();
return (items.length) ? $(this).html($.shuffle(items)) : this;
});
}
$.shuffle = function(arr) {
for(var j, x, i = arr.length; i; j = parseInt(Math.random() * i), x = arr[--i], arr[i] = arr[j], arr[j] = x);
return arr;
}
})(jQuery);
A utilização é bem simples:
$(´ul´).shuffle();
E para array:
var arr = [1,2,3,4,5,6];
arr = $.shuffle(arr);
Não poderia ser mais prático!
Agora é só fazer vitrines, produtos, fotos randômicas... :)