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
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}
You could replace your
compareFunctionwithThe Array.sort function sorts an array by means of the passed
compareFunction(a, b). This works as followsYour compare function always returns values
>= 0. It says thatA >= BandB >= A. Depending on the random values, it mostly occurs thatA > B. Accordingly, it would be impossible thatB >= 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.