Global and local variables in my script
- by Acorn
I'm 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.