jQuery, Random opacity
by Adam Culpepper
HTML
<div id="boxContainer"></div>
CSS
#boxContainer {
width: 384px;
height: 384px;
margin: 20px auto;
}
.boxItem {
width: 48px;
height: 48px;
float: left;
background-color: #ccc;
}
JavaScript
(function($) {
var interval = 1000,
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);