Nathan Long
Nathan Long

Reputation: 125942

How can I randomly show a set of elements using jQuery?

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.

Upvotes: 4

Views: 2348

Answers (3)

neonski
neonski

Reputation: 955

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.

Upvotes: 2

Jason Bunting
Jason Bunting

Reputation: 58931

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).

Upvotes: 1

Andrew Hedges
Andrew Hedges

Reputation: 21796

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);
})();

Upvotes: 0

Related Questions