2

I am trying to make divs appear in random order everytime the page is loaded.

I implemented the following code:

<script type="text/javascript">
$(function() {
  $(window).load(function(){
    $("div.container").randomize("div.random");
  });
});
(function($) {
$.fn.randomize = function(childElem) {
  return this.each(function() {
      var $this = $(this);
      var elems = $this.children(childElem);
      elems.sort(function() { return (Math.round(Math.random())-0.8); });  
      $this.remove(childElem);  
      for(var i=0; i < elems.length; i++)
        $this.append(elems[i]);      
  });    
}
})(jQuery);
</script>

<div class="container">
  <div class="random"> 1 </div>
  <div class="random"> 2 </div>
  <div class="random"> 3 </div>
  <div class="random"> 4 </div>
  <div class="random"> 5 </div>
  <div class="random"> 6 </div>
  <div class="random"> 7 </div>
  <div class="random"> 8 </div>
</div>

Divs really change their positions/order everytime the page is loaded. However, statistically - "1" tends to appear almost always in the "top 4", on the contrary "8" is almost always at the bottom of the list!

That does not seem like being really RANDOM... I will highly appreciate any suggestions about this. It is very important that every div has the same chance to be on top of the list.

jsfiddle

Careless
  • 50
  • 4
Wuu
  • 81
  • 6
  • It doesn't update at all in jsfiddle. – Mutant Feb 21 '14 at 00:56
  • Yes it does not... Tried to make it work there but I was not able to... It works fine in html tho... PS. I'm jquery beginner, sorry :( – Wuu Feb 21 '14 at 01:03

3 Answers3

2

I've used the The Fisher-Yates (Knuth) Shuffle

Wikipedia page: http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle

See the original SO post: How to randomize (shuffle) a JavaScript array?

See the original GitHub page: https://github.com/coolaj86/knuth-shuffle

See a test fiddle here: http://jsfiddle.net/fabio_silva/NRfYJ/

function shuffle(array) {
  var currentIndex = array.length
    , temporaryValue
    , randomIndex
    ;

  // While there remain elements to shuffle...
  while (0 !== currentIndex) {

    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    // And swap it with the current element.
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }

  return array;
}
Community
  • 1
  • 1
Fábio Duque Silva
  • 2,146
  • 1
  • 18
  • 16
  • 1
    Now this is what I call RANDOM :D Works like a charm! Thank you so much!! – Wuu Feb 21 '14 at 01:07
  • I have conflict with other script, I guess it is "$.noConflict();" part that's an issue here... Any idea how to change this code so that it will work? – Wuu Feb 21 '14 at 01:37
1

Try out this

$(function () {
function shuffle(o) { 
    for (var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
    return o;
};

var randomize = function (element) {
    var elems = shuffle($(element));
    $(".container").html('');
    for (var i = 0; i < elems.length; i++)
    $(".container").append(elems[i]);

}
randomize("div.random");
});

working example at jsfiddle

Akhlesh
  • 2,389
  • 1
  • 16
  • 23
  • @Akh, if you look closely, that's the same algorithm that I posted. The difference is that I spent more time trying to read that, with those one-chared variables and that one-lined for cycle... :) – Fábio Duque Silva Feb 21 '14 at 01:24
  • @Akh nope..not me... I just posted it. The original post and code is from CoolAJ86. Check the links in my post. Cheers. – Fábio Duque Silva Feb 21 '14 at 02:01
0

http://jsfiddle.net/jpatel/92dJV/

Try out this -

$.fn.randomize = function(selector){
    var $elems = selector ? $(this).find(selector) : $(this).children(),
        $parents = $elems.parent();

    $parents.each(function(){
        $(this).children(selector).sort(function(){
            return Math.round(Math.random()) - 0.5;
        }).remove().appendTo(this);
    });

    return this;
};

$('.container').randomize('div');
Mutant
  • 3,663
  • 4
  • 33
  • 53
  • Same thing. I just refreshed the page like 20 times and "1" went below "position 4" only 1 time... Strange... It seems order in html makes a really big difference anyway after it is "randomized" and shuffled... – Wuu Feb 21 '14 at 01:02
  • just for curiosity I tried in different browser (Firefox and chrome) and I see some difference in terms of randomization or may be I am in illusion. – Mutant Feb 21 '14 at 01:06
  • That is indeed interesting. Maybe I will look into this one day, when not so hard pressed for time. Thanks to Fabio I already have a solution. Thank you for your effort tho!! – Wuu Feb 21 '14 at 01:09
  • @Mutant FYI, I didn't downvote you either, but using "random - 0.5" is not advised. See http://www.robweir.com/blog/2010/02/microsoft-random-browser-ballot.html. Cheers. – Fábio Duque Silva Feb 21 '14 at 01:27
  • @FábioSilva - Thanks for the link, its very informative. – Mutant Feb 21 '14 at 21:19