jQuery, Random opacity

by Bhabani Raju

HTML

<div id="boxContainer">
Ahh, I've learned something new. I was discussing the case where it equals EXACTLY 1, but apparently (according to W3Schools) Math.random is between 0 inclusive and 1 exclusive.</div>

CSS

#boxContainer {
    width: 784px;
    height: 384px;
    margin: 20px auto;
    text-align:center;
}
.boxItem {
    width: 48px;
    height: 48px;
    float: left;
    background-color: #ccc;
}

JavaScript

(function($) {
    var interval = 2000,
        width = 8,
        height = 8,
        container$ = $('#boxContainer');
    
    // set a handler for custom event
    $(document).on('box.animate', '.boxItem', onAnimate);

    function onAnimate() {
        var box$ = $(this);
        // kind of mutex
        if(!!box$.data('isAnimating')) {
            return;
        }
        box$.data('isAnimating', true);
        box$.animate({
            opacity: Math.random()
        }, interval, function() {
            box$.data('isAnimating', false);
        });
    }
    
    function buildTheField() {
        for(var y = height; 0 < y--;) {
            addRow();
        }
        return $('.boxItem');
    }
 
    function addRow() {
        for(var x = width; 0 < x--;) {
            var div$ = $('<div>').addClass('boxItem').css({
                opacity: Math.random()
            });
            container$.append(div$);
        }
    }

    var boxes$ = buildTheField();
    
    // Triggers the event for all the boxes
    function forceAnimate() {
        boxes$.trigger('box.animate');
    }

    setInterval(forceAnimate, interval);
})(jQuery);