Chapter 2

Working with Core Technologies

WHAT YOU WILL LEARN IN THIS CHAPTER:

  • Adding video to your app
  • Discovering basic JavaScript coding techniques
  • Working with functions and arrays

Although a native iPhone app is built entirely in Objective-C, an iPhone web app is composed of a variety of core technologies that serve as interlocking building blocks. HTML provides structure for the user interface and application data. CSS is used for styling and presentation. JavaScript and Ajax provide the programming logic used to power the app. And, depending on the app, it may have a back-end application server, such as Java or PHP.

Books on programming native iPhone apps often have a primer chapter on the basics of Objective-C to make sure everything is speaking the same language, so to speak. And, although it’s outside the scope of this book to include a complete primer on the core web technologies you will work with to develop an iPhone web app, I do want to explore some of the key technologies you need to be sure you know about in order to be successful.

The information in this chapter is presented with the assumption that you at least know the basics of HTML and at least have a working knowledge of CSS. Most of the material covered here is about the scripting logic layer. However, first I want to highlight the HTML 5 tags that Safari on IOS supports for embedding media into your web app.

EXPLORING HTML 5 MEDIA ELEMENTS

In the early days of the iPhone, working with video inside of an iPhone web app usually consisted of a simple link to a YouTube clip, which would then launch the YouTube app. Because Safari on IOS doesn’t support Flash video (.flv), there were few alternatives to an ordinary link when working with video. However, one of the key HTML 5 technologies that Safari on IOS now supports is the video element.

You use the video element to define a video clip or stream, much like an img tag defines an image on your page. The promise of the video tag is that it eliminates the complicated hoops that developers have to go through with embedded media content. Instead of mixing complicated object definitions and script, you can embed media with a simple tag definition.

Unfortunately for normal websites, the video element remains something of a tease because many desktop browsers don’t yet support HTML 5. As a result, developers either have to add additional code for unsupported browsers or else avoid its use altogether.

However, if you are creating an IOS web app, you don’t have this same dilemma. Safari on IOS provides full support for HTML 5. Therefore, if you need to utilize video in your app make sure to take advantage of the video tag.

Note that the video does not play inside of the web page as an embedded video; instead it launches the built-in IOS media player, which occupies the full screen of the device. The user then clicks the Done button to return to your app.

The basic syntax for the element is shown below:

<video src="../video/trailer.mov" controls="true" poster="picture.jpg"
  width="300" height="200"/>

TABLE 2-1: Attributes for the video Element

ATTRIBUTE DESCRIPTION
autoplay When set to true, the video plays as soon as it is ready to play.
controls If true, the user is shown playback controls.
end Specifies the end point to stop playing the video. If not defined, the video plays to the end.
height Defines the height of the video player.
loopend Defines the ending point of a loop.
loopstart Defines the starting point of a loop.
playcount Specifies the number of times a video clip is played. Defaults to 1.
poster Specifies the URL of a “poster image” to show before the video begins playing.
src Defines the URL of the video.
start Sets the point at which the video begins to play. If not defined, the video starts playing at the beginning.
width Defines the width of the video player.

Supported video formats include QuickTime (.mov) and MPEG (.mp4). Note that Safari on iPhone does not support Flash media (.flv) and OggTheora (.ogg).

TRY IT OUT: Adding a Video

Adding a video into your app now becomes as easy as adding the video tag to your page.

1. Create the following HTML document in your text editor and then save the document as BIDHJ-Ch02-Ex1.html.

image
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
         "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Video</title>
<meta name="viewport" content="width=320; initial-scale=1.0;
  maximum-scale=1.0; user-scalable=0;"/>
<style type="text/css">
body
{
  background-color: #080808;
  margin: 10;
  color: #ffffff;
  font-family: Helvetica, sans-serif;
font-size:10px; 
}
</style>
</head>
<body>
</body>
</html>

Code snippet BIDHJ-Ch02-Ex1.html

2. Add the following div element in the body and save your file:

image
<div style="text-align:center">
<p>Check out the new trailer for our upcoming video game release.</p>
<video src="../videos/tlr2_h.640.mov" controls="true" width="300"/>
</div>

Code snippet BIDHJ-Ch02-Ex1.html

How It Works

When this document loads, the poster image of the video is displayed in the rectangular area of the video element (see Figure 2-1). When the user touches the video player Safari displays the video in the built-in media player, as shown in Figure 2-2.

The audio element works in much the same way, though its attributes are a subset of the video tag’s set. They include src, autobuffer, autoplay, loop, and controls. Figure 2-3 shows the audio file being played in the media player.

SCRIPTING JAVASCRIPT

The scripting layer of your IOS web app is often the “brains behind the operation” — the place on the client-side in which you add your programming logic. That’s why as you begin to develop more and more sophisticated web apps for the IOS platform, you’ll find that the technology you’ll rely more and more on is JavaScript. Therefore, before you go any farther in this book, you need to have a solid grasp on how to script with JavaScript. Use this section as a primer for the core essentials of programming with JavaScript.

Syntax and Basic Rules

Like any other programming language, JavaScript has its own syntax rules and conventions. Consider the following script:

