|
Where am I?
hosting > /games/ > /chess/ |
< Back | Next > |
Code View:
Here's what this simple JavaScript function does. First, since it's a function, it won't be "run" until it's "called". You can see the call made immediately after the buildBoard function is defined, it's the line buildBoard(). Functions are great because they let you group your code logically and run it when you want to rather than on-the-fly (or "inline") as the browser reads the code while the web server is spitting it out. Functions make for much cleaner management and that's critical, particularly as a project increases in complexity.
This function basically creates a long string of HTML. It uses a few housekeeping variables. The variables are for keeping track of which class to assign to the current square (TD cell), which row we're working on, and which column within that row we're working on. The variable i handles the rows, and the variable j handles the columns. The variable tmp is basically a toggle that, when set to 1 is used to set our class variable cls to black, otherwise, cls is already set to white by default. Note: There are a variety of preferences for how to handle a toggle state such as what I'm using to set the class variable. I chose this one because I think it's pretty easy to read (and doesn't introduce the ternary operation which I wanted to avoid at this point.)
The function starts by defining the variable html with an HTML open TABLE tag. Then it drops into the row loop adding an open TR tag. Then it drops into the column loop and adds eight TD tags toggling their classes between white and black. When the for/loop makes the ninth iteration, j is set to "9" and the condition is no longer true, so the j for/loop drops out. At that point the html variable gets a close TR tag added and we loop again on the next row. This process repeats until the i variable gets set to "9" on it's ninth iteration. At that point the i-for/loop's test condition is no longer true and it drops out. Lastly, a close TABLE tag is appended onto the html variable and that variable is rendered using document.write().
Again, the really great thing about this technique is that we serve out a small amount of code relative to what actually gets written into the HTML document in the browser. So we don't have to pay the costs of the extra bandwidth to serve those characters as static HTML. It's not a big deal on a small scale, but as you serve millions of users it becomes more compelling. Plus less is better for dial-up surfers who notice heavy pages more readily than broadband users.
| < Back | Next > |