paulby
paulby

Reputation: 87

Randomly fade in div with jQuery

Any help here is much appreciated. I would like to use jQuery to solve the following...

There are two divs. I would like to randomly fade in one of the divs (green or red), wait a few seconds, then fade it away. Then randomly fades in another one. I've tried using math.random();but I can't seem to get it working correctly.

So basically it chooses either the red or green div.. fades it away after a few seconds, randomly chooses the red or green div... then fades it away after a few seconds. And It just keeps repeating.

html:

<div id="one">This is the first block</div>
<div id="two">This is the second block</div>

css:

#one { 
    background: red;
    width:300px; 
    height:100px; 
}
#two { 
    background: green;
    width:300px; 
    height:100px; 
}

Upvotes: 0

Views: 2181

Answers (4)

Felix
Felix

Reputation: 38102

Give both divs a class name like .fade for easier to manage.

Then you can do like this:

(function randomFade() {
    var fadeDivs = $('.fade'),
        el = fadeDivs.eq(Math.floor(Math.random() * fadeDivs.length));        
    el.fadeIn('1000').delay(2000).fadeOut('1000',randomFade);   
})();

Fiddle Demo

Upvotes: 1

Erik
Erik

Reputation: 128

You could do this:

function fadeRandomly() {
   // fade both out at first
   $('#one').fadeOut(/* duration */); 
   $('#two').fadeOut(/* duration */); 
   if (Math.random() > 0.5) {
      $('#one').fadeIn(/* duration */);
   } else {
      $('#two').fadeIn(/* duration */); 
   }
}

setInterval(fadeRandomly, /* duration between animations */);

Upvotes: 1

james emanon
james emanon

Reputation: 11807

something like: I added a function just in case you have more divs to deal with you and you want to expand the scope of your fades.

var a = ['one', 'two']; // the name of your divs
function fadeRandomDiv(min, max) {
  var divtofade =  a[Math.floor(Math.random() * (max - min + 1) + min)];
   // delay 4 seconds, then fade out
  jQuery( "#" + divtofade ).fadeIn( "slow" ).delay(4000).fadeOut("slow");
}

fadeRandomDiv(1, a.length - 1)

if you want to repeadedly call it.

  // every 3 seconds call the function
   setInterval(function(){
       fadeRandomDiv(1, a.length - 1);
    }, 3000);

Upvotes: 0

dev7
dev7

Reputation: 6369

This should work:

var rnd = Math.floor(Math.random() * 2) + 1;//outputs either 1 or 2

if (rnd == 1) {
  $('#one').fadeIn(500).delay(500).fadeOut(500);
} else {
  $('#two').fadeIn(500).delay(500).fadeOut(500);
}

Hope this helps!

Upvotes: 0

Related Questions