<script>
 
// Defining a variable
var message = "Hello";
 
// Creating a function, a module of code
function showGreeting(allow)
{
  // If allow is true, then show the message variable
  if (allow == true)
  {
    alert(message);
  }
  // Otherwise, show this message
  else
    alert("I withhold all greetings.");
}
 
// Call function
showGreeting(true)
 
</script>

Notice a few aspects of the JavaScript syntax:

  • Case sensitivity: JavaScript is a case-sensitive language. The core language words (such as var, function, and if in the example) are all lowercase. JavaScript objects all use lowerCamelCase conventions, which is explained in the “JavaScript Naming Conventions” section later in this chapter. Variable names that you define can be in the case you choose, but note that the following terms are not equivalent:
    var message = "Hello";
    var MESSAGE = "Hello";
    var Message = "Hello";
  • Whitespace: Just like HTML, JavaScript ignores spaces, tabs, and new lines in code statements. Each of the following are equivalent:
    var message="Hello";
    var message = "Hello";

    These are as well:

    if (allow==true)
    if ( allow == true )
  • Semicolons: Each JavaScript statement ends with a semicolon (except for the descriptive comments lines).
  • Curly brackets: Some JavaScript control structures, such as functions and if statements, use curly brackets ({}) to contain multiple statements between them. You can place these brackets on separate lines or on the same line as the other code. For example:
    if (allow == true) {
      alert(message) }

    is the same as:

    if (allow == true)
    {
      alert(message)
    }

Variables

A variable is an alias that stores another piece of data — a text string, a number, a true or false value, or whatever. Variables are core to programming because they eliminate the need for having everything known while you are developing the script or application.

For example, suppose you want to capture the first name of the user and add it to a welcome message that appears when the user returns to your IOSWeb app. Without variables, you’d have to know the person’s name beforehand — which is, of course, impossible — or you’d have to use a generic name for everyone.

By using a variable, you eliminate this problem. You can capture the name of the user and then store it in the code as a variable, such as firstName. Any time in my script in which I need to work with the user’s name, I call firstName.

Declaring and Assigning Variables

When you want to use a variable, your first task is to declare it with the keyword var and then assign it a value. Here’s how this two-step process can look:

var firstName;
firstName = "Jonah";

The var keyword instructs the JavaScript interpreter to treat the following word, firstName in this case, as a variable. The following line then assigns the literal string Jonah to the firstName variable.

While declaring and assigning a variable may be two separate actions, you usually want to combine these into one single step. For example, the following code is functionally equivalent to the preceding two lines of code:

var firstName = "Jonah";

Truth be told, you can actually assign a variable without even using the keyword var. For example, the following code still works:

firstName = "Jonah";

However, I strongly recommend regular use of var when you first define it to ensure your code is readable and manageable by both you and other developers.

Hanging Loose with Variable Types

You can assign a variety of data types to a variable. Here are a few examples:

// String value
var state = "CO";
// Boolean value
var showForm = true;
// Number value
var maxWidth = 300;
// HTML document "node"
var element = document.getElementById("container"); 
// Array item
var item = myArray[0];

If you are coming from a Java, ActionScript, or other stronger typed language, you are probably wondering where you declare the type of data that can be stored by the variable. Well, to put it simply, you don’t have to. Because JavaScript is a loosely typed language, you do not need to declare the variable type.

Naming Variables

When you are naming variables, keep in mind the following general rules:

  • A variable name must begin with a letter or underscore, not a number or other special character. For example:
    // Valid
    var helper;
    var _helper;
     
    // Invalid
    var 2helper;
    var ^helper;
  • Although a number can’t start off a variable name, you can include one elsewhere in the word, such as the following:
    var doc1;
    var doc2;
  • As with other aspects of JavaScript, variable names are case sensitive. Therefore, each of the following are unique variable names:
    var counter;
    var Counter;
    var COUNTER;
    var counTer;
  • A variable name can’t contain spaces. For example:
    // Valid
    var streetAddress;
    var street_address;
     
    //Invalid
    var street address;
  • You can’t use any reserved word (see the “Reserved Words” section later in the chapter) as a variable name. For example:
    // Valid
    var isDone;
    var defaultValue;
    var mainWindow;
     
    // Invalid
    var is;
    var default;
    var window;

Accessing a Variable

After you define a variable and assign it a value, each time you reference it in your code, the variable represents the value that was last assigned to it. In the following snippet of code, the company variable is assigned a string value and displayed in an alert box:

var company = "Cyberg Coffee";
alert( "Our company is proudly named " + company);

The alert box displays the following:

Our company is proudly named Cyberg Coffee.

You can also change the value of a variable inside your source code. After all, they are called variables, aren’t they? A typical example is a counter variable that has a value that is incremented during a looping process. Consider the following example:

for (var i=1;i<=5;i++)
{
  document.write( "The value of the variable is: " + i + ".<br/>" );
}

I explain what the for loop does later in the chapter. For now, just focus on the variable named i. The variable starts out with a value of 1 during the execution of the first pass of the code inside of the for block. During the next pass, its value is incremented to 2. On the third pass, its value is incremented to 3. This same process continues until i is 5. In total, the document.write() method is called five times and outputs the following content:

