Search code examples
javascriptjqueryhtmlrandomfade

Selecting random div for auto fade in and fade out


Currently, this code is auto fade in and fade out div by selecting the div element the way they were arranged (consecutive order). What I want to do now is to make the selector in random, I want to fade in a random div and after fading it out it will pick another random div and infinite loop the process. Since I'm new in jQuery and so confused, I also want to know your opinion on how to put this such process on a If Else statement in the easiest way. Like for example, I will get the value of a number

int num = 1;
If(num == 1){
<!-- Do the process-->
}
Else {
<!-- Do another process by selecting from another set of divs-->
}

Here is the code:

    jQuery.fn.nextOrFirst = function (selector) {
    var next = this.next(selector);
    return (next.length) ? next : this.prevAll(selector).last();
}

$(document).ready(function () {
    $('div.mb').fadeOut(500);

    var fadeInTime = 1000;
    var intervaltime = 3000;
    setTimeout(function () {
        fadeMe($('div.mb').first());
    }, intervaltime);

    function fadeMe(div) {
        div.fadeIn(fadeInTime, function () {
            div.fadeOut(fadeInTime);
            setTimeout(function () {
                fadeMe(div.nextOrFirst());
            }, intervaltime);
        });
    }
});

Divs:

 <div class="boxes">
      <div class="mb one">1-------------one</div>
      <div class="mb two">2-------------two</div>
      <div class="mb three">3-------------three</div>
 </div>

Solution

  • Not sure if this is exactly what you want but can be modified:

    var mb = $('.mb'),   
    mbl = mb.length;
    
    mb.hide();
    rand();
    
    function rand(){
      var r = getRand(0, mbl);
    
      mb.eq(r).fadeIn('slow', function(){
        $(this).fadeOut('slow', function(){
          setTimeout(rand, 200);
        });
      });
    }
    
    
    function getRand(min, max) {
        return Math.floor(Math.random() * (max - min) + min);
    }