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

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

Explanation . I want to start with the fact that all these elements are hidden and end on all of them, so it doesn't make sense to show() the same element twice.

I initially thought that I would create an array listing all the elements, randomly select one, show that one, remove it from the array using splice() , and then arbitrarily select the next from the remaining list - and so on. But since my array is part of the jQuery object, splice() not available.

+4
source share
3 answers

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

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

So, suppose you have an array of divs ready to go, call the shuffle () method and just go through it one by one so that (they are now shuffled) and show them (according to your intervals). You can make this non-destructive, but by cloning the array returned by the shuffle method, instead of sorting it directly.

+2
source

I do not 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 is not explicit, I assumed that you mean that in the end you want to show all of them, and that when they are visible, we are done. If not, explain in more detail so that I can update this (if you can no longer determine what you need from the code that I provided).

+1
source

Here is 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); })(); 
0
source

All Articles