MooTool JavaScript Challenge #1
My take on the first JavaScript Challenge, promoted by MooTools. More info: http://mootools.net/blog/2012/07/25/javascript-challenge-1/
by secretgspot
CSS
.element {
position: absolute;
line-height: 30px;
font-family: sans-serif;
color: white;
font-size: 15px;
text-align: center;
}
JavaScript
/*
* My solution for MooTools' JavaScript Challenge #1
* More info: http://mootools.net/blog/2012/07/25/javascript-challenge-1/
*
* @params
* columns: Number of columns.
* rows: Number of rows.
* side: Size of the square elements (in pixels)
* start: Starting at cell 0.0, start the pattern to 'right' or 'bottom'
*/
(function(columns, rows, side, start) {
// Ensure default values
columns = columns || 12;
rows = rows || 7;
side = side || 30;
start = (start === 'right') ? start : 'bottom';
// Functions
var newEl = function(innerHtml) {
var newDiv = document.createElement('div');
if (innerHtml != null) newDiv.innerHTML = innerHtml;
newDiv.className = 'element';
newDiv.style.width = side + 'px';
newDiv.style.height = side + 'px';
newDiv.style.position = "absolute";
return newDiv;
},
// Dimensional constraints
getMaxs = function(columns, rows) {
var t = +(start === 'right'),
l = +(start !== 'right'),
r = columns - 1,
b = rows - 1;
return {
'top': function() {
return t;
},
'left': function() {
return l;
},
'right': function() {
return r;
},
'bottom': function() {
return b;
},
'update': function() {
t += 1;
l += 1;
r -= 1;
b -= 1;
}
};
};
// Necessary variables
var body = document.getElementsByTagName('body')[0],
el, numberElements = columns * rows,
// New elements' coordinates
pinX = 0,
pinY = 0,
// Elements' maximum positions
max = getMaxs(columns, rows),
...