The value of the variable is 1.
The value of the variable is 2.
The value of the variable is 3.
The value of the variable is 4.
The value of the variable is 5.

Scope

Variables can either have a limited or wide scope. If you define a variable inside of a function then that variable (called a local variable) is only available to the function itself and expires when the function is done processing. For example, check out the markup variable in the following code:

function boldText(textToDisplay)
{
  var markup = "<strong>" + textToDisplay + "</strong>";
  return markup;
}

The variable is created when the boldText() function runs, but it no longer exists after the function ends.

However, if you define the variable at the top level of the scripting block — in other words, outside of a function — then that variable (known as a global variable) is accessible from anywhere in the document. What’s more, the lifetime of a global variable persists until the document itself is closed.

Table 2-2 summarizes the differences between local and global variables.

TABLE 2-2: Local Versus Global Variables

TYPE SCOPE LIFETIME
Local Accessible only inside of a function Exists until the function ends
Global Accessible from anywhere in the document Exists until the document itself closes

Scope deals with the context of the variable within the scripting hierarchy. However, the location at which a variable is defined also matters. Simply put, a variable is accessible after it is declared. Therefore, you typically want to define global variables at or near the top of the script and local variables at or near the top of the function.

I’ve put together a sample script that demonstrates the scope of variables. First, I define a global variable at the top of a script:

<script type="text/javascript">
var msg = "I am a global variable";
var msgEnd = ", and you cannot stop me."

Next, I add an alert box to display the variable:

alert(msg + msgEnd);

When this code runs, the alert message text that appears is:

I am a global variable, and you cannot stop me.

Now, check out what I do. I create a function that assigns a local variable with the same name (msg) and then simply references msgEnd, the global variable I already defined. Here’s the code:

function displayAltMessage()
{
  var msg = "Don't hassle me, I'm a local variable';
  alert(msg + msgEnd);
}

I call this function in my script with the following line:

displayAltMessage();

When this function is executed the alert box displays the following text:

Don't hassle me, I'm a local variable, and you cannot stop me.

Notice that the local variable msg took precedence over the global variable msg. However, after that function finishes, the local variable msg is destroyed whereas the global variable msg remains.

Now suppose I reassign the value of the global variable msg later in my script and then display the alert box once again:

msg = "Reassigning now!";
alert(msg);

Yes, you’ve got it, the following text is displayed:

Reassigning now!

Notice that when I reassigned the variable, I did not need to add the var keyword again.

Here’s the full script:

<script type="text/javascript">
  // Global variable 
  var msg = "I am a global variable";
  var msgEnd = ", and you cannot stop me."
 
  // Displays "I am a global variable, and you cannot stop me."
  alert(msg + msgEnd);
function displayAltMessage()
  {
    // Local variable
    var msg = "Don't hassle me, I'm a local variable';
    // Displays "Don't hassle me, I'm a local variable, and you cannot stop me."
    alert(msg + msgEnd);
  }
  // Calls the function
  displayAltMessage();
 
  // Reassigning value to msg
  msg = "Reassigning now!";
 
  // Displays "Reassigning now!"
  alert(msg);
</script>

JavaScript Naming Conventions

Like other languages such as Java or ActionScript, JavaScript uses CamelCase conventions for naming parts of the language. Variables, properties, and methods use what is known as lowerCamelCase. When using lowerCamelCase convention, the name begins with a lowercase letter and the first letter of each subsequent new word in a compound word is uppercase with all other letters lowercase. You’ll find that JavaScript and the DOM adhere to this convention. For example:

var divElements = document.getElementsByTagName('div'),

In this example, document is the DOM object name for the HTML document and is all in lowercase. The method getElementsByTagName() is a compound word, so that the first letter of the additional words in the method are capitalized. My variable divElements uses lowerCamelCase style to make it clear that the term combines two words.

Another type of coding convention that some JavaScript developers follow is known as Hungarian notation. Following this coding style, variables are prefixed with a letter that indicates the data type of the variable. Table 2-3 shows several examples of this notation.

TABLE 2-3: Using Hungarian Notation with Your Variables

DATA/OBJECT TYPE PREFIX EXAMPLE
String s sFirstName
Number n nRating
Boolean b bFlag
Array a aMembers
Object (DOM elements, user objects, and so on) o oCustomer
Date d dTransactionDate

Working with Constants

As you work with variables, they often change values during the course of a script. However, there are other occasions in which you want to work with a variable that refers to a value that doesn’t change. These are called constants.

ActionScript, Java, and many other programming languages actually have a constant built into the language that is different than a variable. JavaScript does not. However, from a practical standpoint, you can define a variable and treat it as a constant in your code.

If you do, I recommend following standard conventions for naming constants:

  • Use uppercase letters
  • Separate words with underscores

For example:

var APP_TITLE = "iOSWebApp";
var VERSION_NUM = "2.01";
var MAX_WIDTH = 320;

You can then use these constant-looking variables just as you would a variable throughout your script.

Operators

An operator is a no-frills symbol used to assign values, compare values, manipulate expressions, or connect pieces of code together.

