I’m just starting out learning javascript, and tried to write a little script that would make a grid of divs on a page.
Here’s the script:
var tileWidth=50;
var tileHeight=100;
var leftPos=10;
var topPos=10;
var columns=10;
var rows=10;
var spacing=5;
$('document').ready(function() {
placeTiles();
});
function makeRow() {
for (var i=0; i<columns; i++) {
$('#canvas').append('<div class="tile" style="left:' + leftPos + 'px;top:' + topPos + 'px;"></div>');
var leftPos = leftPos + tileWidth + spacing;
}
}
function placeTiles() {
for (var i=0; i<rows; i++) {
makeRow();
var topPos = topPos + tileHeight + spacing;
}
}
At the moment, 100 <div>s get created, all with a top position of 10px and a left position of undefined (for the first <div> in the row) or NaN.
What should I be doing differently? Why can’t makerow() see my global leftPos variable (and all the other variables for that matter)?
Thanks.
“Why can’t makerow() see my global leftPos variable (and all the other variables for that matter)?”
Because
varis not a declaration. It is a function(scope)-wide annotation. In the top-level scopevaressentially does nothing (the global execution context/scope is the window object) so it is the same aswindow.leftPos = 10or justleftPos = 10. In the makeRow you essentially have:Something look suspicious? 🙂
Two solutions to this are 1) use a different variable name (recommended) 2) use the ‘global’ leftPos a property of the window object (as shown below).
Also, even though it is just a scope-wide annotation, it generally leads to more clear code if you keep the ‘var’s at the top (it is “hoisted” anyway, see above). Eg:
For more information, see:
Identifier Resolution, Execution Contexts and Scope Chains