04.07.2013 Views

Building iPhone Apps with HTML, CSS, and ... - Cdn.oreilly.com

Building iPhone Apps with HTML, CSS, and ... - Cdn.oreilly.com

Building iPhone Apps with HTML, CSS, and ... - Cdn.oreilly.com

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

you are the person driving, in which case it could take considerably longer (did I say<br />

“crash” course?).<br />

Intro to JavaScript<br />

At this point you should know how to structure a document <strong>with</strong> <strong>HTML</strong> <strong>and</strong> how to<br />

modify its visual presentation <strong>with</strong> <strong>CSS</strong>. Now we’ll add some JavaScript to make it do<br />

stuff.<br />

JavaScript is a scripting language that can be added to an <strong>HTML</strong> page to make it more<br />

interactive <strong>and</strong> convenient for the user. For example, you can write some JavaScript<br />

that will inspect the values typed in a form to make sure they are valid. Or you can have<br />

JavaScript show or hide elements of a page depending on where the user clicks.<br />

JavaScript can even contact the web server to execute database changes <strong>with</strong>out refreshing<br />

the current web page.<br />

Like any modern scripting language, JavaScript has variables, arrays, objects, <strong>and</strong> all<br />

the typical control structures (if, while, for, <strong>and</strong> so on). Example 1-8 shows a snippet<br />

of JavaScript that illustrates several core concepts of the language.<br />

Example 1-8. Basic JavaScript syntax<br />

var foods = ['Apples', 'Bananas', 'Oranges'];<br />

for (var i in foods) {<br />

if (foods[i] == 'Apples') {<br />

alert(foods[i] + ' are my favorite!');<br />

} else {<br />

alert(foods[i] + ' are okay.');<br />

}<br />

}<br />

Here’s an explanation of what’s happening here:<br />

Define an array named foods that contains three elements.<br />

Open a for loop that defines a variable named i that will contain the index of each<br />

element of the array during the loop.<br />

A garden-variety if checks to see if the current element of the array is equal to Apples.<br />

This is displayed if the current element of the array is equal to Apples.<br />

This is displayed if the current element of the array is not equal to Apples.<br />

Here are some points about JavaScript’s syntax that are worth noting:<br />

• Statements are terminated <strong>with</strong> semicolons.<br />

• Code blocks are enclosed in curly braces.<br />

• Variables are declared using the var keyword.<br />

• Array elements can be accessed <strong>with</strong> square bracket notation.<br />

Web Programming Crash Course | 9

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!