views:

1116

answers:

3

Using jQuery, how would you show() every div.foo on a page in a random order, with a new one appearing every X milliseconds?

Clarification: I want to start with all these elements hidden and end with all of them showing, so it wouldn't make sense to show() the same element twice.

I originally thought I'd make an array listing all the elements, randomly pick one, show that one, remove it from the array using splice(), and then randomly pick the next one from the remaining list - etc. But since my array is part of a jQuery object, splice() is not available.

+1  A: 

I don't use jQuery myself, but what about this:

var intervalMilliseconds = X; // set to your value for X
var divFoos = $("div.foo").get();
var intervalId = setInterval(function() {
   $(divFoos.splice(Math.floor(Math.random() * divFoos.length), 1)).show();
   if(divFoos.length == 0) clearInterval(intervalId);
}, intervalMilliseconds);

That should do the trick.


UPDATE: Since your description isn't explicit about it, I assumed you meant that you ultimately want to show all of them, and that once they are visible, we are done. If not, please explain further so I can update this (if you can't already determine what you need from the code I provided).

Jason Bunting
A: 

Here's how I would do it (untested):

(function () {
    var int, els;
    int = 100; // interval, in milliseconds
    els = $('div.foo');
    setInterval(function () {
        var idx;
        idx = Math.floor(els.length * Math.random());
        $(els[idx]).show();
        setTimeout(function () {
            $(els[idx]).hide();
        }, int);
    }, int);
})();
Andrew Hedges
This essentially cycles through, showing one, then hiding it before showing another, never ending, and potentially showing the same one multiple times before ever showing some of the others (the random numbers could be generated thus: 0, 1, 1, 0, 2, etc.). Hard to know if that is what the OP meant.
Jason Bunting
It seems to satisfy the requirements as they were expressed. It would be fairly easy to alter it to, for example, not show the same div twice in a row.
Andrew Hedges
+2  A: 

An interesting way to do this would be the extend Javascript's Array base object with a shuffle function. In Prototype (should be the same in JQuery, except jQuery.extend). This is quick and dirty shuffle, there are plenty of other ways to do it.

Object.extend(Array.prototype, {
  shuffle : function() {
    this.sort( function() { return 0.5 - Math.random(); } );
    return this;
  }
});

So assuming you have your array of divs ready to go, call the shuffle() method and simply go through them one by one, in order (they're now shuffled) and show them (according to your intervals). Might want to make that 'non-destructive' though by cloning the array returned by the shuffle method instead of sorting it directly.

neonski