jqueryrandomfadeto

How to randomize fadeTo?


This is a tiny js file, grabbed from somewhere, used in wordpress to make thumbnails fade in on page load.

(function($) {
    $('.featured-thumbnail').each(function(i) {
        $(this).delay((i++) * 380).fadeTo(1000, 1); })
})(jQuery);

I'd like to add randomness to i.

The questions are: Where to use Math.random? Should I use Math.floor also? Do I need total i? Doesn't appear to be necessary.

Slow learning jQuery newbie.


Solution

  • Sounds like you want the thumbnails fading-in in a random order. If you're OK with those fade-ins overlapping, you can say:

    (function($) {
        var len = $('.featured-thumbnail').length;
    
        $('.featured-thumbnail').each(function(i) {
        $(this).delay(Math.floor( Math.random() * 380 * len)).fadeTo(1000, 1); })
    })(jQuery);
    

    otherwise, you can pick off random elements off your list and fade them in on the same schedule as the original:

    (function($) {
      // jQuery selectors return array-LIKE objects,
      // but not actual arrays. We need a real array.
      //
      var items = $.makeArray( $('.featured-thumbnail') );
      var i = 0;
    
      while (items.length > 0)
      {
        // pick a random index within our array
        //
        var idx = Math.floor( Math.random() * items.length );
    
        // grab that item, remove it from the array.
        // splice() returns an array, so grab the first (only)
        // element from that array. splice() removes the
        // selected element(s) from the original array
        //
        var selected = items.splice(idx, 1)[0]; 
    
        // delay and fade in as before
        //
        $(selected).delay(i++ * 380).fadeTo(1000, 1);
      }
    })(jQuery);