The equal sign is perhaps the most common operator and you use it to assign a value to an expression. For example:

var i = 10;

Note that the operator you use to assign a value (=) is different than the operator you use to compare whether two values are equal. The == operator is charged with comparing two items and returning true if conditions are true. For example:

alert(n == 100);

As you may expect, you can use the + operator to add two number values together. However, you can also use it to combine two string literals or variables together. So, check out this code:

var s = "Welcome ";
var t = " to the world of operators.";
alert(s + t);

The text Welcome to the world of operators is displayed in a JavaScript alert box.

Tables 2-4 through 2-7 highlight the major operators. Some of the operators are pretty esoteric in most real-world situations, so the ones you typically use are shown in bold.

TABLE 2-4: Assignment Operators

OPERATOR EXAMPLE DESCRIPTION
= x=y The value of y is assigned to x
+= x+=y Same as x=x+y
-= x-=y Same as x=x-y
*= x*=y Same as x=x*y
/= x/=y Same as x=x/y
%= x%=y Same as x=x%y (modulus, division remainder)

TABLE 2-5: Comparison Operators

OPERATOR EXAMPLE DESCRIPTION
== x==y x is equal to y
!= x!=y x is not equal to y
=== x===y Evaluates both for value and data type (for example, if x = “5” and y = 5, then x==y is true, but x===y is false)
< x<y x is less than y
<= x<=y x is less than or equal to y
> x>y x is greater than y
>= x>=y x is greater than or equal to y
?: x=(y<5) ? -5: y If y is less than 5 then assign -5 to x; otherwise, assign y to x (known as the Conditional operator)

TABLE 2-6: Logical Operators

OPERATOR EXAMPLE DESCRIPTION
&& if ( x > 3 && y=0 ) logical and
|| if ( x>3 || y=0 ) logical or
! if !( x=y) not

TABLE 2-7: Mathematical operators

OPERATOR EXAMPLE DESCRIPTION
+ x+2 Addition
- x-3 Subtraction
* x*2 Multiplication
/ x/2 Division
% x%2 Modulus (division remainder)
++ x++ Increment (same as x=x+1)
-- x-- Decrement (same as x=x-1)

Reserved Words

JavaScript has a set of reserved words (see Table 2-8) that are set aside for use with the language. As a result, avoid using these words when you name variables, functions, or objects.

TABLE 2-8: JavaScript Reserved Words

image

Basic Conditional Expressions

JavaScript has three conditional statements that you can use to evaluate code:

  • if
  • if/else
  • switch

These three statements are explained in the following sections.

if Statements

The if statement is used when you want to evaluate a variable and expression and then perform an action depending on the evaluation. The basic structure looks like the following:

if (condition)
{
// code to execute if condition is true
}

For example:

response = prompt("Enter the name of the customer.", "");
if (response == "Jerry Monroe")
{
alert("Yes!");
}

A prompt box is displayed to the user. The typed response of the user is assigned to the response variable. The if statement then evaluates whether response is equal to “Jerry Monroe.” If so, then the alert box is displayed. Otherwise, if block is ignored.

I mentioned this in the operator section earlier in the chapter, but it bears repeating. The double equal signs are not a typo. A single equal sign (=) is used to assign a value to a variable whereas a double equals sign (==) compares one side of an expression with another.

If you are evaluating a Boolean variable, you write the if statements in two ways:

if (isValid == true)
{
  alert("Yes, it is valid!");
}

or, as a shortcut:

if (isValid)
{
  alert("Yes, it is valid!");
}

If you have a single line of code in the if block, you can actually forgo the curly brackets. So, the following syntax works, too:

if (isValid == true) alert("Yes, it is valid!");

You can also use if on a negative expression. Suppose, for example, that you want to perform an operation if a Boolean variable named isValid is false. The code would look something like this:

if (isValid == false)
{
  // do something to get validation
}

Notice that even though the false value is being used to evaluate the variable, the if block only executes if the expression (isValid == false) is true.

An alternative and usually preferred way to write this expression is to use the not operator (!):

if (!isValid)
{
  // do something to get validation
}

This expression says, in effect, if isValid is not true, then do something . . .

if/else Statements

The if/else statement extends the if statement so that you can also execute a specific block of code if the expression evaluates to true and a separate block if it is false. The basic structure is the following:

if (condition)
{
// code to execute if condition is true
}
else
{
// code to execute if condition is false
}

Here’s an example of the if/else statement:

if (showName)
{
  document.write("My name is Sonny Madison.")
}
else
{
  document.write("I cannot disclose my name.");
}

Chaining if and if/else

You can also chain together if and if/else statements. Consider this scenario:

if (state = "MA")
{
  document.write("You live in Massachusetts.");
}
else if (state="CA")
{
  document.write("You live in California.");
}
else
{
  document.write("I have no idea where you live.");
}

switch Statements

Besides chaining the if and if/else statements, you can use the switch statement to evaluate multiple values. Its basic structure is like this:

switch (expression)
{
case label1:
  // code to be executed if expression equals label1
  break;   
case label2:
  //code to be executed if expression equals label2
  break;
case label3:
  //code to be executed if expression equals label3
  break;
default:
  // code to be executed if expression is different
  // from both label1, label2, and label3
}

