jQuery: Randomly reorder children elements of selected elements
I'm working on a new template for a client, and they asked me to display some list elements in a random order on each page load. I did my Google due diligence, but didn't come up with anything that wasn't slideshow-like -- what I wanted was just something that would show all of the children elements of an element, but in a random order. (In this particular case, the children elements were case case studies.) I was already using jQuery on the page, so I wrote a plugin: jquery.reorder.js (1k) Here's the code:
$.fn.reorder = function() {
// random array sort from
// http://javascript.about.com/library/blsort2.htm
function randOrd() { return(Math.round(Math.random())-0.5); }
return($(this).each(function() {
var $this = $(this);
var $children = $this.children();
var childCount = $children.length;
if (childCount > 1) {
$children.remove();
var indices = new Array();
for (i=0;i
Thoughts? Suggestions? Let me know.10 comments
I found your blog while Googling jQuery terms related to this. Keep up the good work, and thanks for sharing, Rebecca!
Cheers!
is this correct to use your function?
$(document).ready(function(){
$('#item').reorder('', function() {
});
});
So I've made some slight modifications. Because you can't introspect the data on an element, I have provided a callback which is passed the child element and its clone. In the callback you can copy over any data you wish.
In summary: the children are hidden; then in a loop each is cloned and the clone is appended to the container (and shown) and the callback is called; then the child is removed.
Here is the Gist: http://gist.github.com/236696
$('#quotes').reorder().find('blockquote:not(:first)').hide();
Could you also do a version of this where I can pass in a specific element order? My use case: I have a set of elements on the page and due to other users manipulation I want to sort the elements for his colleagues now the same way. I would send the element order from the server to the client, but which is the most efficient (and non-destructive) way to sort the existing elements in the submitted order?
Greetings from Munich!