Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery, random div order

I have this jQuery and HTML http://jsfiddle.net/UgX3u/30/

    <div class="container">
    <div class="yellow"></div>
    <div class="red"></div>
    <div class="green"></div>
    <div class="blue"></div>
    <div class="pink"></div>
    <div class="orange"></div>
    <div class="black"></div>
    <div class="white"></div>
    </div>​
$("div.container div").each(function(){
    var color = $(this).attr("class");
    $(this).css({backgroundColor: color});
});

I am trying to randomise the order, so the div.container div is in any random position, meaning not the same position it started. and the div must remain within the div.container

I have tried http://jsfiddle.net/UgX3u/32/ http://jsfiddle.net/UgX3u/20/ and more functions I found on the net but non are working

​how can I get the div's to display in a random order

like image 255
Yusaf Khaliq Avatar asked Feb 24 '12 18:02

Yusaf Khaliq


1 Answers

Try this:

http://jsfiddle.net/UgX3u/33/

$("div.container div").sort(function(){
    return Math.random()*10 > 5 ? 1 : -1;
}).each(function(){
    var $t = $(this),
        color = $t.attr("class");
    $t.css({backgroundColor: color}).appendTo( $t.parent() );
});

.sort is applied to jQuery like this:

$.fn.sort = [].sort

Since it doesn't perform like other jQuery methods, it isn't documented. That does mean it is subject to change, however I doubt it will ever change. To avoid using the undocumented method, you could do it like this:

http://jsfiddle.net/UgX3u/37/

var collection = $("div.container div").get();
collection.sort(function() {
    return Math.random()*10 > 5 ? 1 : -1;
});
$.each(collection,function(i,el) {
    var color = this.className,
        $el = $(el);
    $el.css({backgroundColor: color}).appendTo( $el.parent() );
});
like image 66
Kevin B Avatar answered Oct 24 '22 14:10

Kevin B