The switch statement evaluates the expression to see if the result matches the first case value. If so, then the code inside of the first case statement is executed. Note break at the end of each of the case statements. It stops the switch statement from continuing to evaluate more of the case statements that follow. The default statement is executed if no matches are found.

Note that the case blocks do not use curly braces inside them.

Here’s an example that uses the switch statement to evaluate the current time of day using the built-in Date() object:

var d = new Date()
var hrs = d.getHours()
 
switch (hrs)
{
case 7 :
  document.write( "Good morning." );
  break;
case 12 :
  document.write( "It must be time for lunch." );
  break;
case 15 :
  document.write( "Afternoon siesta. Zzzzz." );
  break;
case 23 :
  document.write( "Bed time. Boo!" );
  break;
default
  document.write( "Check back later." );
}

The hrs variable is assigned the current hour using the Date,getHours() method. The switch statement evaluates hrs, examining whether this value matches the case statements in sequence. If it finds a match then the code inside of the case is executed. Otherwise, the default statement is executed.

Loops

A common need that you will have in developing scripts in your IOS Web apps is the ability to perform a given task several times or on a series of objects. Or you might find you need to execute code until a condition changes. JavaScript provides two programming constructs for these purposes: for and while blocks. A for loop cycles through a block of code x number of times. A while loop executes a block of code as long as a specific condition is true.

for Loops

Along with the if statement, the for loop is likely the construct you’ll use most often. The following snippet shows a for loop calling document.write() five times:

for (var i=1;i<=5;i++)
{
  document.write("Number:" i + "<br/>");
}

When run, the output is the following:

Number 1
Number 2
Number 3
Number 4
Number 5

Going back to the code, notice the three parts of the for statement inside of the parentheses:

  • Initialize variable: The var i=1 initializes the variable used in the count. (The variable i is the typical name you see used for most loop counters.)
  • Looping condition: The i<=10 indicates the condition that is evaluated each time the loop is cycled through. The condition returns true as long as the i value is less than or equal to 10.
  • Update: The i++ statement is called after a pass of the loop completes. The ++ is the operator used to increment the value of i by 1.

while and do/while Loops

A while loop also cycles through a block of code one or more times. However, it continues as long as the expression evaluates to true. Here’s the basic form:

while(expression)
{
  // statements
}

Here’s an example:

var max = 100;
while(num>max)
{
document.write("Current count: " + num);
num++;
}

In this example, the code block loops as long as num is less than 100. However, suppose that num has the value of 101; the while code block is never executed.

The do/while loop is similar except that the condition evaluates at the end of the loop instead of at the start. Here’s the basic structure:

do
{
   // statement
} while (expression)

In real-world practice, while loops are used more often than do/while loops.

Comments

As in HTML or other languages, you can add your own comments to your JavaScript code. Comments are useful for you personally when you go back into the code weeks or months later and need to understand your code and the thought process behind it. You also might use comments to note specific places in the code that you need to rework later.

You can add single-line or multiline comments.

Single-line Comments

