Skip to content Skip to sidebar Skip to footer

Sort Random Field Items Via Jquery

I have a HTML slide menu. With the following:

Solution 1:

There is a much simpler way to do this. Since a jQuery collection is Array-like, you can call native Array prototypes on them. So using the native Array.sort, your code you be rewritten like this:

var grp = $(".slide").children(); // the original collection, if you want to save it...Array.prototype.sort.call(grp, function() {
    returnMath.round(Math.random())-0.5;
});

$('.slide').empty().append(grp);

Here is a demo: http://jsfiddle.net/JTGfC/

Solution 2:

I'm not sure whether this is 100% kosher, but you could apply Fisher-Yates here, without dependency on jQuery.

fisherYates(document.getElementsByClassName('slide')[0]);

// Fisher-Yates, modified to shuffle DOM container's children instead of an array.functionfisherYates (node)
{
  var children = node.children,
  n = children.length;

  if (!n) {
    returnfalse;
  }

  while (--n) {
     var i = Math.floor( Math.random() * ( n + 1 ) ),
     c1 = children[n];

     node.insertBefore(c1, children[i]);
   }
}

Demo

Solution 3:

Your reorder() function is fine, I tested it in this fiddle : http://jsfiddle.net/kokoklems/YpjwE/

I did not used the second function orderPosts() though...

Solution 4:

This should do it for you:

functionreorder() {
    var grp = $(".slide").children();
    var cnt = grp.length;

    var indexes = [];
    // Build a array from 0 to cnt-1 for (var i = 0; i < cnt; i++) {
        indexes.push(i);
    } 
    // Shuffle this array. This random array of indexes will determine in what order we add the images.
    indexes = shuffle(indexes);

    // Add the images. (No need to remove them first, .append just moves them)for (var i = 0; i < cnt; i++) {
        $(".slide").append($(grp[indexes[i]]));
    }
}

functionshuffle(o){
    for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
    return o;
}

Shuffle function source

Working sample (I used spans instead of the images, to show the result better)

Post a Comment for "Sort Random Field Items Via Jquery"