Global and local variables in my script

Posted by Acorn on Stack Overflow See other posts from Stack Overflow or by Acorn
Published on 2010-04-24T22:51:33Z Indexed on 2010/04/24 22:53 UTC
Read the original article Hit count: 261

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.

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about beginner