To add a single-line comment, add two slashes (//) to a line. Any text on the same line to the right of the slashes is considered a comment and is ignored by the interpreter. For example:

// Define two string variables
var s = "Welcome ";
var t = " to the world of operators.";
// Display concatenated values in an alert box
alert(s + t);

Multiline Comments

You can also define a comment that spans multiple lines. To do so, enclose the comments inside /* and */ marks. Here’s what a multiline comment looks like:

/*
 * Purpose: Converts Internet string date into Date object 
 * RICH TO DO: Double-check that this works under all cases
*/ 
function getDateFromString(s)
{
  s = s.replace(/-/g, "/");
  s = s.replace("T", " ");
  s = s.replace("Z", " GMT-0000");
  return new Date(Date.parse(s));
}

Using JSDoc Comments

The Java world has a documentation generator called Javadoc, which is a tool that can generate HTML-based documentation from the comments a developer adds to the source code. JSDocToolkit is an open-source tool written in Perl that provides similar functionality.

You can download JSDoc at http://code.google.com/p/jsdoc-toolkit/.

To enable a script for JSDoc Toolkit, simply denote the comments you wanted to be included using a multiline comment, but use the following special syntax: Open the comment with a slash and two asterisks (/**) and close the comment the normal way (*/). Here’s an example:

/**
 * Converts Internet string date into Date object 
*/ 
function getDateFromString(s)
{
  s = s.replace(/-/g, "/");
  s = s.replace("T", " ");
  s = s.replace("Z", " GMT-0000");
  return new Date(Date.parse(s));
}

You can also add several attributes that can be used to better describe the code. These attributes are prefixed with an @ sign. You can even add HTML tags for readability. Check this out:

/**
 * Converts Internet string date into Date object.
 * <p>
 * This function is called when the user selects the
 * Cyborg opton in the left-hand module of the doohing.
*
 * @param  s string containing the
 * @returns  the date as a Date object
*/ 
function getDateFromString(s)
{
  s = s.replace(/-/g, "/");
  s = s.replace("T", " ");
  s = s.replace("Z", " GMT-0000");
  return new Date(Date.parse(s));
}

For full details on available attributes, formatting commands, and syntax rules, check out http://code.google.com/p/jsdoc-toolkit/ as well the Javadoc conventions page at http://java.sun.com/j2se/javadoc/writingdoccomments.

Even if you don’t plan on using JSDocToolkit to create source code documentation, the JSDocToolkit conventions are still very useful for creating well-documented code. Plus, you may find in the future that if you would like to use the JSDocToolkit, you’re all set.

Functions

A function is the basic building block or organizing unit of JavaScript. A foundation of a house is composed of many building blocks. In the same way, a JavaScript script usually consists of a set of functions.

These building blocks may be easy to take for granted. But just as a beautifully decorated home means nothing apart from its foundation, a killer JavaScript animation routine is pretty meaningless without these building blocks to rest upon.

Creating a Function

A function is a module of JavaScript statements that together perform a specific action.

TRY IT OUT: Creating a Function

Follow the instructions below to create a JavaScript function.

1. Create the following HTML document in your text editor and then save the document as BIDHJ-Ch02-Ex2.html.

image
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
         "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Video</title>
<meta name="viewport" content="width=320; initial-scale=1.0;
  maximum-scale=1.0; user-scalable=0;"/>
<style type="text/css">
 
body
{
  background-color: #080808;
  margin: 10;
  color: #ffffff;
  font-family: Helvetica, sans-serif;
font-size:10px; 
}
 
</style>
<script type="text/javascript">
 
</script>
</head>
<body>
</body>
</html>

Code snippet BIDHJ-Ch02-Ex2.html

2. Add the addAndDisplay() function inside the script element:

image
function addAndDisplay(a,b)
{
  var total = a + b;
  alert(total);
}

Code snippet BIDHJ-Ch02-Ex2.html

3. Inside the script element, add the following code just after the function you just defined:

image
addAndDisplay(3, 2);

Code snippet BIDHJ-Ch02-Ex2.html

4. Save the file.

How It Works

When the page loads the script, it executes addAndDisplay(3, 2) to display an Alert message box that displays the calculated total. As you can see, the function you created named addAndDisplay() takes two arguments: a and b. An argument (also called a parameter) is a variable or literal value that you want to pass on to the function to process. In this case, the calling function sends the 3 and 2 integer values to the function add them together. Inside the curly brackets the first line adds together the arguments and assigns the sum to the total variable. The second line displays the total in an alert box. When the alert box is closed the function ends and returns control to the code that called it.

As you can see from the preceding Try It Out, a function:

  • Gets called by another section of code to perform a process, return a result, or both
  • Hides the details of its programming logic from other parts of the code

A function can return a value to the calling code. For example, check out the following function:

function getTotal(subtotal)
{
  var t = subtotal * .05;
  return t;
}

The getTotal() function receives subtotal as an argument, multiplies it by the state tax percentage, and then returns the total value to the statement that called the function using the return command.

When return executes, the function stops executing at that line and returns to the calling function. For example:

function createProfile(el)
{
  if (el == null)
  {
    alert("Undefined DOM element. Cannot continue. :(");
    return;
  }
  else
  {
     // do something really important to el
  }
}

In this example, the function checks to see if the el parameter is null. If so, then the function ends processing after displaying an alert box. If not, then the function continues on.

Creating an Inline Function

JavaScript also supports inline functions, which enable you to define an unnamed function for use within a specific context. For example, suppose you want to display an alert message when the window loads. Using a normal function, you could structure your script as follows:

<script>
  function init()
  {
    alert("I am saying something important.");
  }
 
  window.onload = init;
 
</script>

The onload event is assigned the init() function as its event handler. However, you could also use an inline function and eliminate the specific function definition:

<script>
  window.onload = function(){alert("I am saying something important.")}
</script>

Another advantage is that you can reference variables within a specific scope without having to pass them to a function as arguments.

Overloading Functions

Function overloading is a concept of being able to pass varying numbers of arguments to a function. You can overload a function in JavaScript if you make use of the arguments property of a function. For example, suppose you want to create a function that adds two numbers together and then returns the result. You could code it like this:

function add(a, b)
{
  return a+b;
}

However, suppose your needs change over time. Instead of two numbers, you now need to add three or four or five numbers at a time. Instead of writing separate functions for each case, you could overload the add() function to do all of these summing tasks:

function add()
{
  var t = 0;
  for (var i=0, l=arguments.length; i<l; i++)
  {
    t += arguments[i];
  }
  return t;
}

The add() function creates a for loop to iterate through each of the supplied arguments. As it does so, it adds the current argument to the t variable. This total is then returned back to the statement that called the function. Each of the following calls now work:

var t = add(2,2);
var t1 = add(2,4,5);
var t2 = add(392,1230,3020202,1,2033);

You could also use the typeof() command to overload different data types inside of the same function. For example, if I want to expand the functionality of add() to “add” string values, I could modify the function as follows:

function add()
{
  var argType = typeof(arguments[0]);
 
  if (argType == "number")
  {
    var t = 0;
    for (var i=0, l=arguments.length; i<l; i++)
    {
      t += arguments[i];
    }
    return t;
  }
  else if (argType == "string")
  {
    for (var i=0, l=arguments.length; i<l; i++)
    {
      if (i == 0)
      {
        var s = arguments[i];
      }
      else
      {
        s += ", " + arguments[i];
      }
     return s;
    }
    else
      return "Unsupported data type";
  }
}

The add() function examines the type of the first parameter and assigns the result to argType. If the type is a number then the routine continues just like the earlier example. If the type is a string, however, then the function combines the arguments into a single comma-delimited string. If the type is neither a number nor a string then an error message is returned.

Data Types

JavaScript enables you to work with specific data types:

  • String
  • Number
  • Boolean
  • Null
  • Undefined
  • Array
  • Object

Strings, numbers, and Booleans are often known as primitive data types, null and undefined as special data types, and objects and arrays as composite data types.

Strings

A string is a collection of characters enclosed in single or double quotation marks. A string is also called a string literal. The following lines are examples of strings:

var wd = 'Kitchen sink';
var el = "<p>This is HTML.</p>";
var n = "3.14";
var char = 'z';
var special = "@#(*&^%$#@!~<>S"}{+=";
var blank = "";

As you can see, you can include most anything in a string — normal text, HTML tags, numeric values, special characters, and even “the kitchen sink.”

Notice that you can have an empty string (“”), which is not the same as a null or undefined value.

Because you can enclose a string in either single or double quotation marks, you can easily embed a quotation mark and apostrophe by using the opposite type pair to enclose the string literal. For example:

var str =
'"I like living dangerously", said Jack. "I am enclosing a quote in this string."';
var str2 = "I'm happy, aren't I?";

Alternatively, you can use the backslash character () to “escape” an apostrophe or quotation mark if the string is enclosed by the same type of mark. Here are a couple cases:

var str2 = 'I'm happy, aren't I';
var el = "<div id="container"></div>";

The backslash character tells the interpreter to treat the following quote mark as part of the string rather than as the ending delimiter.

For many tasks, you can work with string values as string literals in the manner in which I described. However, if you are going to parse, manipulate, transform, or otherwise pick on a string, then you can also treat it as a String object.

Numbers

The number data type represents any sort of numeric value — integer, real floating-point number, octal, and even hexadecimal numbers.

Table 2-9 lists the variety of number values that are valid within JavaScript.

TABLE 2-9: Examples of Numbers

NUMBER DESCRIPTION
32 Integer
.00223 Floating-point number
1.42e5 Floating-point number
0377 Octal value
0x32CF A hexadecimal integer

In addition to these normal number types, JavaScript also contains a special value NaN, which stands for “not a number.” As you might expect, if you perform an invalid math operation, you get NaN as the result.

Boolean Values

A Boolean type represents either a true or false value. You typically use it to determine whether a condition in your code is true or false. For example, suppose you assign false to the flagUser variable:

var flagUser = false;

You can then evaluate the flagUser variable to determine its Boolean state in an if control structure (see the “if/else Statement” section earlier in this chapter). For example:

if (flagUser == true)
{
  alert("Hey User! You are hereby flagged.");
}

The if statement displays the alert box if flagUser evaluates to true.

Note that a Boolean value is not wrapped in quotation marks. So notice the difference:

// Boolean
var isABoolean = true;
var isAString = "true";

Null Values

When a variable or object contains no value, then its value is expressed as null. (Not the literal string "null", just null.) You can test whether or not a variable or object is null to determine if it has been defined earlier in the code. For example:

if (myArray != null)
{
  doSomethingReallyImportant();
}

This code block evaluates the variable myArray. If its value is not equal to null then the condition evaluates to true and something really important happens.

A null value is not the same as an empty string, the number 0 or NaN, or the undefined data type that I explain in the next section.

If you want to remove the contents of the variable, you can assign it a non-value by setting it to null:

if (loggedOut == true)
{
  userName = null;
}

So, in this example, if the loggedOut variable is true then the userName variable is reset.

Undefined Values

On first take, an undefined value sounds like just another name for null. But an undefined value is actually a different data type. An undefined value is returned by the interpreter when you access a variable that has been declared but never assigned a value. For example, the following snippet displays an alert box with undefined as the message.

var isSmiling;
alert (isSmiling);

You also get undefined if you try to call a property that does not exist. For example:

alert(document.theStreetThatHasNoName);

Arrays

So far, I’ve been talking about variables as individuals. An array, in contrast, is a collection of values. They are grouped together and indexed so that you can access a specific item stored in the group.

JavaScript stores arrays as Array objects, which means that it has a variety of properties and methods, which you can use to perform a variety of tasks.

Creating an Array

You can create a new array by assigning a variable to empty brackets:

var castMembers = [];

You can also create a new array by using new Array(). It goes like this:

var myArray = new Array();

However, using the new operator to create an array is considered old school and is not considered a good practice.

In some programming languages, you need to specify the number of items in an array at the time you define it. This is not so with JavaScript. The size of the array increases each time you add a new item to it.

Adding Items to an Array

To add items to the array, simply assign a value to a specific index in the array. The index is designated by a value within brackets, such as the following:

var castMembers = [];
castMembers[0] = "Jerry";
castMembers[1] = "George";
castMembers[2] = "Elaine";
castMembers[3] = "Kramer";

Notice that, because arrays are zero-based, you start counting at 0 rather than 1.

You can also define the array items by passing values in as parameters:

var primeNumbers = [1,3,5,7,11];

Storing Multiple Types in an Array

You can store most any kind of data in an array, including strings, numbers, Boolean values, undefined and null values, objects, and functions. You can even store an array within an array if you really want to. What’s more, you can store various types of data within the same array. For example, consider the following array that contains a string, number, function, DOM object, and Boolean value:

var el = document.getDocumentById("easy_bake_oven");
var pieLove = ["pie", 3.14, function(){alert("Apple Pie")}, el, true];

Getting and Setting the Size of an Array

You can get the number of items in an array by accessing its length property. (Yes, an array is an object, so it has its own set of properties and methods.) For example:

var primeNumbers = [1,3,5,7,11];
alert(primeNumbers.length));

