Question

I have a script that cycles through tags that are id=banner_1, id=banner_1, id=banner_3, etc...

I want to have my script cycle through the tags but in random order, right now they are cycled in numerical order (1,2,3,etc...)

HTML:

<p id='banner-1'>one</p>
<p id='banner-2'>two</p>
<p id='banner-3'>three</p>

jQuery:

<script type="text/javascript">     
    $(document).ready(function() {
        var divs = $('p[id^="banner-"]').hide(),
        i = 0;
        (function cycle() {
            divs.eq(i).fadeIn(400).delay(5000).fadeOut(400, cycle);
            i = ++i % divs.length;
        })();
    });
</script>

Thanks in advance!

Was it helpful?

Solution 2

Here is an example where it will pick a random banner each time but won't show the same banner twice.

(function cycle() {
    divs.eq(i).fadeIn(400).delay(3000).fadeOut(400, cycle);
    var old = i;
    while(old == i){
        i = (Math.random() * 100).toFixed(0) % divs.length;
    }

Fiddle

Another example this will initialize the banners in a random order and subsequently keep the same pattern (order).

 var orderArray = []; 
 while(orderArray.length < divs.length){
        i = (Math.random() * 100).toFixed(0) % divs.length;
        if(orderArray.indexOf(i) == -1){
            orderArray.push(i);    
        }
    }
    i = 0;
(function cycle() {
    divs.eq(orderArray[i]).fadeIn(400).delay(2500).fadeOut(400, cycle);
    var old = i;
    while(old == i){
        i = (Math.random() * 100).toFixed(0) % divs.length;
    }

Fiddle

Depending on what your looking to do..

OTHER TIPS

Simply add Math.random() to your i:

i = (Math.random() * 100).toFixed(0) % divs.length;

Fiddle

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top