1

Using jQuery 1.5.2, I'm giving a random position to the children of a div, the code works in Firefox, Chrome and Opera, but it doesn't work in IE7-9 and Safari. What is wrong?

A second question, when the page is refresed multiple times, the random pattern is not very random, sometimes the same number stays in first place, etc. Any hint to increase the randomness of the script?

PD: the jquery fiddle is 1.6.4

http://jsfiddle.net/6cqtP/

SCRIPTS

jQuery(document).ready(function() {
              jQuery('#postscript-top-inner').each(function(){
            var parent = jQuery(this);
            var content = parent.find('.block-nodeblock');

            content.sort(function(a){
                  var new_position = parseInt( Math.random()*4 );
                  return( new_position );
            })
            .appendTo(parent);       

      });
});

HTML

<div id="postscript-top-inner">
 <div class="block-nodeblock">
1
 </div>
  <div class="block-nodeblock">
2
 </div>
  <div class="block-nodeblock">
3
 </div>
  <div class="block-nodeblock">
4
 </div>
  <div class="block-nodeblock">
5
 </div>
  <div class="block-nodeblock">
6
 </div>
  <div class="block-nodeblock">
7
 </div>
  <div class="block-nodeblock">
8
 </div>
  <div class="block-nodeblock">
9
 </div>
  <div class="block-nodeblock">
10
 </div>
  <div class="block-nodeblock">
11
 </div>
  <div class="block-nodeblock">
12
 </div>
  <div class="block-nodeblock">
13
 </div>
  <div class="block-nodeblock">
14
 </div>
  <div class="block-nodeblock">
15
 </div>
  <div class="block-nodeblock">
16
 </div>

</div>

CSS

#postscript-top-inner{width: 460px; margin:0 auto}
.block-nodeblock{width:50px; padding:25px 0; background: gray; margin:0 10px 10px 0; text-align:center; float: left}
Ricardo Castañeda
  • 5,746
  • 6
  • 28
  • 41

1 Answers1

1

You could replace your compareFunction with

function() {
    return 0.5 - Math.random();
}

The Array.sort function sorts an array by means of the passed compareFunction(a, b). This works as follows

If compareFunction(a, b) is less than 0, sort a to a lower index than b.

If compareFunction(a, b) returns 0, leave a and b unchanged with respect to each other, but sorted with respect to all different elements.

If compareFunction(a, b) is greater than 0, sort b to a lower index than a.

Your compare function always returns values >= 0. It says that A >= B and B >= A. Depending on the random values, it mostly occurs that A > B. Accordingly, it would be impossible that B >= A. Due to this paradox, some browser implementations of Array.sort do not sort your array at all.

To further improve the randomness, you could implement the Fisher-Yates algorithm.

Community
  • 1
  • 1
Matthias
  • 7,432
  • 6
  • 55
  • 88