0

I have a responsive grid whitin images.
I would like to make a random order of these pictures by a shuffle function but I don't know how to do.
Any idea ? Thanks.

Html

<div id="grid">  
    <div class="box"><img 1></div>
    <div class="box"><img 2></div>
    <div class="box"><img 3></div>
    <div class="box"><img 4></div>
</div>

Script

$.shuffle('#grid div');
Hedra
  • 89
  • 1
  • 17

2 Answers2

1

Here's a solution I came up to this many years ago (recreated from old code today):

http://jsfiddle.net/bznfnb2r/1/

Basically, what I do is randomly swap a few of the boxes:

$(function() {
    jQuery.extend({
        random: function(X) {
            return Math.floor(X * (Math.random() % 1));
        },
        randomBetween: function(MinV, MaxV) {
            return MinV + jQuery.random(MaxV - MinV + 1);
        }
    });

    jQuery.fn.swap = function (b) {
        b = jQuery(b)[0];
        var a = this[0];

        var t = a.parentNode.insertBefore(document.createTextNode(""), a);
        b.parentNode.insertBefore(a, b);
        t.parentNode.insertBefore(b, t);
        t.parentNode.removeChild(t);

        return this;
    }

    var numItems = $("#grid .box").length - 1;

    for (var i = 0; i < numItems; i++) {
        $("#grid .box:eq("+$.randomBetween(0, numItems)+")").swap("#grid .box:eq("+$.randomBetween(0, numItems)+")");
    };
});

It's not great, but does do the job.

As I say though, I'd likely do this server side instead.

Rich Bradshaw
  • 71,795
  • 44
  • 182
  • 241
0

Here's the solution that I found in the following link, the answer wasn't clear : jquery move elements into a random order

this file in addition is required :
http://vestride.github.io/Shuffle/dist/jquery.shuffle.min.js

jQuery.fn.shuffle = function () {
    var j;
    for (var i = 0; i < this.length; i++) {
        j = Math.floor(Math.random() * this.length);
        $(this[i]).before($(this[j]));
    }
    return this;
};

$('#grid .box').shuffle();
Community
  • 1
  • 1
Hedra
  • 89
  • 1
  • 17