The alert box displays 5.

In most cases, you don’t need to explicitly set the size of an array because it dynamically resizes on its own when you add or remove items from it. However, in cases in which you need to specify an array’s size, you can assign a value to the length property. For example, the following line increases the size of the array to 10:

primeNumbers.length = 10;

Note that no new data items are created when you do this.

If you specify a length that is smaller than the current size of the array then the items that fall outside of that length value get the axe.

Keep in mind that the last item in the array has an index value one less than the total number of elements in an array.

Accessing Items in an Array

You can access any value in the array according to its index. For example, to write the third item in a states array to the document, you could use the following code:

function showHomeState(idx)
{
  document.write("<p>Your home state is " + states[idx] + "</p>";
}

You can also iterate through an array using a for loop if you want to work with each item in the group:

var castMembers = [];
castMembers[0] = "Jerry";
castMembers[1] = "Jan";
castMembers[2] = "Elias";
castMembers[3] = "Bob";
document.writeln("<ul>");
for(i=0, l=castMembers.length; i<l; i++)
{
  document.writeln("<li>" + castMembers[i] + "</p>");
}
document.writeln("</ul>");

In this example, the castMembers array defines four string items. The length property is used to determine the size of the array, so I know the number of times to loop through the for structure.

Notice that the length property is assigned to a variable rather than being included directly inside the for loop like this:

// Valid, but less efficient
for(i=0; i<castMembers.length; i++)
{
}

Although that loop is perfectly valid, it is not as efficient, particularly for large arrays. The reason is that the interpreter has to evaluate the length property on each pass rather than only one time. Therefore, it is a good habit to assign an array’s length to a variable for loops.

The HTML output for this script is as follows:

<ul>
<li>Jerry</li>
<li>Jan</li>
<li>Elias</li>
<li>Bob</li>
</ul>

Passing by Reference or Value

When a primitive variable (string, number, or Boolean) is passed into an array, the array creates a copy of the variable’s value rather than storing a reference to that variable. In programming lingo, this is known as passing by value. Here’s an example that demonstrates the difference:

var n = 100;
var b = true;
var s = "string";
ar = [n, b, s];
 
document.write("<p>[First pass]</p>");
for (i=0; i<=2; i++)
  document.write("<p>"+ar[i]+"</p>");
 
n = 200;
b = false;
s = "new and improved string";
 
document.write("<p>[Second pass]</p>");
for (i=0; i<=2; i++)
  document.write("<p>"+ar[i]+"</p>");

Notice that the variables n, b, and s are passed as parameters in the ar array. The for loop then outputs the values of the array items as HTML content to the document. The variables are updated and given new assignments. However, when the same for loop is run again, the original values are output. Check out the HTML content that is output:

[First pass]
100
true
string
[Second pass]
100
true
string

However, when you pass an object or a function into an array, the array stores a reference to those advanced data types rather than a copy of it. As a result, any changes you make to the object or function outside of the array are reflected when you access its corresponding item in the array. This is called passing by reference.

EXERCISES

1. What keyword is used to declare a variable in JavaScript?

2. What is the difference between a local and global variable?

3. How are the = and == operators used differently?

4. What operator is used to compare whether two values are unequal to each other?

5. Write down the basic structure of a for loop that loops through 10 times.

6. Within a function, how would you check to the see the total number of parameters that were passed to the function?

7. Is an empty string "" the same as a null value?

Answers to the Exercises can be found in the Appendix.

• WHAT YOU LEARNED IN THIS CHAPTER

TOPIC KEY CONCEPTS
Embedding video or audio into your app Add a video or audio element to your HTML file.
Variables A variable is an alias that stores another piece of data.
Scope of variables Variable scope refers to the context of the variable, which can be local (specific to one piece of code) or global (accessible across the document).
Conditional expressions Use if, if/else, or switch to add conditional logic to your JavaScript.
Loops A for loop cycles through a block of code x number of times. A while loop executes a block of code as long as a specific condition is true.
Functions A function is a basic organizing unit of JavaScript specified with the function keyword.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset