Frantisek
Frantisek

Reputation: 7693

How to make images appear in a random order using jQuery

When I have this code:

$("img").each(function(i) {
   $(this).delay(i*100).fadeIn('slow');
});

Which can be seen live here to give a better example of what it does...

... How can I make those images appear in a random order? That means not from top left to bottom right, but randomly like image 45, image 100, image 3, etc ... ?

Upvotes: 2

Views: 1646

Answers (4)

wdm
wdm

Reputation: 7189

Should probably use an array and pop values from the array at random until there are none left.

EDIT: Just wrote this custom function...

Demo: http://jsfiddle.net/XqRYq/


(function( $ ){
    $.fn.cascadeMe = function() {

        return this.each(function() {           

            var $this = $(this);
            var obj = $(this).children('span');
            var arr = $.makeArray(obj);          
            arr.sort(function() {return 0.5 - Math.random()});          
            $this.empty().show();
            arr.push("");

            var delay = 150;

            $.each(arr, function(i, val) {
                $this.append(val);
                $this.children('span').hide().fadeIn(500).delay(delay * i);
            });

        });

    };
})( jQuery );

usage...

$('#someDiv').cascadeMe();

Upvotes: 1

Joseph Erickson
Joseph Erickson

Reputation: 2294

You want to avoid fadeOut since it will set display: none; on your elements and then when they fade in they'll just around everywhere. Here's a better function that should get what you want out of the fade. (And yes, I tested it on your site.)

$("img").sort(function(a,b){return Math.round(Math.random())-0.5}).each(function(i) {
    $(this).delay(i*100).fadeTo('slow',1);
});

You'll need to have the images set as visible when the page loads, but set all their opacity to 0.

Upvotes: 0

jrn.ak
jrn.ak

Reputation: 36619

http://blog.staydecent.ca/entry/jquery-random-each

function randsort(c) {
    var o = new Array();
    for (var i = 0; i < c; i++) {
        var n = Math.floor(Math.random()*c);
        if( jQuery.inArray(n, o) > 0 ) --i;
        else o.push(n);
    }
    return o;
}

var e = $('div'); // The elements we're searching
var c = e.size(); // Total number of those elements
var r = randsort(c); // an array of the element indices in random order

$("div").each(function(i) {
    var e = $(this);
    e.fadeTo(0, 0.05);
    setTimeout(function(){
        e.fadeTo(250, 1);
    }, r[i]*10);
});

Upvotes: 6

Khez
Khez

Reputation: 10350

Have you tried using random() ?

$("img").each(function(i) {
   $(this).delay(Math.random()*100).fadeIn('slow');
});

Upvotes: 1

Related Questions