<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
    xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:wfw="http://wellformedweb.org/CommentAPI/"
    xmlns:dc="http://purl.org/dc/elements/1.1/"
    xmlns:atom="http://www.w3.org/2005/Atom"
    xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
    xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
    >

<channel>
    <title>Webmonkey &#187; thau</title>
    <atom:link href="http://www.webmonkey.com/tag/thau/feed/" rel="self" type="application/rss+xml" />
    <link>http://www.webmonkey.com</link>
    <description>The Web Developer&#039;s Resource</description>
    <lastBuildDate>Fri, 05 Apr 2013 20:20:46 +0000</lastBuildDate>
    <language>en-US</language>
    <sy:updatePeriod>hourly</sy:updatePeriod>
    <sy:updateFrequency>1</sy:updateFrequency>
    <generator>http://wordpress.org/?v=3.4.2</generator>
    
    <item>
        <title>JavaScript Tutorial &#8211; Lesson 2</title>
        <link>http://www.webmonkey.com/2010/02/javascript_tutorial_-_lesson_2/</link>
        <comments>http://www.webmonkey.com/2010/02/javascript_tutorial_-_lesson_2/#comments</comments>
        <pubDate>Tue, 16 Feb 2010 01:45:47 +0000</pubDate>

                <dc:creator>Webmonkey Staff</dc:creator>

        <guid isPermaLink="false">http://stag.wired.com/primate/?p=709</guid>
        		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[thau]]></category>
		<category><![CDATA[wiki]]></category>
        <description><![CDATA[Review In the last lesson, you learned about where JavaScript goes and how it looks. Now it&#8217;s time to start learning the language. In this lesson, you&#8217;ll learn how JavaScript stores information, how it makes decisions based on that information, and how to change images based on user interaction. Ready? It&#8217;s time to learn the [...]]]></description>

            <content:encoded><![CDATA[<!-- wpautop disabled --><p><b>Review</b>

</p><p>In the last lesson, you learned about where JavaScript goes and how it looks. Now it&#8217;s time to start learning the language. In this lesson, you&#8217;ll learn how JavaScript stores information, how it makes decisions based on that information, and how to change images based on user interaction.

</p><p>Ready? It&#8217;s time to learn the fundamentals of computer programming. First stop, variables.

</p><br />
<span id="more-709"></span>

<table id="toc" class="toc" summary="Contents"><tbody><tr><td><div id="toctitle"><h2>Contents</h2> </div>
<ol>
<li><a href="#Variables">Variables</a></li>
<li><a href="#The_Body_of_the_First_Variable_Example">The Body of the First Variable Example</a></li>
<li><a href="#The_Magic_of_Strings">The Magic of Strings</a></li>
<li><a href="#Variable_Exercise">Variable Exercise</a></li>
<li><a href="#if-then_Branching">if-then Branching</a></li>
<li><a href="#Example_of_a_Simple_if-then_Statement">Example of a Simple if-then Statement</a></li>
<li><a href="#Link_Events">Link Events</a></li>
<li><a href="#Image_Swapping">Image Swapping</a></li>
<li><a href="#Lesson_2_Review">Lesson 2 Review</a></li>
</ol>
</td></tr></tbody></table>

<a name="Variables"></a><h4> <span class="mw-headline">Variables</span></h4>

<p>If you&#8217;ve taken algebra, you&#8217;ve seen variables. If you haven&#8217;t taken algebra, don&#8217;t worry about it. Variables are simply the way JavaScript stores information. For example, if you write &#8220;x=2,&#8221; &#8220;x&#8221; is a variable that holds the value &#8220;2.&#8221; If you then say &#8220;y=x+3,&#8221; &#8220;y&#8221; will hold the value &#8220;5.&#8221;

</p><p>Here&#8217;s an example of JavaScript that uses <a href="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/variableexample.html" class="external text" title="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/variableexample.html" rel="nofollow">variables</a>.

</p><p>View source on the example, and we&#8217;ll go through it step by step. Here&#8217;s what you see:

</p>

<pre class="brush: js"> &lt;script language="JavaScript"&gt;

 &lt;!-- hide me



</pre>

<p>These first two lines you&#8217;ve seen before. They&#8217;re the typical preamble to any JavaScript program.

</p>

<pre class="brush: js"> // load up some variables



var secs_per_min = 60;

var mins_per_hour = 60;

var hours_per_day = 24;

var days_per_year = 365;

</pre>

<p>The first line here is a comment. This comment states the obvious, but it&#8217;s nice to block off chunks of variable declarations.

</p><p>The next bunch of lines are variable declarations. There are a few things to notice about these lines:

</p><p>The first time you use a variable, you should declare it with the word &#8220;var.&#8221;

Although declaring variables with <code>var</code> is not strictly necessary, it&#8217;s usually a good idea. When we talk about functions two lessons from now, you&#8217;ll see why.

Variables must start with either a letter or the underscore character.

After the first character, variables can have numbers. So <code>monkey_23</code> is a fine variable name.

Variable names are case-sensitive.

This means that JavaScript will treat <code>Loop</code> and <code>loop</code> as two different variables. Generally, it&#8217;s a good idea to pick a naming convention and stick to it. I like having all my variables lowercase, with underscores separating words, like <code>secs_per_min</code> in the example above. Other people prefer using internal capitalization, like <code>secsPerMin</code>.

Variables should describe what they are.

Variables such as <code>x</code>, <code>y</code>, or <code>hack_hack_hack</code> aren&#8217;t very useful to a person who&#8217;s trying to figure out your script. Don&#8217;t make your variables so long that they take forever to type, but make them long enough to be descriptive.

You can give a variable a value when you declare it, or you can wait until later.

In the example, each variable was given a value the first time it was used. You don&#8217;t have to do this, and we&#8217;ll see examples later on where it&#8217;s nice to declare a variable even though we don&#8217;t know the value right away.

Statements end with a semicolon.

Statements are the sentences of JavaScript and semicolons are the end punctuation marks. Spaces and line breaks are ignored by the JavaScript interpreter, so the layout of the script serves only to make it more legible for people. This entire example could have been written in one really long line if you take out the comments. But that would be impossible to read.To be complete, I should mention that in some cases a semicolon isn&#8217;t necessary and you might see some scripts in which people leave them out. However, it&#8217;s always a good idea to put the semicolon in there. Not only does it make your program more legible, but it also makes it less likely that adding a line later will mess up your program. Always stick a semicolon at the end of a statement — it is the Webmonkey way.



</p>

<pre class="brush: js">// do some calculations

var secs_per_day = secs_per_min * mins_per_hour * hours_per_day;

var secs_per_year = secs_per_day * days_per_year;

</pre>

<p>Here we see some basic math. After JavaScript executes these statements, the variable <code>secs_per_year</code> will contain whatever you get when you multiply 60, 60, 24, and 365. From this point on, whenever JavaScript sees the variable <code>secs_per_year</code>, it will substitute in that huge number.

</p>

<pre class="brush: js"> // end hiding --&gt;

 &lt;/script&gt;

</pre>



<p>Nothing new here, just the normal way to end a piece of JavaScript.

</p><p>That&#8217;s all the JavaScript that&#8217;s in the header of this example. After JavaScript has executed all this code, the above variables will be declared and given values. That&#8217;s very nice, but we haven&#8217;t really done anything with the variables yet. That&#8217;s what happens in the body of the example.

</p>

<a name="The_Body_of_the_First_Variable_Example"></a><h4> <span class="mw-headline">The Body of the First Variable Example</span></h4>

<p>Now that we&#8217;ve defined the variables, let&#8217;s do something with them. We start JavaScript in the body of a page just like we do in the head:

</p>

<pre class="brush: js"> &lt;script language="JavaScript"&gt;

 &lt;!-- hide me

</pre>

<p>And here&#8217;s how we can use JavaScript to write variables and HTML to a web page:

</p>

<pre class="brush: js">// here's how to use JavaScript to write out HTML

document.writeln("&lt;b&gt;The monkey dances ");

document.writeln(secs_per_year);

document.writeln(" seconds per year.&lt;/b&gt;&lt;p&gt;");



</pre>

<p>Here are the interesting points about these three lines:

</p><p><code>document.writeln()</code> (as in &#8220;write line&#8221;) writes whatever&#8217;s between the parentheses to a web page.

There&#8217;s a surprising amount of detail involved in what <code>document.writeln()</code> really means. For now, just remember that when you&#8217;re between <code>&lt;script&gt;</code> and <code>&lt;/script&gt;</code> tags, you need to use <code>document.writeln("blah!")</code> to write HTML to your web page.

Characters inside quotes are printed; characters not inside quotes are considered variables.

Notice that in the first and third lines, quotes surround the thing we want printed, while there are no quotes around <code>secs_per_year</code>. Because there are no quotes around <code>secs_per_year</code>, JavaScript thinks it&#8217;s a variable and swaps in the value of the variable. Luckily, back in the header we defined <code>secs_per_year</code> to be some huge number, so that&#8217;s what gets printed. If we hadn&#8217;t defined <code>secs_per_year</code>, JavaScript would probably report an error. Anything between quotes is called a string and won&#8217;t get interpreted by JavaScript. This example uses double quotes (&#8220;), but it could also use single quotes (&#8216;). The two are interchangeable. If the second line were <code>document.writeln("secs_per_year")</code>, the JavaScript would write <code>secs_per_year</code> to the page, instead of <code>31,536,000</code>. This distinction between variables and strings is very important, so make sure you understand what I&#8217;m saying before you go on.

You can write HTML with the <code>document.writeln()</code> command.

Note the <code>&lt;b&gt;</code> and <code>&lt;/b&gt;</code> tags in the first and third lines.



</p><p>That&#8217;s the rundown on this example. One question that often comes up is, &#8220;What JavaScript goes in the head of a page and what goes in the body?&#8221;

</p><p>Usually it doesn&#8217;t matter, but it&#8217;s a good idea to put most of your JavaScript in the head of a page. This is because the head gets read before the body, so any variables that appear in the body (like <code>secs_per_min</code>) will already have been declared in the head by the time they&#8217;re needed. If for some reason <code>secs_per_min</code> were defined after JavaScript tried to do the <code>document.writeln(secs_per_min)</code> command, you&#8217;d get a JavaScript error.

</p><p>OK, we&#8217;re almost ready to do an exercise using variables, but first, a short note about strings.

</p>

<a name="The_Magic_of_Strings"></a><h4> <span class="mw-headline">The Magic of Strings</span></h4>

<p>As mentioned on the previous page, any group of characters between quotes is called a string. Either single or double quotes will do. Just as variables can hold numbers, variables can hold strings. So it&#8217;s legal to say:

</p>



<pre class="brush: js">var nice_monkey = "The monkey smiles at you and recites Shakespeare.";

var bad_monkey = "The monkey scowls at you and burps.";

</pre>

<p>Sticking these statements into a JavaScript declares the variables <code>nice_monkey</code> and <code>bad_monkey</code> and makes them equivalent to these strings. Once you&#8217;ve done this, you can write &#8230;

</p>

<pre class="brush: js">document.writeln(nice_monkey);

</pre>

<p>&#8230; whenever you want JavaScript to write out the long message about what nice monkeys do. Here&#8217;s an example of <a href="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/strings_example.html" class="external text" title="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/strings_example.html" rel="nofollow">what you can do with strings</a>. View source and we&#8217;ll go through the new and interesting parts of this script.

</p><p>The script starts with something new:

</p>



<pre class="brush: js">var monkey = prompt("What's the monkey's name?", "The monkey");

</pre>

<p>Here we&#8217;re calling the prompt method to get input from a user. When the prompt method is called, it brings up a dialog box that asks for a user&#8217;s input. When the user hits OK, the prompt returns whatever is in the input box. In the above line, this returned value gets put into the monkey variable.

</p><p>Notice that the prompt method takes two parameters, both of which are strings. The first parameter is what gets printed above the input field in the dialog box. In this case it&#8217;s, &#8220;What&#8217;s the monkey&#8217;s name?&#8221; The second parameter, &#8220;The monkey&#8221; in this example, is set as the default value of the input box. If you don&#8217;t want a default value, just put two quote marks as the second parameter. Like this:

</p>

<pre class="brush: js"> var monkey = prompt("What's the monkey's name?", "");

</pre>

<p>The next lines are a few straightforward variable assignments, like we&#8217;ve seen before. After these lines we see:

</p>

<pre class="brush: js">var techy_monkey = monkey + demanding + tech;

</pre>

<p>This line introduces a string operator:the plus sign. When the plus sign appears between two strings, or two variables that contain strings as above, it means &#8220;<a href="http://www.pcwebopedia.com/concatenate.htm" class="external text" title="http://www.pcwebopedia.com/concatenate.htm" rel="nofollow">concatenate</a>.&#8221; So the above line creates a new variable called <code>techy_monkey</code> that contains a string made of whatever the three variables contain. In this case, it&#8217;s &#8220;<code>The monkey</code>&#8221; + &#8220;<code>demands, no, insists upon receiving</code>&#8221; + &#8220;<code>a computer that won't crash, and a homemade browser!</code>&#8221; In other words &#8230;



</p>

<pre class="brush: js">var techy_monkey = monkey + demanding + tech;

</pre>

<p>&#8230; is the same as saying &#8230;

</p>

<pre class="brush: js">var techy_monkey = "The monkey demands, no, insists upon receiving a computer that won't crash, and a homemade browser!";

</pre>

<p>The next bunch of lines show some more tricks you can do with strings. All the tricks work in similar ways, so we&#8217;ll just look at three of them:

</p>

<pre class="brush: js">var italic_hippy = hippy_monkey.italics();&lt;/code&gt;

var shouting_hippy= hippy_monkey.toUpperCase();

var red_bold_tech = bold_tech.fontcolor('red');

</pre>

<p>The first of these lines says, &#8220;Take the string that&#8217;s contained in the variable <code>hippy_monkey</code> and put it in italics tags.&#8221; It&#8217;s actually the same thing as saying <code>var italic_hippy = "<i>" + hippy_monkey + "</i>";</code> But it looks much nicer. In either case, when you later write <code>document.writeln(italic_hippy)</code> in your JavaScript, you get the string in <code>hippy_monkey</code> printed in italics.



</p><p>The next line, which declares <code>shouting_hippy</code>, shows a string trick that you can&#8217;t do with HTML. It takes whatever&#8217;s in <code>hippy_monkey</code> and makes all the letters uppercase.

</p><p>The third line shows an example of changing a property of a string. All strings have color, and you can change the color of a string using the <code>string.fontcolor('new color');</code> command. You could also do this:

</p>

<pre class="brush: js">var red_bold_tech = "&lt;font color='red'&gt;" + bold_tech + "&lt;/code&gt;";

</pre>



<p>But that&#8217;s not as easy to read as this:

</p>

<pre class="brush: js">var red_bold_tech = bold_tech.fontcolor('red');

</pre>

<p>You&#8217;ve seen everything else in this example except this line:

</p>

<pre class="brush: js">document.writeln(bold_tech + "&lt;br&gt;");

</pre>

<p>This is just a normal <code>document.writeln()</code>, except instead of just printing a string, we&#8217;re concatenating two strings and then printing the result. This could have been done in two lines, like this:

</p>

<pre class="brush: js">var broken_bold = bold_tech + "&lt;br&gt;";

document.writeln(broken_bold);



</pre>

<p>But that would involve creating another variable, and writing another line, when it&#8217;s really unnecessary.

</p><p>Now that you&#8217;ve learned all about variables and strings, it&#8217;s time to try an exercise.

</p>

<a name="Variable_Exercise"></a><h4> <span class="mw-headline">Variable Exercise</span></h4>

<p>Try writing out this <a href="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/mad-lib.html" class="external text" title="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/mad-lib.html" rel="nofollow">mad-lib</a> without using any HTML between the <code>&lt;body&gt;</code> and <code>&lt;/body&gt;</code> tags.



</p><p>Once you&#8217;ve gotten this to work, it&#8217;s time to learn about if-then clauses.

</p>

<a name="if-then_Branching"></a><h4> <span class="mw-headline">if-then Branching</span></h4>

<p>What &#8220;if-then&#8221; statements do is allow your program to behave very differently depending on what a user inputs. For example, you could write a script that would act one way toward you and a different way toward everyone else. Here&#8217;s the basic form of an if-then statement:

</p>

<pre class="brush: js">if (some condition is true)

 {

     do something;

     do something;

     do something;

 }

</pre>

<p>The important parts of this structure are:

</p>

<ul><li> It starts with the word &#8220;<code>if</code>&#8221; (<code>if</code> must be lowercase).



</li><li> There is a condition in parentheses that is either true or false.

</li><li> There is a set of statements that should be executed if the condition is true. These statements go between curly brackets.

</li></ul>

<p>Remember, spacing is only there to make the script more legible. You can put the entire if-then statement on one line if you want, but that would be hard to read.

</p><p>Here&#8217;s an <a href="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/ifthenexample.html" class="external text" title="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/ifthenexample.html" rel="nofollow">example of an if-then statement</a> in action.

</p>

<a name="Example_of_a_Simple_if-then_Statement"></a><h4> <span class="mw-headline">Example of a Simple if-then Statement</span></h4>

<p>If you typed <code>yes</code> in the prompt box, you should have received a warm greeting before seeing the rest of the page. If you typed something else, you shouldn&#8217;t have received any greeting at all.



</p><p>Here&#8217;s the the heart of the script:

</p>

<pre class="brush: js">var monkey_love = prompt("Do you love the monkey?","Type yes or no");

if (monkey_love == "yes")

{

  alert("Welcome! I'm so glad you came! Please, read on!");

}

</pre>

<p>You&#8217;ve seen the first line before. It just brings up a prompt box and loads the user&#8217;s response into the variable <code>monkey_love</code>. The second line, however, has something new in it:a condition. This condition says that if the variable <code>monkey_love</code> equals the value &#8220;yes,&#8221; the script should run the statement between the curly brackets. If <code>monkey_love</code> equals something else, the statement will not be run.

</p><p>Note that the condition is <b>two</b> equal signs. This is one of those things that everyone messes up initially. If you put one equal sign instead of two, you&#8217;re telling JavaScript that <code>monkey_love</code> <i>should</i> equal &#8220;yes&#8221; instead of testing whether or not it actually <i>does</i> equal &#8220;yes.&#8221; Luckily, most browsers look for this sort of mistake and will warn you about it when you try to run your script. However, it&#8217;s best not to make the mistake in the first place.



</p><p>Other typical conditions are:

</p>

<pre class="brush: js"> (variable_1 &gt; variable_2)  is true if variable_1 is greater than variable_2

 (variable_1 &lt; variable_2)  is true if variable_1 is less than variable_2

 (variable_2 &lt;= variable_2)  is true if variable_1 is less than or equal to variable_2

 (variable_1&nbsp;!= variable_2)  is true if variable_1 does '''not''' equal variable_2

</pre>

<p>Two ways to make your conditions fancier:

</p><p>If you want two things to be true before running the statements in the curly brackets, you can do this:

</p>

<pre class="brush: js"> if ((age &lt; 21) &amp;&amp; (drinking_alcohol == "yes"))

 {

   document.writeln("Hey! You're too young to drink here!");

 }



</pre>

<p>Notice the two ampersands. That&#8217;s how you say &#8220;and&#8221; in JavaScript. Notice also that the whole clause, including the two sub-parts and the ampersands must be enclosed in parentheses.

</p><p>If you want either one of two things to be true before running the statements in the curly brackets, do this:

</p>

<pre class="brush: js"> if ((variable_1 == "bananas") || (variable_1 == "JavaScript"))

 {

   document.writeln("The monkey is happy because it has " +  variable_1);

 }

</pre>

<p>On to the if-then exercise! <a href="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/ifthenexercise.html" class="external text" title="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/ifthenexercise.html" rel="nofollow">Click here</a>.

</p><p>Once you&#8217;ve gotten this to work, it&#8217;s time to learn about link events.

</p>

<a name="Link_Events"></a><h4> <span class="mw-headline">Link Events</span></h4>

<p>Whenever a user clicks on a link, or moves her cursor over one, JavaScript is sent a link event. One link event is called <code>onClick</code>, and it gets sent whenever someone clicks on a link. Another link event is called <code>onMouseOver</code>. This one gets sent when someone moves the cursor over the link.



</p><p>You can use these events to affect what the user sees on a page. Here&#8217;s an example of <a href="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/linkevents.html" class="external text" title="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/linkevents.html" rel="nofollow">how to use link events</a>. Try it out, view source, and we&#8217;ll go over it line by line.

</p><p>The first interesting thing is that there are no <code>&lt;script&gt;</code> tags. That&#8217;s because anything that appears in the quotes of an <code>onClick</code> or an <code>onMouseOver</code> is automatically interpreted as JavaScript. In fact, because semicolons mark the end of statements allowing you to write entire JavaScripts in one line, you can fit an entire JavaScript program between the quotes of an <code>onClick</code>. It&#8217;d be ugly, but you could do it.

</p><p>Here&#8217;s the first line of interest:

</p>



<pre class="brush: js">&lt;a href="#" onClick="alert('Ooo, do it again!');"&gt;Click on me!&lt;/a&gt;

</pre>

<p>This is just like a normal anchor tag, but it has the magic <code>onClick=""</code> element, which says, &#8220;When someone clicks on this link, run the little bit of JavaScript between my quotes.&#8221; Notice, there&#8217;s even a terminating semicolon at the end of the alert.

</p><p>Also note that there&#8217;s a # sign between the quotes in the <code>href="#"</code>. This makes it so the browser doesn&#8217;t try to load another web page when you click on the link. If you put <a href="http://www.webmonkey.com/" class="external free" title="http://www.webmonkey.com/" rel="nofollow">http://www.webmonkey.com/</a> in the href instead of the #, the browser would run the JavaScript in the onClick and the load up this here Webmonkey site.

</p><p>Unfortunately, sometimes using the # sign causes the browser to jump to the top of the page when the link is clicked. To stop that from happening, change the link to this:

</p>



<pre class="brush: js">&lt;a href="#"onClick="alert('Ooo, do it again!');return false;"&gt;Click on me!&lt;/a&gt;

</pre>

<p>Notice the <code>return false;</code> following the alert inside the onClick. This tells JavaScript to stop the browser from even looking at what&#8217;s in the href. Because some very old browsers don&#8217;t understand the return false, people usually do both things:Put the # inside the href and put <code>return false</code> inside the <code>onClick</code>. That makes sure all browsers do the right thing.

</p><p>Here&#8217;s the next line:

</p>

<pre class="brush: js">&lt;a href="#" onMouseOver="alert('Hee hee!');"&gt;Mouse over me!&lt;/a&gt;



</pre>

<p>This is just like the first line, but it uses an <code>onMouseOver</code> instead of an <code>onClick</code>.

</p><p>Now that we&#8217;ve learned about link events, we can go into the wonderful land of image swaps.

</p>

<a name="Image_Swapping"></a><h4> <span class="mw-headline">Image Swapping</span></h4>

<p>One of the most commonly used features of JavaScript is the ability to change images on a mouseover.

</p><p>Here&#8217;s a quick and dirty example of a [# basic image swap].

</p><p>Let&#8217;s go through the example step by step. The first line of interest is:

</p>

<pre class="brush: js">&lt;img src="http://www.wired.com/images/archiveutton_r.gif" name="the_image"&gt;



</pre>

<p>This is just like a standard <code>&lt;img src= &gt;</code> tag except this one has been given a name:<code>the_image</code>. This name could be anything:<code>my_image</code>, <code>a_box</code>, whatever &#8211; but it can&#8217;t have any spaces in it.

</p><p>The next line of interest is:

</p>

<pre class="brush: js"> &lt;a href="#" onMouseOver="document.the_image.src='button_d.gif';"&gt;change&lt;/a&gt;



</pre>

<p>This is where the image swap happens. It&#8217;s just like the <code>onMouseOver</code>

</p><p>you saw before. The active piece of JavaScript, which appears in the quotes of the <code>onMouseOver</code> is this:

</p>

<pre class="brush: js">document.the_image.src='button_d.gif';

</pre>

<p>This statement says, &#8220;find the image called &#8216;<code>the_image</code>&#8216; and change its <code>src</code> to <code>button_d.gif</code>.&#8221; Note that there are double quotes around the whole statement, and &#8216;button_d.gif&#8217; takes single quotes. Although quotes are interchangable, if you have one set of quotes inside another set of quotes, the sets have to be of different kinds. So you could either do &#8221; &#8216;something&#8217; &#8221; or &#8216; &#8220;something&#8221; &#8216; but not &#8221; &#8216;something&#8221; &#8216; or &#8221; &#8220;something&#8221; &#8220;. Got it?



</p><p>Just as there was a lot of detail in what makes <code>document.writeln()</code> work, I&#8217;m not telling you exactly how this image swap is working. You&#8217;ll learn the details of both when we look at object-oriented programming and the Document Object Model in the next lesson.

</p><p>An important caveat about image swapping is that the image you&#8217;re switching to should be the same size as the original. If it&#8217;s not, it&#8217;ll get smashed or stretched to fit the original&#8217;s size.

</p><p>For now, you&#8217;re ready for today&#8217;s homework. <a href="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/JST_homework2.html" class="external text" title="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/JST_homework2.html" rel="nofollow">Click here</a>.

</p>

<a name="Lesson_2_Review"></a><h3> <span class="mw-headline">Lesson 2 Review </span></h3>

<p>To review, here are the things we covered today. If you feel like you didn&#8217;t learn one of these things, go back and hunt for it.

</p>

<dl><dt> Variables

</dt><dd>Variables can hold numbers and strings. There are a few restrictions and rules of thumb to keep in mind when naming variables.



</dd><dt> Statements

</dt><dd>Statments end in a semicolon.

</dd><dt> Strings

</dt><dd>Strings are sequences of characters in quotation marks. You can use either type of quote, single or double. There are lots of neat things you can do to manipulate the way a string will print out. And you can use + to concatenate two strings.

</dd><dt> document.writeln()

</dt><dd>Use <code>document.writeln()</code> to write text and HTML to a web page.

</dd><dt> prompt

</dt><dd>You can use <code>prompt</code> to get input from users.



</dd><dt> if-then-else

</dt><dd>You use <code>if-then-else</code> clauses to make your JavaScript behave differently depending on user actions.

</dd><dt> Link events

</dt><dd><code>onClick</code> and <code>onMouseOver</code> inside an <code>href</code> can be used to run bits of JavaScript that react to user actions.



</dd><dt> image swaps

</dt><dd>By naming images, we can use JavaScript to change what image is displayed.

</dd></dl>

<p>If you made it through all that stuff, Congratulations! It was a lot to learn. In <a href="/2010/02/JavaScript_Tutorial_-_Lesson_3" title="Tutorial:JavaScript Tutorial - Lesson 3">

 Lesson 3</a> we&#8217;ll be burrowing into the heart of JavaScript:the Document Object Model. We&#8217;ll also learn about how to open and manipulate windows and frames, and we&#8217;ll begin building our new browser. <br />

</p><p><br />

</p><div id='linker_widget' class='contextly-widget'></div>]]></content:encoded>
            <wfw:commentRss>http://www.webmonkey.com/2010/02/javascript_tutorial_-_lesson_2/feed/</wfw:commentRss>
        <slash:comments>1</slash:comments>

        
    </item>
    
    <item>
        <title>JavaScript Tutorial &#8211; Lesson 3</title>
        <link>http://www.webmonkey.com/2010/02/javascript_tutorial_-_lesson_3/</link>
        <comments>http://www.webmonkey.com/2010/02/javascript_tutorial_-_lesson_3/#comments</comments>
        <pubDate>Tue, 16 Feb 2010 01:45:47 +0000</pubDate>

                <dc:creator>Webmonkey Staff</dc:creator>

        <guid isPermaLink="false">http://stag.wired.com/primate/?p=711</guid>
        		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[thau]]></category>
		<category><![CDATA[wiki]]></category>
        <description><![CDATA[In earlier lessons, you&#8217;ve learned: How to add JavaScript to your HTML pages How to use dialog boxes and variables to store and utilize user input How to write HTML to a Web page using JavaScript How to let JavaScript make decisions using if-then statements How to make your Web pages react to users&#8217; actions [...]]]></description>

            <content:encoded><![CDATA[<!-- wpautop disabled --><p>In earlier lessons, you&#8217;ve learned:
</p>

<ul><li> How to add JavaScript to your HTML pages
</li><li> How to use dialog boxes and variables to store and utilize user input
</li><li> How to write HTML to a Web page using JavaScript
</li><li> How to let JavaScript make decisions using  <code>if-then</code> statements
</li><li> How to make your Web pages react to users&#8217; actions using link events
</li><li> How to do a basic image swap
</li></ul>
<p><br />

So far I&#8217;ve explained how to do many things, but I haven&#8217;t described why they work. In the last lesson, for instance, I showed you that <code>window.document.monkey_image.src = "happy_monkey.gif"</code> will swap <code>happy_monkey.gif</code> into an image named <code>monkey_image</code> . But what is that <code>window.document</code> stuff? And where does the <code>.src</code> come from? Similarly, you&#8217;ve seen <code>document.writeln("monkey")</code> . But why is it <code>document.writeln</code> and not just <code>writeln</code>&nbsp;?

</p><p>The answer to the above questions can be found in the JavaScript Document Object Model. The DOM is the way JavaScript describes Web pages, and it lies at the heart of all JavaScript programming. This lesson will teach you about the DOM, and the next lesson will teach you the rest of the basics of computer programming. By the end of the next two lessons, you will know all of the major ideas and syntax of JavaScript. All that will be left to learn are details, tricks, and how to avoid snafus.

</p><p>To start us off along the road to the DOM, let&#8217;s learn about how to use JavaScript to open and manipulate new browser windows.
<br />
<span id="more-711"></span>


<table id="toc" class="toc" summary="Contents"><tbody><tr><td><div id="toctitle"><h2>Contents</h2> </div>

<ol>
<li><a href="#Introduction_to_Window_Manipulation">Introduction to Window Manipulation</a></li>
<li><a href="#Window_Manipulation_in_JavaScript">Window Manipulation in JavaScript</a></li>
<li><a href="#Examples_of_Opening_Windows_with_JavaScript">Examples of Opening Windows with JavaScript</a></li>
<li><a href="#Windows_Features">Windows Features</a></li>
<li><a href="#The_JavaScript_Document_Object_Model">The JavaScript Document Object Model</a></li>
<li><a href="#Communicating_between_Windows">Communicating between Windows</a></li>
<li><a href="#More_about_the_JavaScript_Document_Object_Model">More about the JavaScript Document Object Model</a></li>
<li><a href="#Getting_Framed">Getting Framed</a></li>
</ol>
</td></tr></tbody></table>


<p><a name="Introduction_to_Window_Manipulation"></a><h4> <span class="mw-headline">Introduction to Window Manipulation</span></h4>

<p>Before learning how to open a window in JavaScript, you should know how to open one using HTML. In most recent browsers, you can open a new window using an <code>href</code> statement. Example:

</p><p><iframe src="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/windows1.html" name="page1" align="middle" frameborder="0" height="25" scrolling="no" width="500"></iframe>

<br /><br />

</p><p>The HTML used to do this is:

</p>

<pre class="brush: js">clicking &lt;a href="yer_new_window.html" target="yer_new_window"&gt;here&lt;/a&gt; will

open another window.



</pre>

<p>The important thing to know about windows opened by targeted links is that the window above now has the name &#8220;yer_new_window&#8221; associated with it. If you have another <code>href</code> that uses &#8220;yer_new_window&#8221; as the target, and you haven&#8217;t closed the window yet, whatever URL you put in that link will open in the original window.

</p><p><iframe src="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/windows2.html" name="page1" align="middle" frameborder="0" height="50" scrolling="no" width="500"></iframe>

<br /><br />

</p><p>For the purposes of this lesson, I&#8217;m going to call the target name, in this case <code>yer_new_window</code> , the name of the window.

</p><p>Now that we&#8217;ve had this brief refresher on <code>href</code> targets, it&#8217;s time to learn about opening windows in JavaScript.

</p>



<a name="Window_Manipulation_in_JavaScript"></a><h4> <span class="mw-headline">Window Manipulation in JavaScript</span></h4>

<p>While opening windows in HTML is very handy, it&#8217;s also limiting; the browser controls how the window looks. You have no control over the size of the window or what the window looks like. Happily, JavaScript gives you this control.

</p><p>Here&#8217;s how:

</p>

<pre class="brush: js">window.open("URL","name","features");

</pre>

<p>This statement opens a window with the URL that you list as the first parameter in the method call. Above it&#8217;s called &#8221; <code>URL</code>,&#8221; but in an actual call you&#8217;d write &#8221; <code>http://www.mysite.com/webmonkey/</code>&#8221; or something similar.

</p><p>The second parameter of the method call is the window&#8217;s name. This is just like the name we saw in the last page. If you open a window and there&#8217;s already a window open with the same name, the URL in your <code>open</code> statement will be sent to that open window.



</p><p>The third parameter, <code>features</code>, is a list of the different components a window can have. It&#8217;s an optional parameter, so let&#8217;s do some examples with the first two parameters before checking out <code>features</code>.

</p><p>Here are some examples of using JavaScript to open windows.

</p>

<a name="Examples_of_Opening_Windows_with_JavaScript"></a><h4> <span class="mw-headline">Examples of Opening Windows with JavaScript</span></h4>

<p>Try clicking on these three links and see what happens. Don&#8217;t close any of the windows until you&#8217;ve clicked on all three links.

</p><p><iframe src="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/windows3.html" name="page1" align="middle" frameborder="0" height="75" scrolling="no" width="500"></iframe>

<br /><br />

</p><p>Let&#8217;s take a look at how this is done. Here&#8217;s the first line:

</p>

<pre class="brush: js">&lt;a href="#" onClick="window.open('javascript_window_1.html','javascript_1');

return false;"&gt;Here's a window named javascript_1&lt;/a&gt;.



</pre>

<p>When you click on this link, a new window called <code>javascript_1</code> gets opened and the HTML page <code>javascript_window_1.html</code> gets put into the window. Because the <code>features</code> parameter is optional, you can just leave it out. This will give you the default window you would have gotten if you&#8217;d used a targeted <code>href</code> , as in the previous page.

</p><p>Notice that I put the call to open the window in an <code>onClick</code>. You don&#8217;t have to put <code>window.open()</code> calls inside an <code>onClick</code>, it was just convenient to do so in this example. You&#8217;ll see examples of <code>window.open()</code> inside <code>&lt;script&gt;</code> tags soon.



</p><p>The second link is almost exactly like the first link. It just opens a window with a different name and loads in a different HTML page:

</p>

<pre class="brush: js">&lt;a href="#" onClick="window.open('javascript_window_2.html','javascript_2');

return false;"&gt;Here's a window named javascript_2&lt;/a&gt;.

</pre>

<p>The third link sticks a new HTML page into the first window. This works because the third link opens a window with the same name as the first window:<code>javascript_1</code>.

</p>

<pre class="brush: js">&lt;a href="#" onClick="window.open('javascript_window_3.html','javascript_1');

return false;"&gt;Here's another HTML page going into javascript_1&lt;/a&gt;.

</pre>

<p>Now the fun begins. We can play with the <code>features</code> parameter to make our windows look very different.



</p><p>OK already, let&#8217;s play with windows features!

</p>

<a name="Windows_Features"></a><h4> <span class="mw-headline">Windows Features</span></h4>

<p>The third parameter of the <code>window.open()</code> method is a list of features that you&#8217;d like your window to have. As you&#8217;ve seen, if you don&#8217;t include this parameter at all, the window will contain all the features of a default browser window.

</p><p>However, if you specify any features in the third parameter, just those features will appear. The way to specify that you&#8217;d like your window to have certain features is to list them as a comma-separated list.

</p><p>For example, if you write &#8230;

</p>

<pre class="brush: js">window.open ("some_url","window_name","location,menubar");

</pre>

<p>&#8230; you&#8217;ll get a window with just the location box (the place in your browser where you type in a URL) and a menu bar (File, Edit, etc.). <b>Note:</b> that these code samples may wrap to fit here in your browser, but they should be all on one line, no spaces, when you actually use them.



</p><p>Here&#8217;s another example:

</p>

<pre class="brush: js"> window.open("some_url","window_name", "location,height=100,width=100");

</pre>

<p>This will open a window that is 100 pixels high and 100 pixels wide and has no features other than a location field. Notice again that there are no spaces in the string.

</p><p>If you&#8217;d like to open a window that has almost all the features, you can specify which features you don&#8217;t want by setting those features equal to no. For example:

</p>

<pre class="brush: js">window.open("some_url","window_name", "location=no,status=no");

</pre>

<p>This will open a window that has all the features except the location field and the status bar. Here&#8217;s a list of the features that you can include in the feature string:

</p>

<dl><dt>  <code>menubar</code>

</dt><dd>This is the row of functions that appears on most software applications. Normally it includes  <code>File</code>,  <code>Edit</code>, and a few other items.



</dd><dt>  <code>status</code>

</dt><dd>This is the message bar at the bottom of your window. When you move your mouse over an HTML link, the URL appears in the status bar. You may have seen pages that use JavaScript to turn this status bar into a scrolling marquee. I&#8217;m <b>not</b> going to show you how to do this. If you want to know, you have to figure it out yourself. &#8220;Down with marquees,&#8221; the monkey cried!

</dd><dt>  <code>scrollbars</code>

</dt><dd>This allows scrollbars to appear when necessary.

</dd><dt>  <code>resizable</code>

</dt><dd>If  <code>resizable</code> is listed, the window can be resized. Be careful of the spelling. I always get it wrong.



</dd><dt>  <code>width</code>

</dt><dd>The width of the window in pixels.

</dd><dt>  <code>height</code>

</dt><dd>The height of the window in pixels.

</dd><dt>  <code>toolbar</code>

</dt><dd>The browser toolbar, which contains the  <code>Back</code> and  <code>Forward</code> buttons, the  <code>Stop</code> button, and the  <code>Home</code> button, among others.



</dd><dt>  <code>location</code>

</dt><dd>The text area of a browser into which you can type URLs.

</dd><dt>  <code>directories</code>

</dt><dd>The directories that Netscape browsers have called &#8220;What&#8217;s new,&#8221; &#8220;What&#8217;s cool,&#8221; and so on.

</dd></dl>

<p>Here are some examples of <a href="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/windows_features_examples.html" class="external text" title="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/windows_features_examples.html" rel="nofollow">different types of windows</a>.

</p><p>Once you&#8217;ve checked out the examples, and maybe tried bringing up some windows of your own, it&#8217;s time to learn how to  mess with the contents of the windows.

</p><p>Be aware, however, that some browsers (like IE 7), have to be configured to allow Javascript to open new windows without the location, status, etc. So unless the visitors to your pages have customized their security settings to allow this kind of manipulation, IE 7 will continue to show the location, status and menu bars by default, no matter how much you try. I guess the good ol&#8217; boys at Microsoft think it&#8217;s a security risk for us to not be able to see these&#8230; Booo! Anyway, on with the <i>leccion</i>.

</p>



<a name="The_JavaScript_Document_Object_Model"></a><h4> <span class="mw-headline">The JavaScript Document Object Model</span></h4>

<p>Now that you know how to open the window of your choice, it&#8217;s time to learn how to manipulate things inside that window. To really get control over the things that appear in a window, you have to learn about the JavaScript Document Object Model (DOM). And before you learn about the DOM, it helps to learn a little bit about object-oriented programming.

</p><p><b>A Brief Overview</b>

</p><p>Object-oriented programming, especially the JavaScript version of it, isn&#8217;t so hard to understand. The main idea is that information is organized in terms of objects. JavaScript is wonderful because it comes with a built-in library of objects. For example, a window is an object. Whenever I refer to one of the default JavaScript library objects, I will capitalize it (Window). Specific instances (a particular window) will be lowercase.

</p><p><b>Object Properties</b>

</p><p>Objects have properties that describe them. Some of the properties of a Window object are its name, the words in its status bar, the URL of the document inside the window, and the window&#8217;s document itself, which includes the words, images, and hyperlinks inside the window.

</p><p>In JavaScript, you are given a default Window object called, of all things, <code>window</code>. One of the properties of a window is the words in its status bar. Here&#8217;s how you can find out what&#8217;s in the status bar of the default Window:

</p>

<pre class="brush: js">var the_status = window.status;

</pre>

<p>This says:&#8221;Find the <code>status</code> property of the Window object called <code>window</code> , and load it into the variable <code>the_status</code> .&#8221; In addition to reading what those words are, you can also change them. The way to set an object&#8217;s property is this:



</p>

<pre class="brush: js">window.status = "I'm monkeying around!";

</pre>

<a name="Communicating_between_Windows"></a><h4> <span class="mw-headline">Communicating between Windows</span></h4>

<p>Although it doesn&#8217;t make sense to blur or focus the window you&#8217;re on, you might well want to move another window to the fore. In order to communicate with a window using JavaScript, you need a reference to that window. Look at this example and then come back here for an explanation.

</p><p><font color="RED">This example may be too wonky with today&#8217;s tabbed browsers</font>

</p><p><iframe src="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/windows5.html" name="page1" align="middle" frameborder="0" height="25" scrolling="no" width="500"></iframe>

<br /><br />

</p><p>There are a few key lines in this JavaScript. First, we open a new window and get a reference to it:

</p>

<pre class="brush: js">var new_window = window.open("hello.html","html_name","width=200,height=200");

</pre>

<p>This opens a little window and assigns the variable <code>&lt;code&gt;new_window</code>&lt;/code&gt; to refer to it. Just as variables can contain numbers and strings, variables can also contain references to objects &#8211; in this example, a Window object. Now the variable <code>&lt;code&gt;new_window</code>&lt;/code&gt; will behave just like the default Window object. You can call methods on <code>&lt;code&gt;new_window</code>&lt;/code&gt; just like you could on <code>&lt;code&gt;window</code>&lt;/code&gt; .



</p><p>The next line shows you an example of calling a method on <code>new_window</code>:

</p>

<pre class="brush: js">new_window.blur();

</pre>

<p>Not too tricky, it&#8217;s just like <code>window.blur()</code> from the last page. These two lines appear in the head of the HTML page. View Source on the page if you want to see the whole thing. As I&#8217;ve mentioned, I tend to put my JavaScript code in the head of HTML pages. That way I can find it when I&#8217;m looking for it. These lines of JavaScript could just as easily have gone in the body.

</p><p>Now, moving to the body we see two links that will move the new window forward or backward:

</p>

<pre class="brush: js">&lt;a href="#" onMouseOver="new_window.focus();"&gt;Bring it forward&lt;/a&gt;

&lt;a href="#" onMouseOver="new_window.blur();"&gt;Put it backward&lt;/a&gt;



</pre>

<p>Get it? Let&#8217;s see &#8230; it&#8217;s time for an exercise. Try writing this <a href="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/window_ref_extension.html" class="external text" title="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/window_ref_extension.html" rel="nofollow">extension</a> <font color="red">(see above note)</font> to the previous window-reference example. This exercise is pretty tricky; to get it working, you&#8217;ll have to figure some things out. But give it a try before you View Source to check the answer.

</p><p>After you&#8217;re done, come back here and we&#8217;ll go on to discuss more about the JavaScript Object Model.

</p>

<a name="More_about_the_JavaScript_Document_Object_Model"></a><h4> <span class="mw-headline">More about the JavaScript Document Object Model</span></h4>

<p>So far we&#8217;ve learned that JavaScript includes default objects, like Windows. We&#8217;ve learned that objects have properties that describe them, and methods that describe what the objects know how to do. Now it&#8217;s time to delve a little deeper.

</p><p>One neat thing about objects is that the properties of an object can be objects too. For example, windows have a property called <code>document</code> that refers to the actual HTML document in the window. This <code>document</code> property is itself an object that has properties and methods of its own. We saw an example of this when we talked about image swapping. Harkening back to the last lesson, we learned that you can do an image swap like this:



</p>

<pre class="brush: js">&lt;a href="#" onMouseOver="window.document.the_image.src='button_d.gif';"&gt;change&lt;/a&gt;

</pre>

<p>That long string, <code>window.document.the_image.src='button_d.gif'</code>, translates into:&#8221;Find the document property of the window, find <code>the_image</code> property of the document, find the <code>src</code> property of <code>the_image</code>, and set it to <code>button_d.gif</code>.&#8221; Quite a mouthful, eh? It all works because windows are objects, documents inside windows are objects, and images inside the documents are objects too.



</p><p>It may seem like a lot of detail to keep track of, but actually it&#8217;s not too bad. The JavaScript Document Object Model describes a small hierarchy of objects. Here it is:

</p><p><img src="http://www.wired.com/wired/webmonkey/stuff/hierarchy.gif" alt="hierarchy.gif">

</p><p>The top box of the diagram represents your browser window. Following the line from that box down, you&#8217;ll see it connects to seven more boxes. These are the properties of the browser window. The sixth box there, &#8220;document,&#8221; represents the contents of your window. If you follow the little line leading out of the document box, you&#8217;ll see it connects to six more boxes. These are the properties of the document object. Notice that the fourth box is &#8220;images.&#8221; This is the list of all the images in your Web page. Because the images are properties of the &#8220;document,&#8221; which is a property of the &#8220;window,&#8221; the precise way to describe an image to JavaScript is to tell it to look at the &#8220;window,&#8221; find the window&#8217;s &#8220;document,&#8221; and in the document, look for the &#8220;image.&#8221;

</p><p>We&#8217;re going to be visiting the various properties of the document object in lesson 5. However, before you can extract the full potential of that object, you should know how to mess with the DOM in other windows.

</p><p>As we&#8217;ve seen, an image swap can be performed with a line like this:

</p>

<pre class="brush: js">window.document.the_image.src="button_d.gif";

</pre>

<p>This works by telling JavaScript to look at a window, find its

document, and then find the thing called <code>the_image</code> inside that document. Once JavaScript locates the image, it can change its src to whatever GIF we want.

</p><p>Sometimes it&#8217;s useful to have a link in one window change an image in another window. Imagine a slide show in which one window displays the images and another little window contains thumbnails of each slide show image.  Clicking on a thumbnail in the little window changes the image in the big window.

</p><p><font color="RED">This example may be too wonky with today&#8217;s tabbed browsers</font>

</p><p>To give you an idea of what I&#8217;m talking about, here&#8217;s an example of a remote slide show control:

</p><p><iframe src="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/windows6.html" name="page1" align="middle" frameborder="0" height="25" scrolling="no" width="500"></iframe>



<br /><br />

</p><p>There are two windows in this example:the remote control window, and the slide show display window. Clicking on the link above opens the remote control.  The remote control then automatically opens the display window by using this line between the &lt;head&gt; tags:

</p>

<pre class="brush: js">var display_window = &lt;br&gt;window.open("slide_show_main.html","display_window");

</pre>

<p>This opens a new window and assigns the variable <code>display_window</code> to that window. So now whenever we want to use JavaScript to refer to that window, we use the variable <code>display_window</code>.

</p><p>When the display window opens, there&#8217;s a chance it&#8217;ll open right on top of the remote. To ensure that the remote stays visible, we add this line, which executes after the display window opens:



</p>

<pre class="brush: js">window.focus();

</pre>

<p>Now that we&#8217;ve opened both the display window and the remote, we have to figure out how to make the links in the remote window change the image in the display window. If you view source on the display window, you&#8217;ll see that it&#8217;s very simple:It contains just one image, which I&#8217;ve named

</p><p><code>main_image</code>:

</p>

<pre class="brush: js">&lt;img src="sky.gif" name="main_image" height="400" width="400"&gt;

</pre>

<p>To have a link in the remote window change the image in the display window, we have to tell JavaScript to look at the display window (which we do with the <code>display_window</code> variable we assigned earlier), find its document, and locate the image called <code>main_image</code> inside that document. In JavaScriptese:



</p>

<pre class="brush: js">display_window.document.main_image

</pre>

<p>And here&#8217;s how you change the src of that image from the remote window:

</p>

<pre class="brush: js">display_window.document.main_image.src = 'sun.gif';

</pre>

<p>If you view source on the remote, you&#8217;ll see that I&#8217;ve stuck the above line into a link, like so:

</p>

<pre class="brush: js">&lt;a href="#" onClick=&lt;br&gt;

"display_window.document.main_image.src='sky.gif';return false;"&gt;&lt;img src="sky.gif"&gt;&lt;/a&gt;

</pre>



<p>Now that I&#8217;ve given you a taste of what you can do with the properties of the document object, let&#8217;s talk about a property of the window object:frames.

</p>

<a name="Getting_Framed"></a><h3> <span class="mw-headline">Getting Framed</span></h3>

<p>All the remaining properties of windows that we&#8217;ll see in this lesson relate to frames and how to use them with JavaScript. If you don&#8217;t know how to use frames, check out Jillo&#8217;s &#8220;Frames Are a Picnic.&#8221; Read Jillo&#8217;s wisdom, practice building a few framesets, and then come back. After I show you how to play with frames in JavaScript, I&#8217;ll give you your homework for the day.

</p><p>In JavaScript, frames are treated just like windows. Just as you can tweak the contents of one window using JavaScript inside a different window, you can change the contents of one frame using JavaScript in another frame.

</p><p><a href="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/frames_example.html" class="external text" title="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/frames_example.html" rel="nofollow">Here&#8217;s a straightforward example</a> of using frames with JavaScript. I&#8217;ll break it down line by line.

</p><p>The first thing we need to look at is the frameset. Here it is:

</p>

<pre class="brush: js">    &lt;frameset rows="25%,*"&gt;

    &lt;frame src="frames_example_controls.html" name="control_frame"&gt;



    &lt;frame src="blank.html" name="target_frame"&gt;

    &lt;/frameset&gt;

 </pre>

<p>This is just like any ordinary frameset. The important thing to note and remember is that the frames in the frameset are named. The first frame, called control_frame, holds the HTML page that contains the JavaScript. The second frame, as you can see from the src=&#8221;blank.html&#8221;, contains nothing.

</p><p>The second thing to look at is the contents of the control_frame. To keep things simple, it only has one interesting line:

</p>

<pre class="brush: js">    &lt;a href="#" onClick="top.target_frame.document.writeln('Monkey do!&lt;br&gt;');"&gt;Monkey see&lt;/a&gt;



</pre>

<p>This line tries to write the words &#8220;Monkey do!<br />&#8221; into the bottom frame. But before JavaScript can write to the frame, it has to know what frame we&#8217;re talking about. The expression top.target_frame, which you&#8217;ll see in the onClick, tells JavaScript to look at the top-most window, which is the browser itself, and find the thing called target_frame inside that window. Because we called the bottom frame &#8220;target_frame&#8221; when defining the frameset, JavaScript will know that target_frame means the bottom frame.

</p><p>Once we&#8217;ve told JavaScript which frame we&#8217;re talking about, we can treat the frame just like a window. To write the word &#8220;howdy&#8221; to a window called greeting_window, we&#8217;d do this:

</p>

<pre class="brush: js">    greeting_window.document.writeln("howdy");

</pre>

<p>This tells JavaScript to find the window named greeting_window, then find the document of that window, and then write the word &#8220;howdy&#8221; into that document. Yes, if you haven&#8217;t figured it out yet, writeln() is a method of the document object, which is why we&#8217;ve had to write document.writeln(&#8216;blah blah) instead of just writeln(&#8216;blah blah&#8217;).

</p><p>Because frames are treated just like windows, we can do a similar thing:

</p>

<pre class="brush: js">    top.target_frame.document.writeln("Monkey do!");

</pre>

<p>Now, let&#8217;s learn more about windows and frames.

</p><p>We&#8217;ve seen a couple of instances of built-in variables being used in the last few examples.  One of the built-in variables is <code>window</code>.  The <code>window</code> variable refers to whatever window the JavaScript is executing in.  If you have some JavaScript in a frame and you write <code>window.document.writeln()</code>, the <code>writeln</code> will happen in that frame.  People sometimes

use the built-in variable called <code>self</code> instead of <code>window</code>. The two (<code>window</code> and <code>self</code>) are interchangable.



</p><p>In the last example, you were introduced to the built-in variable called <code>top</code>. This will always refer to the top-most browser window.  If you want to start at the top of the window hierarchy, use <code>top</code>.

</p><p>Another built-in variable is <code>parent</code>, which refers to the window containing the frame you&#8217;re currently in.  If you have a frameset in a window, and one frame contains another frameset, the second frameset can refer to the enclosing frame using the <code>parent</code> variable.  This gets a little tricky so I&#8217;m not going to go into it, but here&#8217;s an <a href="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/recursive_frames.html" class="external text" title="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/recursive_frames.html" rel="nofollow">example</a> of using JavaScript with frames inside frames for you to look over.  Check it out or just go on to your <a href="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/JST_homework3.html" class="external text" title="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/JST_homework3.html" rel="nofollow">homework for Lesson 3</a>.

</p><p><br />



After you&#8217;re done with the assignment, be sure to review what we&#8217;ve covered this lesson.

</p><p>We covered four main topics today:windows, frames, the Document Object Model, and Object-Oriented programming. By now you should know about

</p>

<dl><dt> Opening windows

</dt><dd>How to open windows and make them look the way you want

</dd><dt> Communication between windows

</dt><dd>How to get JavaScript in one window to affect another window

</dd><dt> Communication between frames

</dt><dd>How to get JavaScript in one frame to affect other frames

</dd><dt> Objects

</dt><dd>Objects have properties and methods

</dd><dt> The Document Object Model



</dt><dd>A browser window is an object that comprises other objects. If you know the hierarchy of the objects in the DOM you know how to affect different aspects of your HTML page.

</dd></dl>

<p>Although we didn&#8217;t go into all the details of all the objects in the DOM, we did get an idea of how it works. In the <a href="/2010/02/JavaScript_Tutorial_-_Lesson_4" title="Tutorial:JavaScript Tutorial - Lesson 4">Lesson 4</a>, we&#8217;ll cover a few aspects of computer programming that haven&#8217;t been touched on yet. And in <a href="/2010/02/JavaScript_Tutorial_-_Lesson_5" title="Tutorial:JavaScript Tutorial - Lesson 5">Lesson 5</a>, we&#8217;ll study the DOM further and go into how most of the objects in an HTML document can be accessed and changed.

</p><div id='linker_widget' class='contextly-widget'></div>]]></content:encoded>
            <wfw:commentRss>http://www.webmonkey.com/2010/02/javascript_tutorial_-_lesson_3/feed/</wfw:commentRss>
        <slash:comments>2</slash:comments>

        
    </item>
    
    <item>
        <title>JavaScript Tutorial &#8211; Lesson 4</title>
        <link>http://www.webmonkey.com/2010/02/javascript_tutorial_-_lesson_4/</link>
        <comments>http://www.webmonkey.com/2010/02/javascript_tutorial_-_lesson_4/#comments</comments>
        <pubDate>Tue, 16 Feb 2010 01:45:47 +0000</pubDate>

                <dc:creator>Webmonkey Staff</dc:creator>

        <guid isPermaLink="false">http://stag.wired.com/primate/?p=713</guid>
        		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[thau]]></category>
		<category><![CDATA[wiki]]></category>
        <description><![CDATA[Welcome to Lesson 4! There are two main parts to JavaScript: the syntax of the language and its library of objects. In Lesson 2, which was an introduction to the syntax, we looked into variables, statements, and if-then clauses, which are parts of all programming languages. Now it&#8217;s time to learn the rest of the [...]]]></description>

            <content:encoded><![CDATA[<!-- wpautop disabled --><p>Welcome to <b>Lesson 4</b>! There are two main parts to JavaScript: the syntax of the language and its library of objects. In Lesson 2, which was an introduction to the syntax, we looked into variables, statements, and if-then clauses, which are parts of all programming languages. Now it&#8217;s time to learn the rest of the JavaScript syntax.

</p><p>There are only three major aspects of JavaScript syntax that we have yet to cover: loops, arrays, and functions.

</p><p>Let&#8217;s start with loops.
<br />
<span id="more-713"></span>
</p>

<table id="toc" class="toc" summary="Contents"><tbody><tr><td><div id="toctitle"><h2>Contents</h2> </div>

<ol>
<li><a href="#Introduction_to_Loops">Introduction to Loops</a></li>
<li><a href="#Looping_Password">Looping Password</a></li>
<li><a href="#More_about_While_Loops">More about While Loops</a></li>
<li><a href="#For_Loops">For Loops</a></li>
<li><a href="#Nested_Loops">Nested Loops</a></li>
<li><a href="#Loop_Exercise">Loop Exercise</a></li>
<li><a href="#Arrays">Arrays</a></li>
<li><a href="#Arrays_and_Loops">Arrays and Loops</a></li>
<li><a href="#Arrays_in_the_Document_Object_Model">Arrays in the Document Object Model</a></li>
<li><a href="#Functions">Functions</a></li>
<li><a href="#Functions_with_No_Parameters">Functions with No Parameters</a></li>
<li><a href="#Parameters_and_Return_Values">Parameters and Return Values</a></li>
<li><a href="#Functions_with_More_Than_1_Parameter">Functions with More Than 1 Parameter</a></li>
<li><a href="#Lesson_4_Review">Lesson 4 Review</a></li>
</ol>

</td></tr></tbody></table>

<a name="Introduction_to_Loops"></a><h4> <span class="mw-headline">Introduction to Loops</span></h4>

<p>Sometimes you want to do the same thing more than once. Let&#8217;s say, for example, that you wanted to get a password from somebody and you wanted to keep asking until they gave you the right password. If you just wanted to give them two tries, you could do something like this:

</p>

<pre class="brush: js"> var the_password = "pass the wrench";

 var answer = prompt("What's the woyd?","");

 if (answer&nbsp;!= the_password) {

 	answer = prompt("What's the woyd?","");

 	if (answer&nbsp;!= the_password) {

 		document.write("You lose!&lt;p&gt;");

 	} else {

 		document.write("That's right!&lt;p&gt;");

 	}

 } else {

 	document.write("That's right!&lt;p&gt;");

 }



</pre>

<p>Unfortunately, this sort of thing won&#8217;t work if you just want to keep asking until they get it right. And it&#8217;s pretty ugly already &#8211; imagine if you wanted to ask four times instead of just two. You&#8217;d have four levels of if-then clauses, which is never a good thing.

</p><p>The best way to do similar things more than once is to use a loop. In this case, you can use a loop to keep asking for passwords until the person gives up. Here&#8217;s an example of <a href="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/loopsexample.html" class="external text" title="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/loopsexample.html" rel="nofollow">a  <code>while</code> loop in action</a>. The password is: pass the wrench.

</p>

<a name="Looping_Password"></a><h4> <span class="mw-headline">Looping Password</span></h4>

<p>That&#8217;s the woyd!

</p><p>Let&#8217;s go through this example line by line. View Source if you want to see the whole script.

</p><p>After the typical JavaScript preamble, we start with a couple of variable declarations:

</p>

<pre class="brush: js">var password="pass the wrench";

 var answer;



</pre>

<p>Here we define the password as a string, and we declare a variable called <code>answer</code>. You&#8217;ll see why we had to declare <code>answer</code> in a second. The next few lines are the important ones:

</p>

<pre class="brush: js">while (answer&nbsp;!= password)

 {

 	answer = prompt("What's the woyd?","");

 }

</pre>

<p>This is a while loop. while loops come in this general form:

</p>

<pre class="brush: js">while (some test is true)

 {

 	do the stuff inside the curly braces

 }

</pre>

<p>So the above lines say, &#8220;While the answer isn&#8217;t equal to the password, execute the prompt command.&#8221; The loop will keep executing the statements inside the curly brackets until the test is false. In this case, the test will only be false when the words the user enters are the same as the password (that is, &#8220;pass the wrench&#8221;).

</p><p>We had to declare <code>answer</code> because performing a test like <code>(answer&nbsp;!= password)</code> on an undeclared variable will give an error in some browsers. Because <code>answer</code> is given a value by the prompt method inside the while loop, it will have no value the first time we hit the loop. Defining it early gives it an initial value of <code>""</code>.



</p><p>Although looping indefinitely is often useful, loops are more commonly used to execute a set of statements a specific number of times. Here&#8217;s <a href="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/loopsexample2.html" class="external text" title="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/loopsexample2.html" rel="nofollow">another example of a  <code>while</code> loop</a> that shows how to do this.

</p>

<a name="More_about_While_Loops"></a><h4> <span class="mw-headline">More about While Loops</span></h4>

<p>You should have seen as many x&#8217;s as you asked for. Let&#8217;s go over this:

</p><p>First, we ask for the number of x&#8217;s:

</p>

<pre class="brush: js"> var width = prompt("How many x's would you like?

 (1-10 is good)","5");

</pre>



<p>Next, we declare a few variables:

</p>

<pre class="brush: js"> var a_line="";

 var loop = 0;

</pre>

<p>And now for the important part:

</p>

<pre class="brush: js"> while (loop &lt; width)

 {

   a_line = a_line + "x";

   loop=loop+1;

 }

</pre>

<p>This says, &#8220;while the variable loop is less than the requested width of the row of x&#8217;s, add another x to the line and then add one to the value of loop.&#8221; This loop will keep adding an x to the line and adding one to the value of loop until loop is no longer less than the requested width. Here&#8217;s a timeline of what happens when a person chooses two x&#8217;s at the prompt:

</p>

<dl><dt> Time 1</dt><dd>



<ul><li> a_line = &#8220;&#8221; (because we initialized it to be &#8220;&#8221;)

</li><li> loop=0 (because we initialized it to be 0)

</li><li> width=2 (because that&#8217;s what the user asked for)

</li><li> 0 is less than 2 so

</li><li> a_line = a_line + &#8220;x&#8221;, so now a_line = &#8220;x&#8221;

</li><li> loop=loop+1, so now loop = 1

</li></ul>

</dd></dl>

<dl><dt> Back into the loop: Time 2</dt><dd>



<ul><li> loop=1

</li><li> width=2

</li><li> a_line = &#8220;x&#8221;

</li><li> 1 is less than 2 so

</li><li> a_line = a_line + &#8220;x&#8221;, so now a_line = &#8220;xx&#8221;

</li><li> loop=loop+1, so now loop = 2

</li></ul>

</dd></dl>

<dl><dt> Back into the loop: Time 3</dt><dd>



<ul><li> loop=2

</li><li> width=2

</li><li> a_line = &#8220;xx&#8221;

</li><li> 2 is NOT less than 2 so

</li><li> fall out of the loop and do what follows

</li></ul>

</dd></dl>

<p>And what follows is:

</p>

<pre class="brush: js"> alert(a_line);

</pre>



<p>Throw up an alert box announcing a_line.

</p><p>This sort of loop is so common that programmers have developed a few shortcuts. Using the shortcuts, the while loop could have been written like this:

</p>

<pre class="brush: js"> while (loop &lt; width)

 {

   a_line += "x"; //this was a_line = a_line + "x";

   loop++;        //this was loop=loop+1;

 }

</pre>

<p>The first line, <code>a_line += "x"</code> , says &#8220;add x to myself.&#8221; This shortcut works with numbers, too. If you have <code>a_number = 5</code> , and you write, <code>a_number+=3</code> , it&#8217;s just like writing <code>a_number=a_number+3</code>. Programmers are lazy; they&#8217;re always coming up with shortcuts like this.



</p><p>The next line, <code>loop++</code> , means &#8220;add one to myself.&#8221; So, <code>loop++</code> is the same as <code>loop=loop+1</code> , which could also be written <code>loop+=1</code>. Each of these is equally good. Which one you use depends on how lazy you are.

</p><p>Just like there&#8217;s more than one way to add 1 to a number, there&#8217;s more than one way to write a loop. <code>while</code> loops aren&#8217;t the only kind of loops out there. Another popular one is the <code>for</code> loop.



</p>

<a name="For_Loops"></a><h4> <span class="mw-headline">For Loops</span></h4>

<p>The while loop from the last example, which was written like this &#8230;

</p>

<pre class="brush: js">var a_line="";

 var loop = 0;

 while (loop &lt; width)

 {

 	a_line = a_line + "x";

 	loop=loop+1;

 }

</pre>

<p>&#8230; could have been written using a <code>for</code> loop, like this:

</p>

<pre class="brush: js">var a_line="";

 for (var loop=0; loop &lt; width; loop++)

 {

 	a_line = a_line + "x";

 }



</pre>

<p><code>for</code> loops come in this form:

</p>

<pre class="brush: js">for (initial value; test; increment)

 {

 	do this stuff;

 }

</pre>

<p>So, the above <code>for</code> loop sets <code>loop = 0</code> and says that you should keep adding 1 to <code>loop</code> as long as <code>loop &lt; width</code>. It&#8217;s just like the previous <code>while</code> loop with a few less lines. Both say &#8220;add an x to <code>a_line&lt;/font&gt; &lt;code&gt;width</code> times.&#8221;



</p><p>One more thing about loops before we do an exercise using them: Loops can be nested. Here&#8217;s an example of <a href="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/loopsexample3.html" class="external text" title="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/loopsexample3.html" rel="nofollow">nested loops</a>. <i>Turn off your pop-up blocker to see this example in action.</i>

</p>

<a name="Nested_Loops"></a><h4> <span class="mw-headline">Nested Loops</span></h4>

<p>Here&#8217;s the script:

</p>

<pre class="brush: js"> var height = prompt("How high do you want the grid?

 (1-10 is good)","10");



 var width= prompt("How wide do you want the grid?

 (1-10 is good)","10");



 var a_line;



 var new_window =

 window.open("/webmonkey/98/04/files1a/grid.html","looper",

 "width=400,height=400");

 new_window.document.writeln("&lt;h1&gt;A Grid&lt;/h1&gt;");

 for (var height_loop = 0; height_loop &lt; height; height_loop++)

 {

 	a_line = "";

 	for (var width_loop = 0; width_loop &lt; width; width_loop++)

 	{

 		a_line+="x";

 	}

 	new_window.document.writeln(a_line + "&lt;br&gt;");

 }

 </pre>



<p>After asking for height and width, opening a new window, and writing a header to it, we go into a <code>for</code> loop. The first <code>for</code> loop sets <code>a_line = ""</code>. Try doing the example without this line and see what happens. After initializing <code>a_line</code> , the script goes into another <code>for</code> loop to build a line of x&#8217;s as wide as required and prints it out to the new window. This happens <code>height</code> times.



</p><p>OK, here&#8217;s your assignment: Take a look at this <a href="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/loopsexample4.html" class="external text" title="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/loopsexample4.html" rel="nofollow">loop exercise</a> and try doing it on your own before viewing source to see how it works.  <i>Turn off your pop-up blocker to see this example in action.</i>

</p>

<a name="Loop_Exercise"></a><h4> <span class="mw-headline">Loop Exercise</span></h4>

<p>This script asks for a few words and then prints them out in reverse order. Try writing the script yourself. When you&#8217;re done, View Source on this to see how I did it. After you&#8217;ve figured it all out, it&#8217;s time to learn about.

</p>

<a name="Arrays"></a><h4> <span class="mw-headline">Arrays</span></h4>

<p>We&#8217;ve seen that variables can hold numbers, strings, and references to objects. There&#8217;s one more kind of information that JavaScript understands:arrays.

</p><p>Arrays are lists. You might have a list of URLs that you want to visit, a list of names that you want to remember, or a list of colors in which you&#8217;d like text displayed. All these lists can be stored in arrays.



</p><p>Here&#8217;s how to create an array of colors:

</p>

<pre class="brush: js"> var colors = new Array("red","blue","green");

</pre>

<p>Now that you have an array, what can you do with it? The good thing about arrays is that elements of an array can be accessed by number. The first element is number 0 and can be accessed like this:

</p>

<pre class="brush: js"> var the_element = colors[0];

</pre>

<p>After you execute this line of JavaScript, the variable <code>the_element</code> will hold the string &#8220;red.&#8221; As you can see, you access the first element of an array by writing the name of the array and putting the element&#8217;s number in square brackets. The second element of an array is number 1.

</p><p>Once you&#8217;ve created an array, you can add to and change its values. If you decided to change the first element of the colors array to purple instead of red, you could write this:

</p>

<pre class="brush: js"> colors[0] = "purple";



</pre>

<p>Arrays are often used in tandem with loops.

</p>

<a name="Arrays_and_Loops"></a><h4> <span class="mw-headline">Arrays and Loops</span></h4>

<p>Arrays are great, because you can loop through each element of the array and do something with it. Here&#8217;s an example of arrays and loops that presents a <a href="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/slideshow.html" class="external text" title="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/slideshow.html" rel="nofollow">URL slide show</a>. Take a look at the slide show and then come back here. <i>Turn off your pop-up blocker to see this example in action.</i>

</p><p><font color="red">This example may need to be updated.</font>

</p><p>The first thing we do to make the slide show work is declare some variables:

</p>

<pre class="brush: js"> var url_names = new Array("hits.org","awaken.org","bianca.com");

 var a_url;



</pre>

<p>Next, we loop through the array, opening each URL and waiting for the user to click on the alert OK button:

</p>

<pre class="brush: js">for (var loop = 0; loop &lt;url_names.length; loop++)

 {



   // make the name of a url, for example http://www.hits.org/

   a_url = "http://www." + url_names[loop] + "/";



   // open a window

   var new_window=open(a_url,"new_window","width=300,height=300");



   // wait for the click

   alert("hit ok for the next site");



 }

 </pre>

<p>There are a few interesting things in this loop. First, note that the loop goes from 0 to something called <code>url_names.length</code>. Putting <code>.length</code> after the name of an array tells you how many elements are in the array. Remember, however, that this number is not the same as the index number of the last element in an array. If an array has three elements, its length is 3 but its last element is <code>array[2]</code>. This is because the first element of an array is <code>array[0]</code>. If you&#8217;re getting errors like &#8220;object not found&#8221; and there&#8217;s an array in your code, you may well have mixed up the index number of the array element with the overall number of elements in the array.

</p><p>You might have noticed that putting a <code>.length</code> at the end of an array looks a lot like finding a property of an object. Well, that&#8217;s because arrays actually <i>are</i> objects and length <i>is</i> one of the array&#8217;s properties.



</p><p>The other sign that arrays are objects is that you create a new array using the <code>new</code> command. In the above example, <code>url_names = new Array("blah","blah"...)</code> actually says, &#8220;make a new array and make <code>url_names</code> a reference to it.&#8221; In general, that&#8217;s how you create a new instance of an object. We won&#8217;t be going much deeper into objects for this set of lessons, so, for now, just keep in mind that if you see the word &#8220;new&#8221; being used in this way, you&#8217;re looking at an object being created.

</p><p>The first line in the loop just creates a variable that holds a string.

</p>

<pre class="brush: js"> a_url = "http://www." + url_names[loop] + "/";

</pre>

<p>The first time into the loop, the value of the variable <code>loop</code> is 0. The first element in the <code>url_names</code> array is the string <code>"hits.org"</code>. So, during the first time in the loop, the variable <code>a_url</code> will equal the string <code>"<a href="http://www.hits.org/" class="external free" title="http://www.hits.org/" rel="nofollow">http://www.hits.org/</a>"</code>.



</p><p>The next line of the loop opens a window with that URL.

</p>

<pre class="brush: js"> var new_window=open(a_url,"new_window","width=300,height=300");

</pre>

<p>Because each time we open the window we give it the same name, we won&#8217;t get multiple windows. If we had left out the name <code>"new_window"</code> we would have opened a different window each time we went through the loop.

</p><p>The third line of the loop simply throws up an alert box and waits for the user to hit the OK button.

</p><p>There are more uses for arrays than just holding strings. In fact, it turns out that arrays run throughout the JavaScript Document Object Model.

</p>

<a name="Arrays_in_the_Document_Object_Model"></a><h4> <span class="mw-headline">Arrays in the Document Object Model</span></h4>

<p>This example is going to use image swapping to show how arrays are woven into the DOM. <a href="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/image_change.html" class="external text" title="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/image_change.html" rel="nofollow">Try the example</a>, view source, and read on.



</p><p>Here&#8217;s the JavaScript that&#8217;s in the <code>onClick=""</code> in the link:

</p>

<pre class="brush: js"> var change=prompt('Change which image (0 or 1)?',''); window.document.images[change].src='three.jpg';

</pre>

<p>The first line gets a number and the second line does the change. In the past, we changed images using something like this:

</p>

<pre class="brush: js"> document.image_name.src = 'some_image.gif';

</pre>

<p>In order to do this, each image has to be named. If you don&#8217;t know the name of an image that you want to swap, but you know its order on the HTML page, you can refer to the image by its DOM number. The first image in an HTML document is <code>document.images[0]</code>, the second is <code>document.images[1]</code>, and so on. If you want to know how many images are in a document, you can find out by checking the length of the images array:<code>document.images.length</code>. For instance, if you wanted to change all the images on your page to a spacer GIF, you could do this:



</p>

<pre class="brush: js"> for (var loop = 0; loop &lt;

 document.images.length; loop++)

 {

 	document.images[loop].src = 'spacer.gif';

 }

</pre>

<p>Spiffy, huh?

</p><p>OK, there&#8217;s one more part of JavaScript syntax you need to know before you can consider yourself a full-fledged programmer: functions. Once we cover functions, we&#8217;ll do a few exercises, and then I&#8217;ll give you your homework for this lesson.

</p><p>On to functions.

</p>

<a name="Functions"></a><h4> <span class="mw-headline">Functions</span></h4>

<p>Functions are the last bit of basic programming you need to know before you can understand and perform your own serious JavaScripting. All programming languages have functions. Functions, or subroutines, as they&#8217;re sometimes called, are bits of JavaScript that you can call over and over without having to rewrite them every time.

</p><p>Let&#8217;s say you were trying to teach yourself to speed read and you wanted to sprinkle a long text with links which, when hit, would tell you the current time.

</p><p><a href="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/time.html" class="external text" title="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/time.html" rel="nofollow">Click here for an example</a>.



</p><p>Here&#8217;s the JavaScript that does this:

</p>

<pre class="brush: js"> &lt;a href="#" onClick="

   var the_date = new Date();

   var the_hour = the_date.getHours();

   var the_minute = the_date.getMinutes();

   var the_second = the_date.getSeconds();

   var the_time = the_hour + ':' + the_minute + ':' + the_second;

   alert('The time is now:' + the_time);"&gt;time!&lt;/a&gt;

 </pre>

<p>The details of how this little JavaScript works aren&#8217;t really important right now; I&#8217;ll go over them soon. The important thing to notice is that it&#8217;s fairly long. If you wanted to have 10 of these time links, you&#8217;d have to cut and paste this script each time, making your HTML pretty long and ugly. In addition, if you wanted to change the script, you&#8217;d have to change it in 10 different places.

</p><p>Instead of having 10 copies of it on your page, you could write a function to execute the JavaScript. That way you&#8217;d have the function in one place, making it easier to edit and easier to read.

</p><p>Here&#8217;s how you&#8217;d write a timer function.

</p>

<a name="Functions_with_No_Parameters"></a><h4> <span class="mw-headline">Functions with No Parameters</span></h4>

<p>This HTML page contains a function called <code>announceTime()</code>. To call <code>announceTime</code> from a link you&#8217;d do this:



</p>

<pre class="brush: js"> &lt;a href="#" onClick="announceTime(); return false;"&gt; time!&lt;/a&gt;

</pre>

<p>Like so &#8230; <a href="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/time2.html" class="external text" title="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/time2.html" rel="nofollow">Click here</a>!

</p><p>You saw something like this in the second lesson:

</p>

<pre class="brush: js"> &lt;a href="#" onClick="alert('Hello!'); return false;"&gt; Hello!&lt;/a&gt;



</pre>

<p>This was calling the alert method from a link. A function is just like a method, the only difference being that a method is attached to an object. In the case of alert, the object is a Window object.

</p><p>Let&#8217;s go on to the function itself. If you View Source, you&#8217;ll see the function sitting in the head of the HTML document. Here it is:

</p>

<pre class="brush: js"> &lt;html&gt;

 &lt;head&gt;

 &lt;title&gt;Function with No Parameters&lt;/title&gt;

 &lt;script langauge="JavaScript"&gt;



 &lt;!-- hide me



 function announceTime()

 {

   //get the date, the hour, minutes, and seconds

   var the_date = new Date();

   var the_hour = the_date.getHours();

   var the_minute = the_date.getMinutes();

   var the_second = the_date.getSeconds();



   //put together the string and alert with it

   var the_time = the_hour + ":" + the_minute + ":" + the_second;

   alert("The time is now:" + the_time);

 }



 // show me --&gt;



 &lt;/script&gt;



 &lt;/head&gt;

 &lt;body&gt;



 ...



 &lt;/body&gt;



 &lt;/html&gt;

</pre>

<p>OK, let&#8217;s go over this function line by line. First, all functions come in this format:

</p>

<pre class="brush: js"> function functionName(parameter list)

 {

 	statements ...

 }

</pre>

<p>Functions&#8217; naming rules are the same as those for variables. The first character has to be a letter or an underscore. The rest of the characters can be numbers or dashes. Also, you must make sure you don&#8217;t name a function the same as a variable. If you do, you&#8217;ll get really strange, hard to debug, results. I use internal capitalization for my function names to make sure I don&#8217;t accidentally name a function and a variable the same thing.

</p><p>After the function name comes a list of parameters. This function has no parameters, so I&#8217;ll hold off describing parameters until the next example.

</p><p>After the parameters comes the body of the function. This is the set of statements you want to run when the function is called. I&#8217;m going to use this timer for the next few examples, so let me describe how it works.

</p><p>The first line &#8230;

</p>

<pre class="brush: js"> var the_date = new Date();

</pre>



<p>&#8230; gets a new date object. Just like you have to get a new array object before you can do anything with it, you need to get a new date object before you can find out what time it is. When you get a new date object, it is automatically preset to the current date and time. In order to get the information out of the object, you have to use the object&#8217;s methods:

</p>

<pre class="brush: js"> var the_hour = the_date.getHours(); var the_minute = the_date.getMinutes(); var the_second = the_date.getSeconds();

</pre>

<p>You might be asking yourself, how am I supposed to know what methods a date object knows? How do I even know there&#8217;s such a thing as a date object? Well, these are reasons you need to have access to a JavaScript library. I&#8217;ll do my best to explain as many of the built-in JavaScript objects as I can, but there&#8217;s no way I can go through all of them.

</p><p>The rest of the function is pretty clear. It takes the numbers returned by the method calls, turns them into a string, and calls the alert method to put up a dialog box with the string. Note that you can call methods and functions from within functions. We&#8217;ll see a lot more of this.

</p><p>Now, if you&#8217;ve played with the time link enough, you might have noticed something isn&#8217;t quite right. Every once in a while you get something like this:<code>"The time is now:12:14:4"</code>. What&#8217;s the deal here?

</p><p>Well, it turns out that the <code>getSeconds()</code> method returns a number. If it&#8217;s <code>12:14:04</code>, <code>getSeconds()</code> will return the value 4. Then when we do the string concatenation, <code>the_minute + ":" + the_second</code>, we get <code>14:4</code> instead of what we want. There&#8217;s an easy way out of this, and that&#8217;s to make a new function that fixes the minutes and seconds if they need fixing. This new function will demonstrate parameters and return values, two crucial parts of functions, so it deserves a page of its own.



</p><p>On to parameters and return values.

</p>

<a name="Parameters_and_Return_Values"></a><h4> <span class="mw-headline">Parameters and Return Values</span></h4>

<p>Although functions with no parameters are pretty handy for cutting down on the amount of typing you have to do and help make your HTML look better, functions that take parameters are far more useful.

</p><p>In the last example, we had a problem when the <code>getMinutes</code> and <code>getSeconds</code> methods of the Date object returned numbers less than 10. We wanted them to come out as <code>04</code> instead of just <code>4</code>.



</p><p>We could have done something like this:

</p>

<pre class="brush: js"> var the_minute = the_date.getMinutes();

 if (the_minute &lt; 10)

 {

 	the_minute = "0" + the_minute;

 }



 var the_second = the_date.getSeconds();

 if (the_second &lt; 10)

 {

 	the_second = "0" + the_second;

 }

 </pre>

<p>This would work fine. Notice, however, that we&#8217;re basically writing the same code twice:If something is less than 10, stick a &#8220;0&#8243; in front of it. When you start to notice that you&#8217;re writing almost the same exact code a bunch of times in your JavaScript, you should start thinking about writing a function to do it. In this case, I wrote a function called <code>fixNumber</code>:

</p>

<pre class="brush: js">function fixNumber(the_number)

{

	if (the_number &lt; 10)

	{

		the_number = "0" + the_number;

	}

	return the_number;

}

</pre>



<p><br />

<code>fixNumber</code> takes one parameter, called <code>the_number</code>. A parameter is just a variable that gets set when the function is called. In this case, if we call the function like this:

</p>

<pre class="brush: js"> var fixed_variable = fixNumber(4);

</pre>

<p>The parameter <code>the_number</code> gets set to <code>4</code> in the function. The body of <code>fixNumber</code> should make sense to you by now. It says, &#8220;if the variable <code>the_number</code> is less than <code>10</code>, add a <code></code> to the front of it.&#8221; The only new thing is the <code>return</code> command:<code>return the_number</code>. The return command is used when you say something like this:



</p>

<pre class="brush: js"> var some_variable = someFunction();

</pre>

<p>The variable <code>some_variable</code> gets set to the value returned by the <code>someFunction()</code> function. In <code>fixNumber</code>, I wrote:return <code>the_number</code>. This exits the function and returns the value of <code>the_number</code> to whatever variable is waiting to be set. So, if I write &#8230;



</p>

<pre class="brush: js"> var fixed_variable = fixNumber(4);

</pre>

<p>&#8230; <code>the_number</code> will be initially set to <code>4</code> by the function call. Then, because <code>4</code> is less than <code>10</code>, <code>the_number</code> will be changed to &#8220;<code>04</code>&#8220;. Then <code>the_number</code> is returned, and the variable <code>fixed_variable</code> will be set to &#8220;04.&#8221;



</p><p>To include <code>fixNumber</code> in original function, <code>announceTime()</code>, I&#8217;ve made the following additions:

</p>

 <pre class="brush: js"> function announceTime()

 {

   //get the date, the hour, minutes, and seconds

   var the_date = new Date();



   var the_hour = the_date.getHours();

   var the_minute = the_date.getMinutes();

   var fixed_minute = fixNumber(the_minute);

   var the_second = the_date.getSeconds();

   var fixed_second = fixNumber(the_second);



   //put together the string and alert with it

   var the_time = the_hour + ":" + fixed_minute + ":" + fixed_second;

   alert("The time is now:" +the_time);

 }



 </pre>

<p>Let&#8217;s say it&#8217;s 12:04:05 when the time link is clicked on. We get the date using <code>new Date()</code>, get the hour using <code>getHours()</code>, which doesn&#8217;t need fixing, get the minute as we did before, which in this case will be the number <code>4</code>, and then call <code>fixNumber</code> on <code>the_minute</code>:



</p>

<pre class="brush: js"> var fixed_minute = fixNumber(the_minute);

</pre>

<p>When <code>fixNumber()</code> is called, the parameter <code>the_number</code> gets set to the value of <code>the_minute</code>. In this example, since <code>the_minute</code> is <code>4</code>, <code>the_number</code> will be set to <code>4</code>. Once the parameter is set, we go into the body of the function. Since 4 is less than 10, <code>the_number</code> is changed to be &#8220;<code>04</code>&#8220;. Then <code>the_number</code> is returned, using the return command. Once &#8220;04&#8243; is returned by <code>fixNumber</code>, the variable <code>fixed_minute</code> will equal &#8220;04&#8243;.



</p><p>Once you get this working, it should look like <a href="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/time3.html" class="external text" title="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/time3.html" rel="nofollow">this</a>!

</p><p>Let&#8217;s go through this step by step and then do an exercise. Assume the time is 12:04:05.

</p><p>We start in <code>function announceTime()</code>

</p>

<ol><li> <code>the_minute</code> = <code>the_date.getMinutes();</code> Now <code>the_minute</code> = 4



</li><li> <code>fixed_minute = fixNumber(the_minute);</code> Call the <code>fixNumber()</code> function and return its value to <code>fixed_minute</code>===Now we&#8217;re in <code>function fixNumber()</code>===

</li><li> <code>function fixNumber(the_number)</code><code>fixNumber()</code> is called with the value of <code>the_minute</code>, which is 4, now <code>the_number = 4</code>



</li><li> <code>if (the_number &lt; 10) {the_number = "0" + the_number;}</code> Since 4 is less than 10, <code>the_number</code> now equals &#8220;04&#8243;

</li><li> return <code>the_number</code>The function exits and returns &#8220;04&#8243; ===<code>Function fixTime()</code> has exited, so we&#8217;re back in <code>announceTime()</code>===



</li><li> The function returns with &#8220;04&#8243; So <code>fixed_minute</code> now equals &#8220;04&#8243;

</li></ol>

<p><br />

This example used a function which only had one parameter. You can actually have as many parameters as you&#8217;d like. For example, here&#8217;s a function in <i>the Functions with More Than 1 Parameter</i> section that takes two arrays and returns a list of elements that the arrays have in common.

</p>

<a name="Functions_with_More_Than_1_Parameter"></a><h4> <span class="mw-headline">Functions with More Than 1 Parameter</span></h4>

<p>Here are the arrays I&#8217;ve defined:

</p><p><code> var monkeys = new Array("mattmarg","wendy","kristin","tim","aaron", "luke"); var kittyphile = new Array("wendy", "ruby", "roscoe", "tim"); var discophile = new Array("mattmarg", "john travolta", "wendy"); var happy = new Array("tim", "wendy", "stimpy", "aaron"); var cranky = new Array("ren", "mattmarg","luke");</code> With these arrays defined, and the <code>arrayIntersect</code> function written, it&#8217;s very easy to figure out which Webmonkeys love disco: <a href="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/dancing_monkeys.html" class="external text" title="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/dancing_monkeys.html" rel="nofollow">dancing monkeys</a>.



</p><p>Note that even though John Travolta loves disco, he&#8217;s not on the <code>monkeys</code> list, so he&#8217;s not a dancing monkey. To call this function, I wrote this:

</p>

<pre class="brush: js"> &lt;a href="#" onClick="arrayIntersect('dancing monkeys',monkeys,discophile); return false;"&gt;Click to see which monkeys love disco&lt;/a&gt;

</pre>

<p>This is a function with three parameters:a string representing the name of the intersection, the first array, and the second array. It&#8217;s similarly easy to find the names of Webmonkeys who like cats:<a href="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/catlovingmonkeys.html" class="external text" title="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/catlovingmonkeys.html" rel="nofollow">cat-loving monkeys</a>.

</p><p>Like so:

</p>

<pre class="brush: js"> &lt;a href="#" onClick="arrayIntersect('monkeys who love cats',monkeys,kittyphile); return false;"&gt;Click to see the cat-loving monkeys&lt;/a&gt;



</pre>

<p>Let&#8217;s look at the <code>arrayIntersect</code> function itself:

</p>

<pre class="brush: js"> function arrayIntersect(intersect_name, array_1, array_2)

 {

   var the_list = "";

   for (var loop_1 = 0; loop_1 &lt; array_1.length; loop_1++)

   {

     for (var loop_2 = 0; loop_2 &lt; array_2.length; loop_2++)

     {

       if (array_1[loop_1] == array_2[loop_2])

       {

         the_list = the_list + array_1[loop_1] + " ";

       }

     }

   }

   alert("the " + intersect_name + " are:"+ the_list);

 }

</pre>

<p>See if you can figure out for yourself what the <code>for</code> loops are doing in this example. The important thing to note here is the first line of the function:



</p>

<pre class="brush: js"> function arrayIntersect(intersect_name, array_1, array_2)

</pre>

<p>This defines a function called <code>arrayIntersect</code> with three parameters. Just like in the earlier example, each parameter is like a variable that gets set when the function is called. So, when this function is called like this:

</p>

<pre class="brush: js"> arrayIntersect('dancing monkeys',monkeys,discophile);

</pre>

<p>The following assignments are made:

</p>

<ul><li> intersect_name = &#8216;dancing monkeys&#8217;

</li><li> array_1 = monkeys



</li><li> array_2 = discophile

</li></ul>

<p><br />

The only thing you have to be careful of is that you call your functions with the right number of parameters. If we had accidentally called <code>arrayIntersect</code> like this:

</p>

<pre class="brush: js"> arrayIntersect(monkeys,discophile);

</pre>

<p>We would have gotten all kinds of errors. Try it and see what happens.

</p><p>Functions are the basic building blocks of any decent JavaScript, so it&#8217;s very important that you understand how they work. Here&#8217;s an exercise to test your knowledge of functions. After you&#8217;ve done the exercise, we&#8217;ll do one more exercise that combines everything we&#8217;ve learned in this lesson, and then go on to do some more work on our personal browsers. Here&#8217;s a snazzy way to give people a chance to go to another URL without having to drag their mouses all the way to the Location window:Where are you <a href="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/heading.html" class="external text" title="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/heading.html" rel="nofollow">heading</a>?

</p><p>The neat thing about this script is that people can type either <code><a href="http://some.address.com" class="external free" title="http://some.address.com" rel="nofollow">http://some.address.com</a></code> or just <code>some.address.com</code>. If they do the latter, JavaScript will figure it out and append <code>http://</code> to the front of what they type. Give it a try. Type <code>www.hits.org</code> and you&#8217;ll see that the script appends the <code>http://</code> on the front.



</p><p>Your assignment, of course, is to do this. You&#8217;ll need one tip though. To check the first few letters of the typed URL, you need to do this:

</p>

<pre class="brush: js"> var the_first_seven = the_url_they_typed.substring(0,7);

</pre>

<p>After you do this, <code>the_first_seven</code> will hold the first seven characters of the string typed into the prompt.

</p><p>Try doing this exercise. If you give up, View Source for the solution. Try it first, though! Then go on to the <a href="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/JST_homework4.html" class="external text" title="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/JST_homework4.html" rel="nofollow">final exercise</a> for this lesson.

</p>

<a name="Lesson_4_Review"></a><h4> <span class="mw-headline">Lesson 4 Review</span></h4>



<p>Today we finished with the syntax of JavaScript. We&#8217;ve covered, in broad strokes, most of what is covered in an introductory computer science course. If you understood it all, you should go grab a celebratory banana. Here&#8217;s what you should know by now:

</p>

<dl><dt> while loops

</dt><dd>How to make a while loop loop both indefinitely and a specific number of times

</dd><dt> for loops

</dt><dd>How for loops work

</dd><dt> Arrays

</dt><dd>What arrays are and how to initialize and set them

</dd><dt> Arrays and loops

</dt><dd>How to use loops to go through arrays (using the <code>array.length</code> property)



</dd><dt> Arrays in the DOM

</dt><dd>How to use arrays to affect images on your pages (the DOM is packed with arrays)

</dd><dt> Functions

</dt><dd>You should know what a function is and how to write and call one

</dd><dt> Parameters and return values

</dt><dd>Functions get interesting when you can change their behavior based on parameters and use their results in other parts of your JavaScript

</dd></dl>

<p>You can now call yourself a junior computer programmer. In <a href="/2010/02/JavaScript_Tutorial_-_Lesson_5" title="Tutorial:JavaScript Tutorial - Lesson 5">

 Lesson 5</a>, we&#8217;re going to leave the dry-ish world of JavaScript syntax and return to the JavaScript Document Object Model. Here we will learn about how you can use forms to interact with users in powerful and interesting ways.

</p><p>See you then!

</p><p><br />



</p><div id='linker_widget' class='contextly-widget'></div>]]></content:encoded>
            <wfw:commentRss>http://www.webmonkey.com/2010/02/javascript_tutorial_-_lesson_4/feed/</wfw:commentRss>
        <slash:comments>0</slash:comments>

        
    </item>
    
    <item>
        <title>JavaScript Tutorial &#8211; Lesson 5</title>
        <link>http://www.webmonkey.com/2010/02/javascript_tutorial_-_lesson_5/</link>
        <comments>http://www.webmonkey.com/2010/02/javascript_tutorial_-_lesson_5/#comments</comments>
        <pubDate>Tue, 16 Feb 2010 01:45:47 +0000</pubDate>

                <dc:creator>Webmonkey Staff</dc:creator>

        <guid isPermaLink="false">http://stag.wired.com/primate/?p=715</guid>
        		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Multimedia]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[thau]]></category>
		<category><![CDATA[wiki]]></category>
        <description><![CDATA[Now that you&#8217;ve mastered the basics of computer programming, it&#8217;s time to refocus on the Document Object Model (DOM). We&#8217;ve already seen that the DOM hierarchy starts with a Window object. Inside each Window object is a Document object. We&#8217;ll be spending this lesson going through the Document object and seeing how it can be [...]]]></description>

            <content:encoded><![CDATA[<!-- wpautop disabled --><p>Now that you&#8217;ve mastered the basics of computer programming, it&#8217;s time to refocus on the Document Object Model (DOM). We&#8217;ve already seen that the DOM hierarchy starts with a Window object. Inside each Window object is a Document object. We&#8217;ll be spending this lesson going through the Document object and seeing how it can be used to get all kinds of information from your users and to dynamically present new information.</p>
<br />
<span id="more-715"></span>

<p>We&#8217;ve already had a good look at one of the properties of the Document object, the Images array. If you remember back to Lesson 4, the first image in a document can be modified by changing its src property. For example,</p>
<pre class="brush: js"> window.document.images[0].src='some_new_picture.gif';
</pre>
<p>will change the first image in a document to the GIF called <code>some_new_picture.gif</code>. As you might have guessed, each Image in the Image array is itself an object in the DOM. That&#8217;s why <code>images[0].src</code> works. It&#8217;s saying, get the Image object <code>image[0]</code> from the Images array and set its src property. The whole statement above reads in English, &#8220;get the document property of this window, get the first image from the document&#8217;s image array, and change its source property to <code>some_new_picture.gif</code>.&#8221;</p>
<p>The Image object has lots of other interesting properties. For example, you can have your JavaScript check to see if an image has been completely loaded before doing anything. However, these interesting properties will have to wait for later lessons. Gotta keep you coming back somehow, right? Today, we&#8217;ll be focusing entirely on forms and how to use them in JavaScript.</p>
<table id="toc" class="toc" summary="Contents">
<tbody>
<tr>
<td>
<div id="toctitle">
<h2>Contents</h2>
</p></div>
<ol>
<li><a href="#Introduction_to_Forms">Introduction to Forms</a></li>
<li><a href="#Manipulating_the_Value_of_a_Text_Field">Manipulating the Value of a Text Field</a></li>
<li><a href="#Text_Field_Events">Text Field Events</a></li>
<li><a href="#Form_Handlers">Form Handlers</a></li>
<li><a href="#Text_Field_Exercise">Text Field Exercise</a></li>
<li><a href="#Checkboxes">Checkboxes</a></li>
<li><a href="#Radio_Buttons">Radio Buttons</a></li>
<li><a href="#Selects">Selects</a></li>
<li><a href="#onChange_in_Select_Form_Elements">onChange in Select Form Elements</a></li>
<li><a href="#Review_of_Lesson_5">Review of Lesson 5</a></li>
</ol>
</td>
</tr>
</tbody>
</table>
<p></p>
<p><a name="Introduction_to_Forms"></a><br />
<h4> <span class="mw-headline">Introduction to Forms</span></h4>
<p>Forms are part of the HTML 1.0 specification. Many people don&#8217;t know about them, however, because there&#8217;s a misconception that they&#8217;re only useful if you (or someone you know) can do server-side CGI programming. As June points out in her <a href="/2010/02/Add_HTML_Forms_to_Your_Site" title="Tutorial:Add HTML Forms to Your Site">forms tutorial</a>, forms can be fun even if you aren&#8217;t a CGI programmer. More important for this tutorial, JavaScript can be used to add all sorts of functionality to forms without the help of server-side CGI.</p>
<p>If you don&#8217;t know how forms work, check out <a href="/2010/02/Add_HTML_Forms_to_Your_Site" title="Tutorial:Add HTML Forms to Your Site">Jay&#8217;s tutorial</a> and try writing some forms yourself. I&#8217;m going to assume that you know the basics.</p>
<p>The first thing you need to know about forms and JavaScript is that forms, like images, are stored in an array of objects. Just like you can refer to the first image on a page by calling it <code>window.document.images[0]</code>, you can refer to the first form on a page using <code>window.document.forms[0]</code>. Similarly, just like you can name images, you can name forms. For an example if <a href="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/forms1.html" class="external text" title="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/forms1.html" rel="nofollow">this form</a> is written like this,</p>
<pre class="brush: js"> &lt;form name="first_form"&gt;

 &lt;input type="text" name="first_text" size="40"

 value="Power to the primates!"&gt;

 &lt;/form&gt;
</pre>
<p>You can refer to the form in either of these two ways:</p>
<pre class="brush: js"> var the_form = window.document.forms[0];

 var the_same_form = window.document.first_form;
</pre>
<p>Although being able to refer to forms is sometimes useful, more often you want to refer to elements inside of forms, such as the text field in the last example. Here&#8217;s an example of manipulating the value of a text field.</p>
<p><a name="Manipulating_the_Value_of_a_Text_Field"></a><br />
<h4> <span class="mw-headline">Manipulating the Value of a Text Field</span></h4>
<p><a href="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/forms2.html" class="external text" title="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/forms2.html" rel="nofollow">Click here</a> and mouse over the links below the text field and see what happens.</p>
<p>This magic is performed by changing the value of the text field. The form looks like the one in the last example:</p>
<pre class="brush: js"> &lt;form name="first_form"&gt;

 &lt;input type="text" name="first_text" value="Are you happy?"&gt;

 &lt;/form&gt;
</pre>
<p>The links that change the text field are:</p>
<pre class="brush: js"> &lt;a href="#" onMouseOver="window.document.first_form.first_text.value=

 'Clap clap!';"&gt;Yes, and I know it.&lt;/a&gt;

 &lt;a href="#" onMouseOver="window.document.first_form.first_text.value=

 'Sour puss!';"&gt;No!&lt;/a&gt;
</pre>
<p>These are normal mouseovers; the important part is:<code>window.document.first_form.first_text.value='Clap clap!'</code>. This says, &#8220;find the form called <code>first_form</code> in the document, find the form element called <code>first_text</code>, and set its value to &#8216;Clap clap!&#8217;.&#8221; The second line works similarly. This is very much like changing the src of an image. Instead of having a src, text fields have values.</p>
<p>Other types of form elements can be affected by messing with their values &#8211; for example, textareas:</p>
<p><a href="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/forms3.html" class="external text" title="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/forms3.html" rel="nofollow">Click here</a>.</p>
<p>The forms and links here are very similar to those above. The form is:</p>
<pre class="brush: js">&lt;form name="form_two"&gt;

 &lt;textarea name="the_textarea" rows=10 cols=60&gt;

 Mouse over below to see the first verse of

 The Webmonkey song, adapted from

 "I Wanna Be Like You" (The Monkey Song)

 from Walt Disney's &lt;cite&gt;The Jungle Book&lt;/cite&gt;

 written by Richard M. Sherman and Robert B. Sherman

 &lt;/textarea&gt;

 &lt;/form&gt;
</pre>
<p>Notice that the form has a name, <code>form_two</code>, and the textarea has a name as well, <code>the_textarea</code>.</p>
<p>The links are basically the same as what you saw in the text field example:</p>
<pre class="brush: js">&lt;a href="#" onMouseOver="window.document.form_two.the_textarea.value=

first_part;"&gt;Part 1&lt;/a&gt;

&lt;a href="#" onMouseOver="window.document.form_two.the_textarea.value=

second_part;"&gt;Part 2&lt;/a&gt;
</pre>
<p>The only difference is that instead of assigning a string to the value of the textareas, I assigned variables that I defined in the header. View Source to see that they&#8217;re there. I only did this for the sake of neatness, to get those long strings out of the HTML. A well-groomed monkey is a happy monkey. Here&#8217;s one of the strings:</p>
<pre class="brush: js"> var first_part = "Now I'm the king of the swingersnOh, the jungle VIPnI've reached the top and had to stopnAnd that's what botherin' me";
</pre>
<p>Notice the <code>"n"</code>. This is standard computerese for new lines. In general, because you&#8217;re working with HTML, the new line isn&#8217;t important. But if you&#8217;re writing something in a <code>&lt;pre&gt;</code> tag, or you&#8217;re writing into a textarea, the <code>"n"</code> comes in handy.</p>
<p>In addition to changing the values of form elements, JavaScript allows you to detect events that go on inside of them. Here&#8217;s an example of detecting events inside a text field.</p>
<p><a name="Text_Field_Events"></a><br />
<h4> <span class="mw-headline">Text Field Events</span></h4>
<p>Text fields understand <code>onBlur</code>, <code>onFocus</code>, and <code>onChange</code>. The <code>onFocus</code> event occurs when someone clicks inside a text field. <code>onBlur</code> happens when somebody moves out of a text field by clicking outside of it, or hitting &#8220;tab.&#8221; <code>onChange</code> happens when somebody changes what&#8217;s in the text field and then moves outside the text field.</p>
<p>Try doing these things in the text field and see what happens in the textarea below it.</p>
<p><a href="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/forms4.html" class="external text" title="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/forms4.html" rel="nofollow">Click here</a>.</p>
<p>Here&#8217;s how this works. The text field looks like this:</p>
<pre class="brush: js">&lt;input type="text" name="first_text"

   onFocus="writeIt('focus');"

   onBlur="writeIt('blur');"

   onChange="writeIt('change');"&gt;
</pre>
<p>Each of the event handlers calls the function <code>writeIt()</code>, which I&#8217;ve defined in the header. The header looks like this:</p>
<pre class="brush: js">&lt;head&gt;

 &lt;title&gt;Text Field Events&lt;/title&gt;

 &lt;script language="JavaScript"&gt;

 &lt;!-- hide me

 function writeIt(the_word)

 {

   var word_with_return = the_word + "n";

   window.document.first_form.the_textarea.value +=

     word_with_return;

 }

 // show me --&gt;

 &lt;/script&gt;

 &lt;/head&gt;
</pre>
<p>This should all look pretty familiar to you. The first few lines are the typical JavaScript preamble and the function definition. The first line in the body of the function &#8230;</p>
<pre class="brush: js"> var word_with_return = the_word + "n";
</pre>
<p>&#8230;. initializes a new variable, <code>word_with_return</code>, and sets it equal to the string that was passed into the function concatenated with a <code>"n"</code>. (Remember, the <code>"n"</code> is standard computerese for &#8220;new line.&#8221;)</p>
<p>The next line &#8230;</p>
<pre class="brush: js"> window.document.first_form.the_textarea.value += word_with_return;
</pre>
<p>&#8230;. says, &#8220;set the value of the textarea to its current value plus the new variable.&#8221; This shortcut was covered when we learned about loops. It&#8217;s the same as saying:<code>window.document.first_form.the_textarea.value =</p>
<p></code></p>
<pre class="brush: js">  window.document.first_form.the_textarea.value + word_with_return;

 It just takes less time. So far, we've seen a property of text fields and textareas (the value) and some events that they can handle. The remaining thing to know about these elements is the methods that they can handle:<code>blur()</code>, <code>focus()</code>, and <code>select()</code>.
</pre>
<p>Here are some links to show you how <code>focus()</code> and <code>select()</code> work. Beware that they sometimes stop working after the first time:</p>
<p></p>
<p><a href="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/forms5.html" class="external text" title="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/forms5.html" rel="nofollow">Click here</a>.</p>
<p></p>
<p>Here are the form and the two links:</p>
<pre class="brush: js"> &lt;form name="method_form"&gt;

 &lt;input type="text" name="method_text" size=40 value="Hey, hey, we're the monkeys"&gt;

 &lt;/form&gt;  &lt;a href="#" onMouseOver="window.document.method_form.method_text.focus();"&gt;Mouseover to focus&lt;/a&gt;

 &lt;a href="#" onMouseOver="window.document.method_form.method_text.select();"&gt;Mouseover to select&lt;/a&gt;
</pre>
<p>Accessing the methods of a text field is just like accessing the methods of any object:<code>object_name.method()</code>. The name of a text field is <code>window.document.form_name.text_field_name</code>. So, to call the <code>focus()</code> method on the text field above, we call:</p>
<pre class="brush: js"> window.document.method_form.method_text.focus();
</pre>
<p>That&#8217;s pretty much all there is to know about text fields and textareas. We&#8217;re about ready to try the first exercise for this lesson. First, however, there&#8217;s one more thing you need to know about form handlers before you can do the exercise.</p>
<p><a name="Form_Handlers"></a><br />
<h4> <span class="mw-headline">Form Handlers</span></h4>
<p>Forms are objects; they have their own methods, properties, and event handlers. One event handler that you should know about is <code>onSubmit</code>. <code>onSubmit</code> gets called in two situations:if a user clicks on a Submit button, or if a user hits Return in a text field. If these actions are not handled in some way, your JavaScript may behave differently than expected. Try clicking on</p>
<p><a href="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/forms6.html" class="external text" title="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/forms6.html" rel="nofollow">Submit</a> and see what happens.</p>
<p>In Netscape, clicking on an unhandled Submit button generally leads to reloading the page. In general, you won&#8217;t want this. In order to block this behavior, you need to do this:</p>
<pre class="brush: js">&lt;form onSubmit="return false;"&gt;

 &lt;input type="submit" value="Submit"&gt;

 &lt;/form&gt;
</pre>
<p><a href="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/forms7.html" class="external text" title="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/forms7.html" rel="nofollow">Try it</a></p>
<p>Generally, <code>return false</code> is a way that JavaScript stops your browser from doing what it would otherwise do. Another example of this is stopping an <code>href</code> from going to the URL assigned to it. For example, the link &#8230;</p>
<pre class="brush: js"> &lt;a href="http://www.webmonkey.com/" onClick="return false;"&gt;mattmarg!&lt;/a&gt;
</pre>
<p>&#8230;. won&#8217;t go anywhere because you&#8217;ve returned false on the onClick. <a href="http://www.webmonkey.com/" class="external text" title="http://www.webmonkey.com/" rel="nofollow">Click on this dead link</a>, if you don&#8217;t believe me.</p>
<p>This may seem like a weird thing to do, but actually it&#8217;s quite common, especially in the case of forms. Here&#8217;s an example of using a form to get input from a user. Type something into <a href="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/forms8.html" class="external text" title="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/forms8.html" rel="nofollow">this text field</a> and hit Return.</p>
<p></p>
<p>Here&#8217;s the form:</p>
<pre class="brush: js"> &lt;form name="text_entry_form" onSubmit="monkeyLove(); return false;"&gt;

 &lt;b&gt;Who does the monkey love:&lt;/b&gt;

 &lt;input type="text" name="monkey_love" size="30"&gt;

 &lt;/form&gt;
</pre>
<p>When you hit Return in the text field, the <code>onSubmit</code> handler gets called. It executes the function <code>monkeyLove()</code>, which changes the value in the text field.</p>
<p>If the <code>return false</code> wasn&#8217;t in the <code>onSubmit</code> handler, the function <code>monkeyLove()</code> would execute, changing the text field, but then the page would reload, changing the text field back to what it was. To stop this from happening, you need to have that <code>return false</code> in the <code>onSubmit</code>.</p>
<p>Here&#8217;s the <code>monkeyLove()</code> function for your perusal:</p>
<pre class="brush: js">function monkeyLove()

 {

   var who_it_is = window.document.text_entry_form.monkey_love.value;

   who_it_is = 'The monkey loves ' + who_it_is;

   window.document.text_entry_form.monkey_love.value = who_it_is;

 }
</pre>
<p>And here&#8217;s an example of the <a href="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/forms9.html" class="external text" title="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/forms9.html" rel="nofollow">same form</a> without the return false, just so you can see what happens.</p>
<p>Once you&#8217;ve convinced yourself of the merits of <code>return false</code>, it&#8217;s time to try a text-field exercise.</p>
<p><a name="Text_Field_Exercise"></a><br />
<h4> <span class="mw-headline">Text Field Exercise</span></h4>
<p>This exercise is an extension of one we did in Lesson 4. The exercise is to get this textarea to behave like a browser&#8217;s Location box. If you type in <code><a href="http://www.webmonkey.com/" class="external free" title="http://www.webmonkey.com/" rel="nofollow">http://www.webmonkey.com/</a></code> or just <code>www.webmonkey.com</code>, it&#8217;ll spawn a window that displays the Mattmarg.com Web site.</p>
<p><a href="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/forms10.html" class="external text" title="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/forms10.html" rel="nofollow">Click here</a>.</p>
<p>Try getting this to work before viewing source to see a solution. When you&#8217;re done, it&#8217;s time to move on to checkboxes and radio buttons.</p>
<p><a name="Checkboxes"></a><br />
<h4> <span class="mw-headline">Checkboxes</span></h4>
<p>Text fields and textareas are just two types of form elements. Others that we&#8217;ll look at in this lesson are checkboxes, radio buttons, and selects. Let&#8217;s discuss checkboxes first.</p>
<p>Checkboxes have one main property of interest: <a href="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/checkbox1.html" class="external text" title="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/checkbox1.html" rel="nofollow">checked</a>.</p>
<p>If you have a form named <code>the_form</code> and a checkbox named <code>the_checkbox</code> you can see if the checkbox has been checked like this:</p>
<pre class="brush: js">var is_checked = window.document.the_form.the_checkbox.checked;

 if (is_checked == true)

 {

   alert("Yup, it's checked!");

 } else {

   alert("Nope, it's not checked.");

 }
</pre>
<p>As you can see, if a checkbox is checked, the checked property will be <code>true</code>. <code>true</code> is a built-in JavaScript datatype, so you don&#8217;t have to put it in quotes when checking it. If the checkbox is not checked, the checked property will be false (also a built-in datatype).</p>
<p>Just like you can read the checked property, you can set the checked property. Here&#8217;s an example of checking and <a href="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/checkbox2.html" class="external text" title="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/checkbox2.html" rel="nofollow">setting the checked property of a checkbox</a>.</p>
<p>Here&#8217;s the code for the above:</p>
<pre class="brush: js">&lt;form name="form_1"&gt;

 &lt;input type="checkbox" name="check_1"&gt;Checkbox 1

 &lt;/form&gt;

 &lt;a href="#" onClick="window.document.form_1.check_1.checked=true;

 return false;"&gt;Click to check Checkbox 1&lt;/a&gt;

 &lt;a href="#" onClick="window.document.form_1.check_1.checked=false;

 return false;"&gt;Click to uncheck Checkbox 1&lt;/a&gt;

 &lt;a href="#" onClick="alert(window.document.form_1.check_1.checked);

 return false;"&gt;Click to see the value of Checkbox 1&lt;/a&gt;
</pre>
<p>Notice that I&#8217;m sticking the <code>return false</code> in the <code>href</code>. It stops the page from bouncing around when you click on a link.</p>
<p>Checkboxes have one interesting event handler:<code>onClick</code>. When someone clicks on a checkbox, the <code>onClick</code> event handler goes into action. Here&#8217;s an example of it in use.</p>
<p><a href="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/lightswitch.html" class="external text" title="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/lightswitch.html" rel="nofollow">Click here to check out the Light Switch</a></p>
<p>This example introduces a few new things. First, there&#8217;s form that introduces the <code>onClick</code> checkbox handler:</p>
<pre class="brush: js">&lt;form name="form_2"&gt;

 &lt;input type="checkbox" name ="check_1"

 onClick="switchLight();"&gt;The Light Switch

 &lt;/form&gt;
</pre>
<p>When someone clicks on the checkbox, the <code>onClick</code> handler gets triggered and executes the <code>switchLight()</code> function. Here&#8217;s the <code>switchLight()</code> function (it&#8217;s in the header of this page):</p>
<pre class="brush: js">function switchLight()

 {

   var the_box = window.document.form_2.check_1;

   var the_switch = "";

   if (the_box.checked == false) {

     alert("Hey! Turn that back on!");

     document.bgColor='black';

   } else {

     alert("Thanks!");

     document.bgColor='white';

   }

 }
</pre>
<p>The interesting thing here is the first line:</p>
<pre class="brush: js"> var the_box = window.document.form_2.check_1;
</pre>
<p>This line assigns the checkbox object to a variable. This a handy way to cut down on your typing. It&#8217;s also a good way to pass objects as parameters to functions. We&#8217;ll see a lot more of that in later lessons.</p>
<p>That&#8217;s most of what you have to know about checkboxes. Now let&#8217;s learn about  radio buttons.</p>
<p><a name="Radio_Buttons"></a><br />
<h4> <span class="mw-headline">Radio Buttons</span></h4>
<p>Happily, radio buttons are almost exactly like checkboxes with respect to JavaScript. The only real difference is in the HTML. Checkboxes are on/off devices. If a checkbox is checked, you can uncheck it. If it&#8217;s unchecked, you can check it. Radio buttons are different. Once a radio button is on, it stays on until another one is selected. Then the first one goes off. Here&#8217;s a typical radio button set:</p>
<p><a href="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/radio1.html" class="external text" title="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/radio1.html" rel="nofollow">Click here</a>.</p>
<p></p>
<p>As you can see, you can&#8217;t simply unselect a radio button, you have to choose a new one. With that in mind we can re-do the light switch example with two radio buttons instead of one checkbox:</p>
<p><a href="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/radio2.html" class="external text" title="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/radio2.html" rel="nofollow">Click here</a>.</p>
<p>This example looks very much like the checkbox example. The form is:</p>
<pre class="brush: js"> &lt;form name="form_1"&gt;

 &lt;input type="radio" name ="radio_1" onClick="offButton();"&gt;Light off

 &lt;input type="radio" name ="radio_2" onClick="onButton();" checked&gt;Light on

 &lt;/form&gt;
</pre>
<p>When the first radio button is clicked, the <code>offButton()</code> function is called. That function is:</p>
<pre class="brush: js">function offButton()

 {

   var the_box = window.document.form_1.radio_1;

   if (the_box.checked == true)

   {

     window.document.form_1.radio_2.checked = false;

     document.bgColor='black';

     alert("Hey! Turn that back on!");

   }

 }
</pre>
<p>This is pretty much just like the checkbox example earlier. The main difference is this line:</p>
<pre class="brush: js"> window.document.form_1.radio_2.checked = false;
</pre>
<p>This tells JavaScript to turn off the other button when this button has been clicked. The function that is run when the other button is clicked is similar to this one:</p>
<pre class="brush: js"> function onButton()

 {

   var the_box = window.document.form_1.radio_2;

   if (the_box.checked == true) {

     window.document.form_1.radio_1.checked = false;

     document.bgColor='white';

     alert("Thanks!");

   }

 }
</pre>
<p>There are a few more details about checkboxes and radio buttons, but those can wait until the next set of tutorials. Right now, let&#8217;s look at the last type of form element, selects.</p>
<p><a name="Selects"></a><br />
<h4> <span class="mw-headline">Selects</span></h4>
<p>Selects are the strangest of the form elements we&#8217;ll cover in this lesson. There are two primary kinds, pulldown selects and list selects. Here are examples of each:</p>
<p><a href="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/select1.html" class="external text" title="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/select1.html" rel="nofollow">Click here</a>.</p>
<p>The thing that makes select objects strange is that the whole select is named, but none of the select&#8217;s options is. For example, the HTML for the first select looks like this:</p>
<pre class="brush: js"> &lt;select name="pulldown_1" size=1&gt;

 &lt;option&gt;probiscus

 &lt;option&gt;spider

 &lt;option&gt;lemur

 &lt;option&gt;chimp

 &lt;option&gt;gorilla

 &lt;option&gt;orangutan

 &lt;/select&gt;
</pre>
<p>Notice that the whole select is named <code>pulldown_1</code>, but the individual options aren&#8217;t named. This makes it difficult to access individual options.</p>
<p>Luckily, through the magic of arrays and objects, there&#8217;s a way to access and change the options of a select. If you wanted to change the second option of the pulldown menu, you&#8217;d type:</p>
<pre class="brush: js"> window.document.form_1.pulldown_1.options[1].text = 'new_text';
</pre>
<p>This works because the select element has an options property that is an array of all the select&#8217;s options. You can grab one of the options in the array and change its text property. Try it &#8211; <a href="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/select2.html" class="external text" title="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/select2.html" rel="nofollow">change the select</a> and then scroll up to see that the pulldown menu actually changed. The second option in the pulldown select should now be <code>*thau*</code>.</p>
<p>In addition to the options property, selects have a property called <code>selectedIndex</code>. When one option in a select has been chosen, the <code>selectedIndex</code> property of the select will be the array number of the selected option. To test this, select one of the options in the list select (the second one) and then <a href="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/select3.html" class="external text" title="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/select3.html" rel="nofollow">check the index</a>. Remember that the first option in the array is option <code>0</code>. The line I used to check this was:</p>
<pre class="brush: js"> &lt;a href="#" onClick="alert('index is:' + window.document.form_1.list_1.selectedIndex); return false;"&gt;check the index.&lt;/a&gt;
</pre>
<p>The form is named <code>form_1</code>, the list select is named <code>list_1</code>. To get the <code>selectedIndex</code>, I looked at <code>window.document.form_1.list_1.selectedIndex</code>. If you want, you can set the <code>selectedIndex</code> like this &#8230;</p>
<pre class="brush: js"> window.document.form_1.list_1.selectedIndex = 1;
</pre>
<p>&#8230;. and highlight the second option in the <code>list_1</code> select.</p>
<p>Once you know the index number of the selected option, you can find out what it is:</p>
<pre class="brush: js"> var the_select = window.document.form_1.list_1;

 var the_index = the_select.selectedIndex;

 var the_selected = the_select.options[the_index].text;
</pre>
<p>The <code>selectedIndex</code> property is great when you only have one option selected. What happens when you have more than one option selected? Well, that gets slightly stranger. If you want to know, here&#8217;s some information about <a href="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/multiple_selects.html" class="external text" title="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/multiple_selects.html" rel="nofollow">multiple selects</a>.</p>
<p>Just like the other form elements, the select element has a handler:<code>onChange()</code>. This handler gets called whenever there&#8217;s a change to the select. Here&#8217;s the example from Lesson 1 to show you how  <code>onChange</code> works with a select.</p>
<p><a name="onChange_in_Select_Form_Elements"></a><br />
<h4> <span class="mw-headline">onChange in Select Form Elements</span></h4>
<p><a href="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/select4.html" class="external text" title="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/select4.html" rel="nofollow">Play with this example</a> and then read the blow-by-blow description.</p>
<p>This is a fairly complicated JavaScript, so let&#8217;s go through it slowly. First, let&#8217;s look at the form itself (<b>note</b> that your browser might wrap that <code>onChange</code> line, but it should be on one line, no spaces, inyour code):</p>
<pre class="brush: js"> &lt;form name="the_form"&gt;

 &lt;select name="choose_category"

   onChange="swapOptions

   (window.document.the_form.choose_category.

   options[selectedIndex].text);"&gt;

 &lt;option selected&gt;Dogs

 &lt;option&gt;Fish

 &lt;option&gt;Birds

 &lt;/select&gt;

 &lt;select name="the_examples" multiple&gt;

 &lt;option&gt;poodle

 &lt;option&gt;puli

 &lt;option&gt;greyhound      .

 &lt;/select&gt;

 &lt;/form&gt;
</pre>
<p>This form has two elements, a pulldown select and a list select. The pulldown select has an <code>onChange</code> handler that calls a function called <code>swapOptions()</code>. <code>swapOptions()</code>, which is defined in the header, has one parameter &#8211; the selected animal type.</p>
<p>Now let&#8217;s check out the header. The first thing that happens is I define a few arrays:</p>
<pre class="brush: js"> var dogs = new Array("poodle","puli","greyhound");

 var fish = new Array("trout", "mackerel", "bass");

 var birds = new Array("robin", "hummingbird", "crow");
</pre>
<p>Notice that the arrays are named the same thing as the animals in the pulldown select. You&#8217;ll see why soon. Now let&#8217;s look at the function that gets called when the pulldown select is changed:</p>
<pre class="brush: js"> function swapOptions(the_array_name)

 {

   var numbers_select = window.document.the_form.the_examples;

   var the_array = eval(the_array_name);

   setOptionText(window.document.the_form.the_examples, the_array);

 }
</pre>
<p>The function definition includes one parameter:<code>the_array_name</code>. If you pulled the pulldown select to &#8220;Fish,&#8221; <code>the_array_name</code> will equal the string &#8220;Fish.&#8221;</p>
<p>The first line in the body of the function sets a variable to refer to the second form element, the list select.</p>
<p>The second line introduces something new:<code>eval()</code>. <code>eval()</code> is a little weird and better left for later lessons. The end result of the second line is that the variable <code>the_array</code> will equal one of the arrays defined earlier. If <code>the_array_name</code> is &#8220;Fish,&#8221; <code>the_array</code> will equal the Fish array. If you want a description of how this happens, <a href="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/eval.html" class="external text" title="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/eval.html" rel="nofollow">study up on eval</a>.</p>
<p>The third line of the function calls another function called <code>setOptionText()</code>. <code>setOptionText()</code> does the work of setting the values of the list select to the contents of <code>the_array</code>. Here it is:</p>
<pre class="brush: js"> function setOptionText(the_select, the_array)

 {

   for (loop=0; loop &lt; the_select.options.length; loop++)

   {

     the_select.options[loop].text = the_array[loop];

   }

 }
</pre>
<p>This function takes two parameters, a reference to a select element and an array. The first line of the function sets up a for loop, which loops through all the options in the select element. Remember that the options property of a select element is an array of all that select&#8217;s options. Because it&#8217;s an array, you can find out how many options are in a select using the length property of arrays. That&#8217;s how the loop works.</p>
<p>The first time you hit the loop, the loop variable equals 0. The body of the loop then reads:</p>
<pre class="brush: js"> the_select.options[0].text = the_array[0];
</pre>
<p>If you chose &#8220;Fish&#8221; in the pulldown, <code>the_array[0]</code> will be &#8220;trout,&#8221; so this line will change the first option in the list select to &#8220;trout.&#8221; The next time through the loop, loop will equal 1, and the second option in the list select will equal &#8220;mackerel.&#8221;</p>
<p>There&#8217;s one caveat to all this. When you change the text of an option, the size of the select won&#8217;t change. So if you change an option&#8217;s text to something really long, it&#8217;ll probably get cut off.</p>
<p>One way to get around this is to stretch out the select when you first go to it. For example, I did this:</p>
<pre class="brush: js"> &lt;option&gt;greyhound      .
</pre>
<p>Note the period I used to stretch out my select box. It&#8217;s sort of cheesy, but it works.</p>
<p>OK, that was a mouthful. If you understand how this example works, you understand a lot of JavaScript, and you&#8217;ll have no problem doing your <a href="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/JST_homework5.html" class="external text" title="http://www.wired.com/wired/webmonkey/stuff/javascript_tutorial_files/JST_homework5.html" rel="nofollow">homework assignment</a> for this lesson. Once you&#8217;ve done the example and viewed source to see how I did it, go on to this lesson&#8217;s review.</p>
<p><a name="Review_of_Lesson_5"></a><br />
<h4> <span class="mw-headline">Review of Lesson 5</span></h4>
<p>Today we focused on forms and what you can do with them. We learned:</p>
<dl>
<dt> Forms and their elements can be named</p>
</dt>
<dd>You can refer to a form element like this:<code>window.document.form_name.element_name</code></p>
</dd>
<dt> Text field and textarea form elements have value properties</p>
</dt>
<dd>Refer to the value property like this:<code>window.document.form_name.element_name.value</code>; you can set the value by equating it to something, or get the value</p>
</dd>
<dt> Text field and textarea elements understand <code>focus()</code>, <code>blur()</code>, and <code>change()</code> event handlers</p>
</dt>
<dd>When you click on a text field or textarea, the focus event handler triggers; clicking out of one of these elements triggers the blur event handler; if you hit Tab or Return after changing an element, <code>onChange()</code> gets triggered</p>
</dd>
<dt> Forms have an <code>onSubmit()</code> event handler</p>
</dt>
<dd>To stop a form from reloading the page when you click on a Submit button, put <code>onSubmit="return false;"</code> in the <code>&lt;form&gt;</code> tag</p>
</dd>
<dt> Checkboxes and radio buttons have a checked property</p>
</dt>
<dd>You can check and uncheck checkboxes and radio buttons by changing their checked property</p>
</dd>
<dt> Checkboxes and radio buttons have an <code>onClick</code> event handler</p>
</dt>
<dd>Just like links, you can trigger functions when a user clicks on a checkbox or radio button</p>
</dd>
<dt> Selects have an options property that is an array of that select&#8217;s options</p>
</dt>
<dd>Just like any array, you can find the length of the options array by typing <code>window.document.form_name.select_name.options.length</code></p>
</dd>
<dt> You can change the text of an option by messing with its text property</p>
</dt>
<dd>To change the text of the first element of a select you&#8217;d type <code>window.document.form_name.select_name.options[0].text='new text';</code></p>
</dd>
<dt> You can find out which option was selected using the <code>selectedIndex</code> property of the select element</p>
</dt>
<dd><code>window.document.form_name.select_name.selectedIndex</code> returns the array number, you can then type <code>window.document.form_name.select_name.options[that_number].text</code> to find out what was actually selected</p>
</dd>
<dt> Selects have <code>onChange</code> event handlers</p>
</dt>
<dd>If someone changes the thing highlighted in a select, the <code>onChange</code> handler gets triggered</p>
</dd>
<dt> You can change the URL of a window using <code>window.location.replace('new url');</code></p>
</dt>
<dd>This was in the homework</p>
</dd>
<dt> You can create a new option for a select element using new Option</p>
</dt>
<dd>Since each option in the options array of a select is an object, you can use new to create a new Option; then you can stick this option into the options array</p>
</dd>
</dl>
<p>Today was packed, and it concludes this set of five lessons. We covered a lot of territory, from the basics of computer programming to a major portion of the JavaScript DOM. Not surprising, there&#8217;s still much more to learn. We only covered part of the DOM, and there are more than a few interesting JavaScript objects to study. We also didn&#8217;t talk too much about making our own objects, nor did we cover all the interesting properties of the Windows object.</p>
<p>Obviously this is a plug for the next set of lessons. So after you give yourself a minute to catch your breath, dive right into my <a href="/2010/02/Advanced_JavaScript_Tutorial" title="Tutorial:Advanced JavaScript Tutorial"> Advanced JavaScript Tutorial</a>.</p>
<p></p><div id='linker_widget' class='contextly-widget'></div>]]></content:encoded>
            <wfw:commentRss>http://www.webmonkey.com/2010/02/javascript_tutorial_-_lesson_5/feed/</wfw:commentRss>
        <slash:comments>0</slash:comments>

        
    </item>
    
    <item>
        <title>Thau&#8217;s Advanced JavaScript Tutorial</title>
        <link>http://www.webmonkey.com/2010/02/advanced_javascript_tutorial/</link>
        <comments>http://www.webmonkey.com/2010/02/advanced_javascript_tutorial/#comments</comments>
        <pubDate>Tue, 16 Feb 2010 01:45:47 +0000</pubDate>

                <dc:creator>Webmonkey Staff</dc:creator>

        <guid isPermaLink="false">http://stag.wired.com/primate/?p=717</guid>
        		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[thau]]></category>
		<category><![CDATA[wiki]]></category>
        <description><![CDATA[If you&#8217;ve gone through Thau&#8217;s basic JavaScript tutorial (or you already know a bunch about the subject), Thau&#8217;s advanced JavaScript course is just for you. In the previous tutorial, Thau taught the basics. He picks up here where he left off, starting with the meaning of var and if-then-else statements. He moves along to show [...]]]></description>

            <content:encoded><![CDATA[<!-- wpautop disabled --><p>If you&#8217;ve gone through Thau&#8217;s <a href="/2010/02/JavaScript_Tutorial_-_Lesson_1" title="Tutorial:JavaScript Tutorial - Lesson 1">basic JavaScript tutorial</a>  (or you already know a bunch about the subject), Thau&#8217;s advanced JavaScript course is just for you. In the previous tutorial, Thau taught the basics. He picks up here where he left off, starting with the meaning of <code>var</code> and <code>if-then-else</code> statements.

</p><p>He moves along to show you how to make cookies (Mmmmm), and you&#8217;ll learn fancy string handling and associative arrays along the way. Give your JavaScript a sense of history and time (by setting timelines on your pages so that different events occur at different times), and then learn how to sense which browser your visitors are using.

</p><p>Next, his Thauness gives lessons on image mapping and preloading images, with practical applications such as setting up an employee database and creating a virtual pet!



</p><p>By the end of the five lessons, Thau puts the finishing touches on your JavaScript mastery, covering JavaScripting tools, debugging techniques, and ways to make your code sprint like the wind.

</p><p>Get started:<b><a href="/2010/02/Advanced_JavaScript_Tutorial_-_Lesson_1" title="Tutorial:Advanced JavaScript Tutorial - Lesson 1"> Lesson 1</a></b><div id='linker_widget' class='contextly-widget'></div>]]></content:encoded>
            <wfw:commentRss>http://www.webmonkey.com/2010/02/advanced_javascript_tutorial/feed/</wfw:commentRss>
        <slash:comments>1</slash:comments>

        
    </item>
    
    <item>
        <title>Advanced JavaScript Tutorial &#8211; Lesson 1</title>
        <link>http://www.webmonkey.com/2010/02/advanced_javascript_tutorial_-_lesson_1/</link>
        <comments>http://www.webmonkey.com/2010/02/advanced_javascript_tutorial_-_lesson_1/#comments</comments>
        <pubDate>Tue, 16 Feb 2010 01:45:47 +0000</pubDate>

                <dc:creator>Webmonkey Staff</dc:creator>

        <guid isPermaLink="false">http://stag.wired.com/primate/?p=719</guid>
        		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Multimedia]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[thau]]></category>
		<category><![CDATA[wiki]]></category>
        <description><![CDATA[Hello, and welcome to the Advanced JavaScript Tutorial, where I finish off what I started in the basic JavaScript Tutorial. In the second installment &#8211; This Time We Mean It &#8211; I&#8217;ll be covering the finer points of JavaScript that I passed over back in Part I. I&#8217;ll also introduce you to some of the [...]]]></description>

            <content:encoded><![CDATA[<!-- wpautop disabled --><p>Hello, and welcome to the Advanced JavaScript Tutorial, where I finish off what I started in the <a href="/2010/02/JavaScript_Tutorial" title="Tutorial:JavaScript Tutorial">basic JavaScript Tutorial</a>. In the second installment &#8211; This Time We Mean It &#8211; I&#8217;ll be covering the finer points of JavaScript that I passed over back in Part I. I&#8217;ll also introduce you to some of the fancier aspects of JavaScript and the tips and lowdown that will allow you to build real multimedia applications.</p>
<br />
<span id="more-719"></span>
<p>As we head into the JavaScript nitty-gritty, I&#8217;m going to assume that you&#8217;ve covered the following:

</p>

<ul><li> Assigning values to variables

</li><li> If-then statements

</li><li> For and while loops

</li><li> Writing your own functions



</li><li> Opening and manipulating windows

</li><li> Reading and writing to HTML forms

</li><li> Using arrays

</li><li> Conducting image swaps

</li></ul>

<p><br />

Any of these sound unfamiliar? You may want to take a peek at the <a href="/2010/02/JavaScript_Tutorial_-_Lesson_1" title="Tutorial:JavaScript Tutorial - Lesson 1">first five</a> JavaScript lessons before you get into Part II.

</p>

<table id="toc" class="toc" summary="Contents"><tbody><tr><td><div id="toctitle"><h2>Contents</h2> </div>



<ol>

<li><a href="#The_Five-Day_Lesson_Plan">The Five-Day Lesson Plan</a></li>

<li><a href="#An_If-Then-Else_Shortcut">An If-Then-Else Shortcut</a></li>

<li><a href="#What_Is_This_Thing_Called_Var.3F">What Is This Thing Called Var?</a></li>

<li><a href="#The_Way_of_Var">The Way of Var</a></li>



<li><a href="#Conclusion">Conclusion</a></li>

</ol>

</td></tr></tbody></table>



<a name="The_Five-Day_Lesson_Plan"></a><h4> <span class="mw-headline">The Five-Day Lesson Plan</span></h4>

<p>Back in <a href="/2010/02/JavaScript_Tutorial_-_Lesson_1" title="Tutorial:JavaScript Tutorial - Lesson 1">Part I</a>, we covered the heart of JavaScript:most of the important syntax and many of the most commonly used objects. It is now time to refine your JavaScript knowledge and become a true JavaScript master. And here&#8217;s what you&#8217;ll find along the path to enlightenment.

</p>

<dl><dt> Day 1</dt><dd>



</dd><dd>Introductions and the tying up of a few loose ends. A pretty light start, with just a few tips and teasers to get you into the mood. Highlights include a new kind of if-then-else statement and the true meaning of var.

</dd><dt> Day 2</dt><dd>

</dd><dd>Fancy string handling, saving information about your visitors after they&#8217;ve left your site, and a new type of array.

</dd><dt> Day 3</dt><dd>

</dd><dd>Setting timelines on your pages so that different events occur at different times. Bonus:making your JavaScript work on  as many browsers as possible.

</dd><dt> Day 4</dt><dd>

</dd><dd>Preloading images, image maps and JavaScript. Creating your own objects and using loops to easily get at hard-to-find objects.

</dd><dt> Day 5</dt><dd>

</dd><dd>Tools for developing and testing JavaScript, debugging techniques, and tips for making your JavaScript code run quickly.



</dd></dl>

<p>By the end of these five lessons, you should have a grip on the full range of JavaScript possibilities. With this knowledge firmly in your grasp, a vast array of Internet applications will be yours for the writing.

</p><p>Let&#8217;s get started with a lovely if-then-else shortcut.

</p>

<a name="An_If-Then-Else_Shortcut"></a><h4> <span class="mw-headline">An If-Then-Else Shortcut</span></h4>

<p>One of the most commonly used statements in JavaScript is the good old if-then-else. Take the Webmonkey reward schedule for instance:

</p>

<pre class="brush: js"> if (monkey_behavior == "good")

 {

 	var toy = "videogames";

 } else {

 	var toy = "rocks";



 }

</pre>

<p>In plain English, this means, &#8220;If the monkey&#8217;s been good, he gets to play videogames. If not, he gets only rocks.&#8221; For reasons of legibility, it is a perfectly good way to do this. For those who don&#8217;t like to squander keystrokes, however, there is a shortcut (albeit, a less legible one). It&#8217;s called the &#8220;conditional operator,&#8221; and it goes a little something like this:

</p>

<pre class="brush: js"> var toy = (monkey_behavior=="good")&nbsp;? "videogames"&nbsp;:"rocks";



</pre>

<p>This expression does the same thing as the if-then-else statement above it. See what I mean about legibility? The conditional operator has three parts:a conditional test, a value to return if that test is true, and a value to return if that test is false. So, in the above example, the conditional test is <code>(monkey_behavior=="good")</code>. If that test is true, it returns the value after the question mark. In this case, it&#8217;s the string videogames. If the conditional test is false, the value after the colon is returned; in this case, it&#8217;s rocks.

</p><p>This sort of shortcut is most useful inside function calls. For example, you can use it to do something like this:

</p>

<pre class="brush: js"> var password = "open sesame";

 var answer = prompt("what's the password? ","");

 alert((answer == password)&nbsp;? "welcome!"&nbsp;:"buzz off");

</pre>

<p><a href="http://www.wired.com/wired/webmonkey/stuff/advanced_js_tutorial_files/ifthenshortcut.html" class="external text" title="http://www.wired.com/wired/webmonkey/stuff/advanced_js_tutorial_files/ifthenshortcut.html" rel="nofollow">Click here</a> to see this in action. What you&#8217;re seeing is the conditional operator doing its job and returning either welcome or buzz off, depending on the answer you give at the prompt. The value returned by the conditional gets sent to alert, which throws up an alert box with that value.

</p><p>Without the conditional operator, the code would look like this:

</p>

<pre class="brush: js"> var password = "open sesame";

 var answer = prompt("what's the password? ","");

 if (answer == password)

 {

 	alert("welcome");

 } else {

 	alert("buzz off");

 }



</pre>

<p>It&#8217;s definitely longer, but some people find it more readable, and understandable, to actually write out the if-then-else statement. The method you choose is simply a matter of personal preference.

</p><p>OK, last stop on today&#8217;s tour of loose ends: the mysterious <code>var</code>.

</p>

<a name="What_Is_This_Thing_Called_Var.3F"></a><h4> <span class="mw-headline">What Is This Thing Called Var?</span></h4>

<p>Way back in Part I, <a href="/2010/02/JavaScript_Tutorial_-_Lesson_2" title="Tutorial:JavaScript Tutorial - Lesson 2">Day 2</a>, I said that the first time you use a variable, you should declare it with the word &#8220;var.&#8221; I promised that I&#8217;d explain why when I talked about functions. Well, I forgot! So, now is the time.

</p><p>Just to jiggle your memory, here&#8217;s an example of var in use:

</p>

<pre class="brush: js"> var happiness = "a banana split";

 alert("The monkeys think happiness is " + happiness);

</pre>



<p>This little blurb declares a variable called happiness, then throws up an alert box that uses that variable.

</p><p>If you&#8217;ve been looking at other people&#8217;s JavaScript, you might have noticed that not everyone declares their variables with var, which can cause problems. First, some versions of MSIE will bomb, or at least act strangely, if a variable isn&#8217;t declared with var. This is especially true for MSIE on Macs. Second, if you want to write JavaScripts of any significant size, you&#8217;re going to have to write your own functions. And once you start writing your own functions, you really need to understand what var is all about.

</p><p>As described in Part I, <a href="/2010/02/JavaScript_Tutorial_-_Lesson_4" title="Tutorial:JavaScript Tutorial - Lesson 4">Day 4</a>, a function is a block of JavaScript that can be called when necessary. The best functions are self-contained. You know what goes into the function and what comes out of it, and, once you&#8217;ve written the function, you don&#8217;t have to worry about how it works.

</p><p>As long as all your functions are self-contained, you never have to worry that writing a new function will accidentally screw up a function you&#8217;ve already written. The key to writing self-contained functions is to make sure that your function doesn&#8217;t alter variables that aren&#8217;t passed directly into them as parameters.

</p><p>Here&#8217;s an example of what can happen if you&#8217;re not careful. Let&#8217;s say you want to write a program that converts Fahrenheit temperatures into Celsius. Click the <a href="http://www.wired.com/wired/webmonkey/stuff/advanced_js_tutorial_files/tempconvert.html" class="external text" title="http://www.wired.com/wired/webmonkey/stuff/advanced_js_tutorial_files/tempconvert.html" rel="nofollow">Fahrenheit/Celsius converter</a> to see what I mean. If you convert 50 degrees Fahrenheit, you get a message saying, &#8220;50 degrees Fahrenheit is 10 degrees Celsius.&#8221; You could write a script without vars that would look something like this:

</p>

<pre class="brush: js"> function fahrenToCelsius(faren)

 {

     temp = (faren - 32) * 5/9;

     return temp;

 }

 function convertTemp()

 {

     temp = prompt("what temperature fahrenheit? ","50");

     celsius = fahrenToCelsius(temp);

     alert(temp + " degrees Fahrenheit is " +

     celsius + " degrees Celsius.");

 }

</pre>

<p>The workings of these functions should be pretty clear to you. One function named <code>convertTemp()</code> calls another function named <code>fahrenToCelsius()</code> and returns the results. Take a moment to make sure you understand what&#8217;s going on. Breathe. Breathe. If it&#8217;s just not coming to you, revisit <a href="/2010/02/JavaScript_Tutorial_-_Lesson_4" title="Tutorial:JavaScript Tutorial - Lesson 4">Day 4</a>, which covers functions at great length.



</p><p>OK, ready?

</p><p>The confusing thing about this example is that the variable called temp is used in both functions. In the <code>convertTemp()</code> function, it&#8217;s used to store the temperature in Fahrenheit (which is supplied by the user). In the <code>fahrenToCelsius()</code> function, it&#8217;s used to calculate temperature in Celsius. Not only does this confuse us, it also confuses JavaScript. Here&#8217;s what happens when you <a href="http://www.wired.com/wired/webmonkey/stuff/advanced_js_tutorial_files/tempconvert_bad.html" class="external text" title="http://www.wired.com/wired/webmonkey/stuff/advanced_js_tutorial_files/tempconvert_bad.html" rel="nofollow">try running the code without vars</a>.

</p><p>Notice that if you try to convert 50 degrees Fahrenheit, you get a message that says, &#8220;10 degrees Fahrenheit is 10 degrees Celsius.&#8221; Why does the program suddenly think you entered 10 degrees instead of 50? Let&#8217;s trace the functions to see what happened.

</p><p>When we call <code>convertTemp()</code> and type &#8220;50&#8243; into the prompt, we get

</p>

<pre class="brush: js"> temp = 50;



</pre>

<p>In the next step, &#8220;temp&#8221; is passed to the function called <code>farenToCelsius()</code>. Inside <code>farenToCelsius()</code>, the parameter called <code>faren</code> is then set to 50 and &#8220;temp&#8221; gets set to (50 &#8211; 32) * 5/9, which is 10. Before returning the value, you have:

</p>

<pre class="brush: js"> faren = 50

 temp = 10

</pre>

<p>Now <code>farenToCelsius()</code> returns 10 to the variable <code>celsius</code>:



</p>

<pre class="brush: js"> temp = 10

 celsius = 10

</pre>

<p>And we&#8217;re left with the false statement, &#8220;10 degrees Fahrenheit is 10 degrees Celsius.&#8221;

</p><p>It&#8217;s possible to solve this issue if you carefully avoid naming your variables the same thing. If you didn&#8217;t have a variable called temp in both functions, you wouldn&#8217;t have a problem.

</p><p>Unfortunately, this isn&#8217;t the best solution. As you start adding more and more functions to your script, it becomes harder to ensure that you&#8217;re not re-using variable names. Also, you will repeatedly use lots of variable names, like loop, index, count, and the_name. Coming up with different versions of these commonly used variable names would be a real pain.

</p><p>A better solution is to tell JavaScript that the variable called temp inside the <code>fahrenToCelsius()</code> function is different from the temp variable in the <code>convertTemp()</code> function. If every function has its own special temp variable, then you don&#8217;t have to worry about certain functions messing with the variables of other functions.

</p><p>If you haven&#8217;t guessed yet, this is exactly what var does. Let&#8217;s take a look.

</p>

<a name="The_Way_of_Var"></a><h4> <span class="mw-headline">The Way of Var</span></h4>



<p>To keep JavaScript from mixing up same-name variables, put var in front of your variables as you declare them. A variable inside a function that&#8217;s declared with var is called a local variable, and it only exists inside that function. In general, you want your variables to be local whenever possible.

</p><p>Here is the JavaScript with the correct vars in it:

</p>

<pre class="brush: js"> function fahrenToCelsius(faren)

 {

 	var temp = (faren - 32) * 5 / 9;

 	return temp;

 }



 function convertTemp()

 {

 	var temp = prompt("what temperature Fahrenheit? ","50");

 	var celsius = badFahrenToCelsius(temp);

 	alert(temp + " degrees Fahrenheit is " +

 	celsius + " degrees Celsius.");

 }

</pre>

<p>And here&#8217;s how it works. Let&#8217;s say we call <code>convertTemp()</code> and type 50 into the prompt. Because we used var before the prompt, this temp is localized to the <code>convertTemp()</code> function. So &#8230;

</p>

<pre class="brush: js"> (inside convertTemp) temp = 50

</pre>



<p>As before, we pass temp to the function called <code>fahrenToCelsius()</code>. Inside <code>fahrenToCelsius()</code>, the parameter called <code>faren</code> gets set to 50. Then temp is set with the line:

</p>

<pre class="brush: js"> var temp = (faren - 32) * 5 / 9;

</pre>

<p>As before, putting that var in front of temp tells JavaScript, &#8220;This variable called temp is different than any other variable called temp. This one exists only inside the <code>fahrenToCelsius</code> function.&#8221; Once JavaScript finishes with <code>fahrenToCelsius()</code>, the special temp variable vanishes. So, just before <code>fahrenToCelsius()</code> returns,



</p>

<pre class="brush: js"> faren = 50

 (inside fahrenToCelsius) temp = 10

 (inside convertTemp) temp = 50

</pre>

<p><code>fahrenToCelsius()</code> then returns its version of the temp variable, which is 10. Once we leave <code>fahrenToCelsius()</code>, its version of the temp variable vanishes.

</p><p>When <code>fahrenToCelsius()</code> returns, it sets the variable called <code>celsius</code> to 10:

</p>



<pre class="brush: js"> (inside convertTemp) temp = 50



 (inside convertTemp) celsius = 10

</pre>

<p>And thus the alert message says, &#8220;50 degrees Fahrenheit is 10 degrees Celsius.&#8221; Which is exactly what we want.

</p><p>To review, by using var before a variable, you localize that variable to the one function that houses it. And once that function ends, the variable ceases to exist.

</p><p>And that&#8217;s the (loose) end of today&#8217;s lesson. Now all that&#8217;s left is your homework assignment.

</p>

<a name="Conclusion"></a><h4> <span class="mw-headline">Conclusion</span></h4>

<p>I didn&#8217;t want to give you anything too heavy on the very first day. Mostly I just wanted to make sure you understood all the elements covered in Part I. After today, we&#8217;ll be diving in pretty deep, and, if you don&#8217;t have a firm grasp of the basics, you might slide into an abyss of confusion. Or &#8211; even worse &#8211; stop reading. So, make double-sure you understood:

</p>

<ul><li> why var is a good thing;

</li><li> how to use the if-then-else shorthand operator.

</li></ul>



<p><br />

Before we get down and dirty tomorrow, put your knowledge to the test with a little <a href="http://www.wired.com/wired/webmonkey/stuff/advanced_js_tutorial_files/AJST_homework1.html" class="external text" title="http://www.wired.com/wired/webmonkey/stuff/advanced_js_tutorial_files/AJST_homework1.html" rel="nofollow">exercise</a> I whipped up.

</p><p>Now, on to the <a href="/2010/02/Advanced_JavaScript_Tutorial_-_Lesson_2" title="Tutorial:Advanced JavaScript Tutorial - Lesson 2"> next Lesson</a>

</p><div id='linker_widget' class='contextly-widget'></div>]]></content:encoded>
            <wfw:commentRss>http://www.webmonkey.com/2010/02/advanced_javascript_tutorial_-_lesson_1/feed/</wfw:commentRss>
        <slash:comments>1</slash:comments>

        
    </item>
    
    <item>
        <title>Advanced JavaScript Tutorial &#8211; Lesson 2</title>
        <link>http://www.webmonkey.com/2010/02/advanced_javascript_tutorial_-_lesson_2/</link>
        <comments>http://www.webmonkey.com/2010/02/advanced_javascript_tutorial_-_lesson_2/#comments</comments>
        <pubDate>Tue, 16 Feb 2010 01:45:47 +0000</pubDate>

                <dc:creator>Webmonkey Staff</dc:creator>

        <guid isPermaLink="false">http://stag.wired.com/primate/?p=721</guid>
        		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[cookies]]></category>
		<category><![CDATA[thau]]></category>
		<category><![CDATA[wiki]]></category>
        <description><![CDATA[Welcome back. Now that your brain has re-acclimated to the semicolons and curly braces of the JavaScript world, it&#8217;s time to learn something useful and exciting. We&#8217;ll spend this lesson sampling those tasty treats known as cookies &#8211; the little bits of information you can leave on the computers of people who visit your site. [...]]]></description>

            <content:encoded><![CDATA[<!-- wpautop disabled --><p>Welcome back. Now that your brain has re-acclimated to the semicolons and curly braces of the JavaScript world, it&#8217;s time to learn something useful and exciting.

</p><p>We&#8217;ll spend this lesson sampling those tasty treats known as cookies &#8211; the little bits of information you can leave on the computers of people who visit your site. Cookies allow you to give your pages a personal touch. For instance, with a cookie you can &#8220;remember&#8221; people&#8217;s names and serve up a warm greeting every time they re-visit. You can also remember user preferences &#8211; if a visitor generally comes in on a slow connection, a cookie lets you know to automatically serve them minimal graphics.</p>
<br />
<span id="more-721"></span>
<p>Cookies can be very useful — and sometimes scary:When I buy airplane tickets online, the service I use remembers not only my name, but also where I live and my seating preferences. It even knows who I traveled with last and asks if that person will be joining me on my next flight. There&#8217;s a fine line between useful and invasive.

</p><p>As long as you use them responsibly and effectively (and don&#8217;t freak anyone out with Big Brother knowledge), cookies can be extremely handy for all sorts of reasons. So I&#8217;m going to show you how they work. But before we get our hands all doughy, we should cover two JavaScript topics:fancy string handling and associative arrays.

</p>

<table id="toc" class="toc" summary="Contents"><tbody><tr><td><div id="toctitle"><h2>Contents</h2> </div>



<ol>

<li><a href="#Fancy_String_Handling">Fancy String Handling</a></li>

<li><a href="#indexOf">indexOf</a></li>

<li><a href="#charAt">charAt</a></li>

<li><a href="#String_Exercise_1">String Exercise 1</a>



<ol>

<li><a href="#Substring">Substring</a></li>

<li><a href="#The_Split_Method">The Split Method</a></li>

<li><a href="#Associative_Arrays">Associative Arrays</a></li>

<li><a href="#Example_of_an_Associative_Array">Example of an Associative Array</a></li>



<li><a href="#Cookie_Introduction">Cookie Introduction</a></li>

<li><a href="#More_About_Cookies">More About Cookies</a></li>

</ol>

</li>

<li><a href="#Setting_Cookies">Setting Cookies</a>

<ol>

<li><a href="#Reading_Cookies">Reading Cookies</a></li>



</ol>

</li>

<li><a href="#Complicated_Cookie_Reading">Complicated Cookie Reading</a></li>

<li><a href="#Reading_and_Writing_Multiple_Cookies">Reading and Writing Multiple Cookies</a></li>

<li><a href="#More_About_Cookies_2">More About Cookies</a></li>

<li><a href="#Cookie_Path_and_Domain">Cookie Path and Domain</a></li>



<li><a href="#Lesson_2_Review">Lesson 2 Review</a></li>

</ol>

</td></tr></tbody></table>



<a name="Fancy_String_Handling"></a><h4> <span class="mw-headline">Fancy String Handling</span></h4>

<p>Why do you have to learn about fancy string handling before getting into the joyous world of cookies? Well, it turns out that cookies are strings. To store visitor information, you have to first build a special cookie string. And then to read the information when the visitor returns, you have to decode the cookie string. To create and interpret these strings, you have to know your way around JavaScript&#8217;s string library.

</p><p>You should be pretty familiar with strings, since we&#8217;ve been working with them all along, but for a refresher, take a look at <a href="/2010/02/JavaScript_Tutorial_-_Lesson_2" title="Tutorial:JavaScript Tutorial - Lesson 2">Part I, Day 2</a> to see how to make an ordinary string bold:

</p>

<pre class="brush: js"> var normal_monkey = "I am a monkey!&lt;br&gt;";

 document.writeln("Normal monkey " + normal_monkey);

 var bold_monkey = normal_monkey.bold();

 document.writeln("Bold monkey " + bold_monkey);



</pre>

<p>The statement:

</p>

<pre class="brush: js"> var bold_monkey = normal_monkey.bold();

</pre>

<p>Is the same as the statement:

</p>

<pre class="brush: js"> var bold_monkey = "&lt;b&gt;" + normal_monkey + "&lt;/b&gt;";

</pre>

<p>The first version just looks neater. One of the many methods of the string object is <code>bold</code>, and it&#8217;s sort of silly. Less silly are the methods <code>indexOf, charAt, substring,</code> and <code>split</code>, which actually get inside strings and see what they&#8217;re made of. Let&#8217;s look at <code>indexOf</code> first.



</p>

<a name="indexOf"></a><h3> <span class="mw-headline">indexOf</span></h3>

<p>The <code>indexOf</code> finds the location of a set of characters inside a string and tells you where the substring starts. If the string doesn&#8217;t contain the substring, <code>indexOf</code> returns &#8220;-1.&#8221; Here are some examples:

</p>

<dl><dt> <code>var the_word = "monkey";</code>

</dt><dd>Let&#8217;s start with the word &#8220;monkey.&#8221;

</dd><dt> <code>var location_of_m = the_word.indexOf("m");</code>



</dt><dd>The <code>location_of_m</code> will be &#8220;0,&#8221; because that&#8217;s the starting position of a string.

</dd><dt> <code>var location_of_o = the_word.indexOf("o");</code>

</dt><dd>The <code>location_of_o</code> will be &#8220;1.&#8221;

</dd><dt> <code>var location_of_key = the_word.indexOf("key");</code>

</dt><dd><code>location_of_key</code> is &#8220;3&#8243; because the substring &#8220;key&#8221; starts with &#8220;k,&#8221; which is position three in the word &#8220;monkey.&#8221;



</dd><dt> <code>var location_of_y = the_word.indexOf("y");</code>

</dt><dd>The <code>location_of_y</code> is &#8220;5.&#8221;

</dd><dt> <code>var cheeky = the_word.indexOf("q");</code>

</dt><dd>The <code>cheeky</code> is &#8220;-1&#8243; because there&#8217;s no letter &#8220;q&#8221; in the word &#8220;monkey.&#8221;

</dd></dl>

<p>A more realistic use of <code>indexOf</code> is:



</p>

<pre class="brush: js"> var the_email = prompt("What's your email address?", "");

 var the_at_is_at = the_email.indexOf("@");

 if (the_at_is_at == -1)

 {

 	alert("You loser, email addresses must

 	have @ signs in them.");

 }

</pre>

<p>This little scrap of code asks users for their email address, and then checks to see if it&#8217;s a valid address. If the address doesn&#8217;t contain an @ sign, it can&#8217;t be valid. Enter <code>indexOf</code>, which checks for &#8220;@&#8221; in the string.

</p>

<a name="charAt"></a><h3> <span class="mw-headline">charAt</span></h3>

<p>The <code>charAt</code> finds out what letter is at a certain position inside a string. Here it is in action:

</p>

<pre class="brush: js"> var the_word = "monkey";

 var the_first_letter = the_word.charAt(0);

 var the_second_letter = the_word.charAt(1);

 var the_last_letter = the_word.charAt(the_word.length-1);



</pre>

<p>After this, <code>the_first_letter</code> is &#8220;m,&#8221; <code>the_second_letter</code> is &#8220;o,&#8221; and <code>the_last_letter</code> is &#8220;y.&#8221; Note that you can find out how many letters are in a word using the length property of the string. In this case, <code>the_word</code> is &#8220;monkey,&#8221; so <code>the_word.length</code> is &#8220;6.&#8221; Don&#8217;t forget that the first character of a string is at position &#8220;0&#8243; (as in <code>charAt(0)</code>), so the last letter will be in position <code>length-1</code>, which is why the last line features <code>the_word.length-1</code>.



</p><p>Before going over <code>substring</code> and <code>split</code>, let&#8217;s do an exercise with <code>charAt</code> and <code>indexOf</code>.

</p>

<a name="String_Exercise_1"></a><h3> <span class="mw-headline">String Exercise 1</span></h3>

<p>Your task is to write a script that will determine whether the last letter of a word is a vowel or a consonant. You can do it in a clever way, using both <code>indexOf</code> and <code>charAt</code>. Of course you <i>could</i> do it in a much less clever way without <code>indexOf</code>, but remember:the clever monkey gets the golden banana.



</p><p>Here&#8217;s an example of <a href="http://www.wired.com/wired/webmonkey/stuff/advanced_js_tutorial_files/vowel_checker.html" class="external text" title="http://www.wired.com/wired/webmonkey/stuff/advanced_js_tutorial_files/vowel_checker.html" rel="nofollow">it working</a>. When you&#8217;ve finished the exercise, or nearly died trying, learn how it&#8217;s done or double-check your work against <a href="http://www.wired.com/wired/webmonkey/stuff/advanced_js_tutorial_files/string_solution.html" class="external text" title="http://www.wired.com/wired/webmonkey/stuff/advanced_js_tutorial_files/string_solution.html" rel="nofollow">my solution</a>. Or, if you&#8217;re so pleased with your solution that you don&#8217;t want to sully your mind with mine, feel free to carry on with the string-a-thon.

</p>

<a name="Substring"></a><h4> <span class="mw-headline">Substring</span></h4>

<p>The <code>substring</code> is just like <code>charAt</code> except it can grab entire substrings from a word, not just letters. Here&#8217;s the format:

</p>



<pre class="brush: js"> var the_substring = the_string.substring(from, to);

</pre>

<p>&#8220;From&#8221; refers to the position of the first character of the substring, and &#8220;to&#8221; is, strangely enough, one greater than the last position of the substring. Using this weird method to mark the beginning and end of the substring makes it so that &#8220;to&#8221; minus &#8220;from&#8221; gives you the length of the substring:

</p>

<pre class="brush: js"> var the_string = "monkey";

 var clergy = the_string.substring(0,4);

 var tool = the_string.substring(3,6);

</pre>

<p>After this batch of code runs, &#8220;clergy&#8221; will equal &#8220;monk&#8221;; &#8220;tool&#8221; will equal &#8220;key.&#8221;

</p><p>The <code>substring</code> is often used with <code>indexOf</code> to break apart strings. For example, you could pull out the domain name of a given URL:

</p>



<pre class="brush: js"> var the_url = prompt("What's the URL?","");

 var lead_slashes = the_url.indexOf("//");

 var domain_start = lead_slashes + 2;

 var without_resource = the_url.substring(domain_start, the_url.length);

 var next_slash = without_resource.indexOf("/");

 var domain = without_resource.substring(0, next_slash);

</pre>

<p>Which means if you enter &#8220;<a href="http://www.webmonkey.com/javascript/index.html" class="external free" title="http://www.webmonkey.com/javascript/index.html" rel="nofollow">http://www.webmonkey.com/javascript/index.html</a>,&#8221; the domain will equal &#8220;www.webmonkey.com.&#8221; Try the <a href="http://www.wired.com/wired/webmonkey/stuff/advanced_js_tutorial_files/domain_grabber.html" class="external text" title="http://www.wired.com/wired/webmonkey/stuff/advanced_js_tutorial_files/domain_grabber.html" rel="nofollow">domain grabber</a> to see it work. If this code seems like kind of a drag to you, don&#8217;t worry. After I break it down line by line, I&#8217;ll show you how to make things much simpler using the <code>split</code> method. First, however, the analysis.

</p><p>The basic tactic we&#8217;re using here is to isolate everything between the first double slash and the next slash. Here&#8217;s how we do it:

</p>

<dl><dt> <code>var the_url = prompt("What's the URL?","");</code>



</dt><dd>This just asks the user for a URL. Let&#8217;s say they enter &#8220;<a href="http://www.webmonkey.com/javascript/index.html" class="external free" title="http://www.webmonkey.com/javascript/index.html" rel="nofollow">http://www.webmonkey.com/javascript/index.html</a>.&#8221;

</dd><dt> <code>var lead_slashes = the_url.indexOf("//");</code>

</dt><dd>This locates the first two slashes. In the case of our example URL, <code>lead_slashes</code> equals &#8220;5&#8243; because the two slashes start at position five. What&#8217;s that? You wonder, &#8220;if the string is a URL, it <i>always</i> starts with <code>http://</code>, so why don&#8217;t we just assume, oh so cleverly, that the two slashes start at position five instead of messing around with <code>indexOf</code>?&#8221; The thing is, you never know <i>what</i> people will do at the prompt. They might enter &#8220;the URL I want is <a href="http://www.blah.com/" class="external free" title="http://www.blah.com/" rel="nofollow">http://www.blah.com/</a>.&#8221; Or they might accidentally put a space before the URL. Or maybe they enter a URL that&#8217;s on a secure server, making it something like &#8220;<a href="https://www.whatever.com/" class="external free" title="https://www.whatever.com/" rel="nofollow">https://www.whatever.com/</a>.&#8221;One of the hardest things about programming is anticipating all possible cases and then coming up with a way to handle them. Ask people to drop information into an open text field, and you never quite know what you&#8217;ll get. So we can&#8217;t just assume that the two slashes are at positions five and six. Instead, we need to use the <code>indexOf</code> method to determine exactly where the two slashes start.



</dd><dt> <code>var domain_start = lead_slashes + 2;</code>

</dt><dd>This calculates the location of the first letter of the domain. Because there are two slashes, the first letter of the domain will be two positions over from the slashes.

</dd><dt> <code>var without_resource = the_url.substring(domain_start, the_string.length);</code>

</dt><dd>This grabs everything from the beginning of the domain name (which we determined in the previous line of code) and the end of the string. So, using the current example, <code>without_resource</code> is &#8220;www.webmonkey.com/javascript/index.html.&#8221;

</dd><dt> <code>var next_slash = without_resource.indexOf("/");</code>

</dt><dd>This figures out the position of the next slash in the string. Everything between the beginning of the string and this slash is domain name. In this case, the next slash is in position seventeen.

</dd><dt> <code>var domain = without_resource.substring(0, next_slash);</code>



</dt><dd>This final step grabs everything from the beginning of the string to the position of the next slash. In the current case, that makes domain equal to &#8220;www.webmonkey.com.&#8221;

</dd></dl>

<p>And there you have it. Yes, it&#8217;s a pain. If it makes you feel any better, string handling is a pain in almost all languages. JavaScript 1.2, which was introduced with Netscape 4.0, takes some strides toward making string handling easier. But it&#8217;s still a pain.

</p><p>The whole process can be handled quite a bit more easily with the <code>split</code> method.

</p>

<a name="The_Split_Method"></a><h4> <span class="mw-headline">The Split Method</span></h4>

<p>When you have a list of things separated by a delimiter, you generally use <code>split</code>. Say you have a list of names separated by commas &#8211; <code>split</code> takes that list and puts each of the names into an array. For example:



</p>

<pre class="brush: js"> var my_friends = "trixie,moxie,sven,guido,hermes";

 var friend_array = my_friends.split(",");

 for (var loop=0; loop &lt; friend_array.length; loop++)

 {

     document.writeln(friend_array[loop] + " is my friend.&lt;br&gt;");

 }

</pre>

<p>This breaks the string <code>my_friends</code> into an array of five elements. (Happily, JavaScript creates the array for you automatically, so you don&#8217;t have to use <code>new Array()</code> to create it yourself).

</p><p>After breaking the string into an array, we loop through it, writing out each friend&#8217;s name. If arrays or loops are unfamiliar to you, check out <a href="/2010/02/JavaScript_Tutorial_-_Lesson_4" title="Tutorial:JavaScript Tutorial - Lesson 4">Part I, Day 4</a> for an explanation.



</p><p>We can use <code>split</code> to make the earlier domain grabber easier to code:

</p>

<pre class="brush: js"> var the_url = prompt("What's the URL?","");

 var first_split = the_url.split("//");

 var without_resource = first_split[1];

 var second_split = without_resource.split("/");

 var domain = second_split[0];

</pre>

<p>This is much more attractive, and easier to understand, right? Here&#8217;s the breakdown:

</p>

<dl><dt> <code>var the_url = prompt("What's the URL?","");</code>

</dt><dd>As before, this requests a URL (let&#8217;s go with &#8220;<a href="http://www.webmonkey.com/javascript/index.html" class="external free" title="http://www.webmonkey.com/javascript/index.html" rel="nofollow">http://www.webmonkey.com/javascript/index.html</a>&#8221; again).

</dd><dt> <code>var first_split = the_url.split("//");</code>



</dt><dd>This splits the string into two pieces:<code>first_split[0]</code> is &#8220;http:&#8221; and <code>first_split[1]</code> is &#8220;www.webmonkey.com/javascript/index.html.&#8221;

</dd><dt> <code>var without_resource = first_split[1];</code>

</dt><dd>This just grabs the second element in the array, so now <code>without_resource</code> is &#8220;www.webmonkey.com/javascript/index.html.&#8221;

</dd><dt> <code>var second_split = without_resource.split("/");</code>



</dt><dd>This breaks <code>without_resource</code> into three pieces:<code>www.webmonkey.com</code>, <code>javascript</code>, and <code>index.html</code>. See how useful <code>split</code> is?

</dd><dt> <code>var domain = second_split[0];</code>

</dt><dd>Now all we have to do is grab the first element of the <code>second_split</code> array. And voila! We&#8217;re done.



</dd></dl>

<p>That might seem to be a lot of work at first, but you&#8217;ll get used to it pretty fast. I personally love <code>split</code> &#8211; it&#8217;s a special coding treat.

</p><p>Now that you&#8217;ve learned all the fancy string handling routines for cookies, take a breather &#8211; you&#8217;ve just digested quite a mouthful of information. Go for a little stroll. Have a snack. OK? Then it&#8217;s time to learn one last thing before sallying forth into cookie country:associative arrays.

</p>

<a name="Associative_Arrays"></a><h4> <span class="mw-headline">Associative Arrays</span></h4>

<p>If you&#8217;ve done any JavaScript programming, you&#8217;re probably familiar with arrays, which let you store lists of items and also give you access to the images, forms, and form elements of your HTML pages. In <a href="/2010/02/JavaScript_Tutorial_-_Lesson_4" title="Tutorial:JavaScript Tutorial - Lesson 4">Part I, Day 4</a>, I showed you how to create and manipulate arrays that are indexed by number. For example:

</p>

<pre class="brush: js"> var an_array = new Array("hickory","dickory");

 var element_one = an_array[0];

 var element_two = an_array[1];

 an_array[2] = "doc";

</pre>



<p>This creates a new array and initializes it with two strings. The first element of the array is accessed using its index number, &#8220;0.&#8221; The second element, element 1 of the array, is accessible with <code>an_array[1]</code>. You can add to an array by assigning something to a specific index of the array:in the example above, I made the third element of the array equal to &#8220;doc.&#8221; Now the array contains &#8220;hickory, dickory, doc.&#8221;

</p><p>Associative arrays are just like the array above, except rather than using numbers to index elements in the array, you use words.

</p>

<pre class="brush: js"> var phone_book = new Array();

 phone_book["sleepy"] = "(203) 555-1234";

 phone_book["happy"] = "(203) 555-2345";

</pre>

<p>This creates sort of a phone book. Access the phone number for &#8220;happy&#8221; by writing:

</p>

<pre class="brush: js"> var happy_number = phone_book["happy"];

</pre>

<p>Try out the working phone book example on the next page to see how an associative array might work (and get a major refresher on the use of JavaScript with forms at the same time).

</p>

<a name="Example_of_an_Associative_Array"></a><h4> <span class="mw-headline">Example of an Associative Array</span></h4>



<p><a href="http://www.wired.com/wired/webmonkey/stuff/advanced_js_tutorial_files/associative_array.html" class="external text" title="http://www.wired.com/wired/webmonkey/stuff/advanced_js_tutorial_files/associative_array.html" rel="nofollow">Click here</a>.

</p><p>This example is a bit involved, so let&#8217;s go through it slowly. First let&#8217;s look at the phone book itself. The phone book, which is defined in the header ( <code>phone_book</code>) and has seven entries, looks like this:

</p>

<pre class="brush: js"> var phone_book = new Array();

 phone_book["happy"] = "(203) 555-1234";

 phone_book["sleepy"] = "(203) 555-2345";

 phone_book["sneezy"] = "(203) 555-4321";

 phone_book["sleazy"] = "(203) 555-3245";

 phone_book["sneery"] = "(203) 555-3213";

 phone_book["bleary"] = "(203) 555-2365";

 phone_book["tweaked"] = "(203) 555-1664";

</pre>

<p>The key to each entry is the name of the dwarf, and the value of each entry is that dwarfs&#8217;s phone number. When we want to get a phone number for our favorite dwarf, say &#8220;Sneezy,&#8221; we write this:

</p>

<pre class="brush: js"> var the_number = phone_book["sneezy"];

</pre>

<p>Now let&#8217;s look at the form:

</p>

<pre class="brush: js"> &lt;form name="the_form"&gt;



 &lt;b&gt;Name:&lt;/b&gt;

 &lt;select onChange =

 "displayNumber(phone_book,this.options[selectedIndex].value);"&gt;

 &lt;option value="happy"&gt;Happy

 &lt;option value="sleepy"&gt;Sleepy

 &lt;option value="sneezy"&gt;Sneezy

 &lt;option value="sleazy"&gt;Sleazy

 &lt;option value="sneary"&gt;Sneery

 &lt;option value="bleary"&gt;Bleary

 &lt;option value="tweaked"&gt;Tweaked

 &lt;/select&gt;



 &lt;p&gt;

 &lt;b&gt;Number&lt;/b&gt;

 &lt;input type="text" name="number_box" value=""&gt;

 &lt;/form&gt;

</pre>

<p>Note that the form and the elements inside the form have names. This allows us to read and write to the form elements. Also, take a look at the <code>onChange</code> handler in the select tag. This says that when the <code>select</code> is changed, it calls the function <code>displayNumber</code>, which is defined up in the header. If I use the pulldown to select &#8220;sneezy,&#8221; the expression <code>this.options[selectedIndex].value</code> returns &#8220;sneezy.&#8221; If you need a refresher on this kind of form madness, check out <a href="/2010/02/JavaScript_Tutorial_-_Lesson_5" title="Tutorial:JavaScript Tutorial - Lesson 5">Part I, Day 5</a>. Once we&#8217;ve figured out what the user has selected, we jump to the <code>displayNumber</code> function, which looks like this:



</p>

<pre class="brush: js"> function displayNumber(phone_book, entry)

 {

     var the_number = phone_book[entry];

     window.document.the_form.number_box.value = the_number;

 }

</pre>

<p>It takes two parameters &#8211; a phone book and a name &#8211; to make this function work. The first line of the function,

</p>

<pre class="brush: js"> var the_number = phone_book[entry];

</pre>

<p>looks the name up in the phone book, and the next line,

</p>

<pre class="brush: js"> window.document.the_form.number_box.value = the_number;

</pre>

<p>puts that number into the form element called <code>number_box</code>.



</p><p>And there you have it. As you can see, associative arrays are a good way to link one string to another. They&#8217;re useful for linking names to phone numbers, to passwords, to birthdays, and all kinds of things. A few lessons from now, I&#8217;ll introduce another useful trick you can do with associative arrays, so don&#8217;t cast them into the facts-best-forgotten pit quite yet.

</p><p>And now, if you&#8217;re ready for it, let&#8217;s sink our teeth into cookies!

</p>

<a name="Cookie_Introduction"></a><h4> <span class="mw-headline">Cookie Introduction</span></h4>

<p>Now that you&#8217;ve mastered advanced string handling and associative arrays, it&#8217;s time to open up the cookie jar. As I mentioned earlier, cookies are little bits of information that you can leave on a user&#8217;s hard drive, where they stay even after the user leaves your site or turns off the computer, which is extremely useful when you want to remember information about repeat visitors.

</p><p>Let&#8217;s look at a basic example of a working cookie. In this example, we set a cookie on one page and then read it from another page. As you play around with the example, try to think about how you would do this without cookies. Here&#8217;s the very basic example of <a href="http://www.wired.com/wired/webmonkey/stuff/advanced_js_tutorial_files/cookie_example.html" class="external text" title="http://www.wired.com/wired/webmonkey/stuff/advanced_js_tutorial_files/cookie_example.html" rel="nofollow">a working cookie</a>.

</p><p>Had your fill of cookie dough tasting? Let&#8217;s move on to the next step of the recipe.

</p>

<a name="More_About_Cookies"></a><h4> <span class="mw-headline">More About Cookies</span></h4>

<p>Because cookies involve writing to, and reading from, users&#8217; hard drives, security issues arise that the people who wrote Netscape, MSIE, and the other cookie-friendly browsers had to confront. The most important limitations for this tutorial are:

</p>



<ol><li> Not everyone has a cookie-friendly browser (but most do).

</li><li> Not everyone who has a cookie-friendly browser will accept your cookies (but most will).

</li><li> Each domain is allotted only 20 cookies, so use them sparingly.

</li><li> Cookies must be no larger than 4 KB. That&#8217;s just over 4,000 characters, which is plenty.

</li></ol>

<p>With those limitations in mind, let&#8217;s learn about setting cookies.

</p>

<a name="Setting_Cookies"></a><h3> <span class="mw-headline">Setting Cookies</span></h3>

<p>Setting a basic cookie is very easy. All you have to do is create a string in the form of <code>cookie_name=value</code> and then set the <code>document.cookie</code> property to that. The only trick:cookie values must never have spaces, commas, or semicolons. Happily, you don&#8217;t really have to worry about this because a pair of functions will code and decode your properties:they are <code>escape()</code> and <code>unescape()</code>.



</p><p>Our simple example, which stored your name as a cookie, looks like this:

</p>

<pre class="brush: js">function setCookie()

{

    var the_name = prompt("What's your name?","");



    var the_cookie = "wm_javascript=" + escape("username:" + the_name);



    document.cookie = the_cookie;



    alert("Thanks, now go to the next page.");



}

</pre>

<p>The middle two lines of this function are the critical ones:

</p>

<dl><dt> <code>var the_cookie = "wm_javascript=" + escape("username:" + the_name);</code>

</dt><dd>If I entered &#8220;dave thau&#8221; at the prompt, this line would create a string that looks like <code>wm_javascript=username%3Adave%20thau</code>. This means that I&#8217;m going to save a cookie named <code>wm_javascript</code> to the hard drive. That cookie is going to have the value <code>username%3Adave%20thau</code> &#8211; the escape() function replaced the colon after username with <code>%3A</code> and the space between &#8220;dave&#8221; and &#8220;thau&#8221; with a <code>%20</code>.When we read the cookie, we&#8217;re going to look for the cookie named <code>wm_javascript</code>, then grab the <code>username%3Adave%20thau</code>, unescape() it, which changes the <code>%3A</code> back to a colon and the <code>%20</code> back into a space, and then chop off the <code>username:</code>.



</dd><dt> <code>document.cookie = the_cookie;</code>

</dt><dd>And this sets the cookie. Easy, huh?

</dd></dl>

<p>Now let&#8217;s learn how to read cookies.

</p>

<a name="Reading_Cookies"></a><h4> <span class="mw-headline">Reading Cookies</span></h4>

<p>Once you save a cookie to someone&#8217;s hard disk, it&#8217;s easy to read. Here&#8217;s the code that reads the example cookie:

</p>

<pre class="brush: js">function readCookie()

{

    var the_cookie = document.cookie;

    var the_cookie = unescape(the_cookie);

    var broken_cookie = the_cookie.split(":");

    var the_name = broken_cookie[1];

    alert("Your name is:" + the_name);

}

</pre>

<p>The first line is the important one. Whenever your browser opens a Web page, it calls in whatever cookies it can, then loads them into the <code>document.cookie</code> property.



</p><p>The tricky part about reading cookies is getting the information you want out of them. Remember, the cookie we set looks like this:<code>wm_javascript=username%3Adave%20thau</code>. Everything after the first line of the function is devoted to pulling the username out of the cookie. Here&#8217;s a breakdown of that process:

</p>

<dl><dt> <code>var the_cookie = unescape(the_cookie);</code>

</dt><dd>Undo the stuff that the escape() function created. In this case, unescape() swaps the <code>%3A</code> with a colon, and the <code>%20</code> with a space.

</dd><dt> <code>var broken_cookie = the_cookie.split(":");</code>



</dt><dd>Split the cookie into two parts at the colon.

</dd><dt> <code>var the_name = broken_cookie[1];</code>

</dt><dd>Grab the part after the colon, which is dave thau.

</dd><dt> <code>alert("Your name is:" + the_name);</code>

</dt><dd>Yee-haw!

</dd></dl>

<p>This example used a cookie that only stored one bit of information:the username. As I said before, cookies can store up to 4 KB, which leaves plenty of room for quite a bit more information.

</p>

<a name="Complicated_Cookie_Reading"></a><h3> <span class="mw-headline">Complicated Cookie Reading </span></h3>

<p>If you want your cookie to contain more than just one piece of information, you can make the value of the cookie as long as you want (up to the 4000 character limit). Say you&#8217;re looking to store a person&#8217;s name, age, and phone number. You do something like this:

</p>



<pre class="brush: js">var the_cookie = "username:thau/age:older than the hills/phone:411";

document.cookie="my_happy_cookie=" + escape(the_cookie);

</pre>

<p>I use a slash to separate property names and a colon to distinguish the property name from the property value. The slash and colon are arbitrary choices &#8211; they could be anything, like say, this:

</p>

<pre class="brush: js">var the_cookie = "username=thau&amp;age=older than the hills&amp;phone=411";

document.cookie="my_happy_cookie=" + escape(the_cookie);

</pre>

<p><br />

The delimiters you choose are up to you. Just remember what you used so you can decode the cookie later.

</p><p><br />

As with our simple example, the easy part is setting the cookie. Things get a little sticky, however, when it comes to pulling the information out of the cookie when you need it. I suggest using associative arrays to store all the information. For example, let&#8217;s say you saved this to someone&#8217;s hard drive:

</p>

<pre class="brush: js">my_happy_cookie=username:thau/age:older than the hills/phone:411

</pre>

<p>You could put the information into a handy associative array like this:

</p>



<pre class="brush: js">function readTheCookie(the_info)

{

// load the cookie into a variable and unescape it



var the_cookie = document.cookie;

var the_cookie = unescape(the_cookie);



// separate the values from the cookie name



var broken_cookie = the_cookie.split("=");

var the_values = broken_cookie[1];



// break each name:value pair into an array



var separated_values = the_values.split("/");



// loop through the list of name:values and load

// up the associate array



var property_value = "";



for (var loop = 0; loop &lt; separated_values.length; loop++)



{

property_value = separated_values[loop];

var broken_info = property_value.split(":");

var the_property = broken_info[0];

var the_value = broken_info[1];

the_info[the_property] = the_value;

}



}

</pre>

<p>If you had this function in your JavaScript, you could call it like this:

</p>

<pre class="brush: js">var cookie_information = new Array();

readTheCookie(cookie_information);

</pre>

<p>And then you&#8217;d have <code>cookie_information["username"], cookie_information["age"],</code> and <code>cookie_information["phone"]</code> set correctly.

</p><p><br />

This may look a little funky, but actually it&#8217;s not that hard. Here&#8217;s a step-by-step analysis of what&#8217;s going on:



</p><p><br />

</p>

<dl><dt> <code>var the_cookie = document.cookie;</code>

</dt></dl>

<dl><dd>This is the easy part. It puts the cookie into a variable.

</dd></dl>

<dl><dt> <code>var the_cookie = unescape(the_cookie);</code>

</dt></dl>

<dl><dd>Undo the work of escape().

</dd></dl>

<dl><dt> <code>var broken_cookie = the_cookie.split("=");<br /> var the_values = broken_cookie[1];</code>



</dt></dl>

<dl><dd>These lines make <code>the_values</code> equal to <code>username:thau/age:older than the hills/phone:411</code>.

</dd></dl>

<dl><dt> <code>var separated_values = the_values.split("/");</code>

</dt></dl>

<dl><dd>This makes an array called <code>separated_values</code> that contains three elements:<code>separated_values[0] = "username:thau"<br /> separated_values[1] = "age:older than the hills"<br /> separated_values[2] = "phone:411"<br /></code>



</dd></dl>

<dl><dt> <code>for (loop = 0; loop &lt; separated_values.length; loop++) </code>

</dt></dl>

<dl><dd>This loops through the three elements of <code>separated_values</code>.

</dd></dl>

<dl><dt> <code>property_value = separated_values[loop];</code>

</dt></dl>

<dl><dd>This grabs the current <code>name:value pair</code>, the first one being <code>username:thau</code>.



</dd></dl>

<dl><dt> <code>var broken_info = property_value.split(":");</code>

</dt></dl>

<dl><dd>This breaks the pair into two elements into an array called <code>broken_info</code> where <code>broken_info[0] = "username"<br /> broken_info[1] = "thau"<br /></code>

</dd></dl>

<dl><dt> <code>var the_property = broken_info[0];</code>



</dt></dl>

<dl><dd>The first time through the loop, <code>the_property</code> will be &#8220;username&#8221;

</dd></dl>

<dl><dt> <code>var the_value = broken_info[1];</code>

</dt></dl>

<dl><dd><code>the_value</code> will be &#8220;thau.&#8221;

</dd></dl>

<dl><dt> <code>the_info[the_property] = the_value;</code>



</dt></dl>

<dl><dd>Here&#8217;s where associative arrays come in handy. This makes <code>the_info["username"] = "thau"</code>. So now, when you want the username from the cookie, you can just say something like <code>var the_name = the_info["username"];</code>.

</dd></dl>

<dl><dt> And so on

</dt></dl>

<dl><dd>Each time through the loop, a new element gets added to <code>the_info</code>. At the end of the loop is <code>the_info["username"] = "thau", the_info["age"] = "old as the hills"</code> and <code>the_info["phone"] = 411</code>.



</dd></dl>

<p>It <i>is</i> a bit cumbersome, but it&#8217;s the way I prefer to get large quantities of information in and out of cookies. There are lots of ways to do it, and if you find another way that you like, all the power to you.

</p><p>Okay, the last thing you need to know is what to do when you&#8217;re dishing out multiple cookies.

</p><p><br />

</p>

<a name="Reading_and_Writing_Multiple_Cookies"></a><h3> <span class="mw-headline">Reading and Writing Multiple Cookies </span></h3>

<p>On the last page, we learned how to cram lots of information into one cookie. Another way to do this is with multiple cookies.

</p><p>Saving multiple cookies is very straightforward. We&#8217;ve learned that every cookie has a name. In the last example, we named the cookie <code>my_happy_cookie</code>, and did something like this:

</p>

<pre class="brush: js">var the_cookie = "my_happy_cookie=happiness_and_joy";

document.cookie = the_cookie;



</pre>

<p>To save multiple cookies, just give each cookie a different name. If you&#8217;re adding a new cookie, setting <code>document.cookie</code> doesn&#8217;t delete cookies that are already there. So if we do this:

</p>

<pre class="brush: js">var the_cookie = "my_happy_cookie=happiness_and_joy";

document.cookie = the_cookie;

var another_cookie= "my_other_cookie=more_joy_more_happiness";

document.cookie = another_cookie;

</pre>

<p>You&#8217;ll now have access to <i>both</i> cookies. It&#8217;s sort of weird, so make sure you understand what&#8217;s going on.

</p><p>Let&#8217;s assume you executed the last block of code and you want to access <code>my_happy_cookie</code>. If you look at <code>document.cookie</code>, you&#8217;ll see this:



</p>

<pre class="brush: js">my_happy_cookie=happiness_and_joy;

my_other_cookie=more_joy_more_happiness;

</pre>

<p>If you don&#8217;t believe me, just <a href="http://www.wired.com/wired/webmonkey/stuff/advanced_js_tutorial_files/multiple_cookies.html" class="external text" title="http://www.wired.com/wired/webmonkey/stuff/advanced_js_tutorial_files/multiple_cookies.html" rel="nofollow">look at your cookie</a>.

</p><p>This is very nice, but it makes reading a specific cookie a bit more difficult. Here&#8217;s some (slightly simplified) code that allows you to isolate a specific cookie:

</p>

<pre class="brush: js">function WM_readCookie(name) {

if (document.cookie == '') {



// there's no cookie, so go no further



return false;

} else {



// there is a cookie



var firstChar, lastChar;

var theBigCookie = document.cookie;

firstChar = theBigCookie.indexOf(name);



// find the start of 'name'



if(firstChar&nbsp;!= -1) {



// if you found the cookie



firstChar += name.length + 1;



// skip 'name' and '='



lastChar = theBigCookie.indexOf(';', firstChar);



// Find the end of the value string (i.e. the next ';').



if(lastChar == -1) lastChar = theBigCookie.length;



return unescape(theBigCookie.substring(firstChar, lastChar));



} else {



// If there was no cookie of that name, return false.



return false;

}



}



}



// WM_readCookie

</pre>

<p>Since this is very well commented, I&#8217;ll just let you take a look at it and figure out what&#8217;s happening on your own (c&#8217;mon, you know everything you need to know to make sense of this).

</p><p>Once you&#8217;ve parsed that information, let&#8217;s leave our &#8220;setting and reading basic cookies&#8221; discussion and look at some of the cooler things you can do with cookies.

</p>

<a name="More_About_Cookies_2"></a><h3> <span class="mw-headline">More About Cookies</span></h3>



<p>So far, you&#8217;ve learned how to set and read a basic cookie. Unfortunately, your basic cookie will get deleted automatically when a user quits out of the browser. Sometimes this is for the best. Since each domain, such as webmonkey.com, is allowed only 20 cookies on any user&#8217;s machine, you don&#8217;t want to waste space with cookies that aren&#8217;t saved between browser sessions.

</p><p>However, if you do want to save cookies on users&#8217; hard drives, you have to set an expiration date, which has to be in a special format called GMT. For example:

</p>

<pre class="brush: js">Mon, 27-Apr-1998 00:00:00 GMT

</pre>

<p>(This is the date on which Koko the gorilla had her AOL chat session.)

</p><p>Getting the GMT right can be sort of a pain, especially when it comes to figuring out the day of the date. Is it a Monday? A Friday? To make things easier on you, JavaScript has a date method called <code>toGMTString</code>. Here&#8217;s an easy way to set an expiration date to some distant time in the future:

</p>

<pre class="brush: js">var the_date = new Date("December 31, 2023");

var the_cookie_date = the_date.toGMTString();

</pre>

<p>Once you establish an expiration date for your cookie, you have to add this information before you set the cookie. Therefore, your cookie should look like this:

</p>

<pre class="brush: js">cookie_name=blah_blah;expires=date

</pre>

<p>Basically, you&#8217;re just adding <code>expires=date</code> to the cookie string and separating the different cookie components with a semicolon.



</p><p>Here&#8217;s how to build a cookie that will last until the end of the Mayan calendar:

</p>

<pre class="brush: js">function setCookie()

{



// get the information



//



var the_name = prompt("What's your name?","");

var the_date = new Date("December 31, 2023");

var the_cookie_date = the_date.toGMTString();





// build and save the cookie



//



var the_cookie = "my_cookie=" + escape(the_name);

the_cookie = the_cookie + ";expires=" + the_cookie_date;

document.cookie = the_cookie;



}

</pre>

<p>At the end of all this, <code>the_cookie</code> will look something like this:

</p>

<pre class="brush: js">my_cookie=thau;expires=Fri, 31-Dec-2023 00:00:00 GMT

</pre>

<p>When this cookie is set, it will live on the user&#8217;s hard drive until the expiration date.

</p><p>The expiration date also allows you to delete cookies you don&#8217;t want users to have any more. If you set the expiration date of a cookie to a time that&#8217;s already passed, the cookie will be deleted from the cookie file.

</p><p>In addition to <code>name</code> and <code>expires</code>, there are two other important cookies components that you&#8217;ll need to know about: path and domain.



</p>

<a name="Cookie_Path_and_Domain"></a><h3> <span class="mw-headline">Cookie Path and Domain</span></h3>

<p>This is the last tricky cookies hurdle: By default, a cookie can be read only by HTML pages that sit on the same web server and in the same directory as the page that set the cookie.

</p><p>For example, if you have a JavaScript on &#8220;<a href="http://chimp.webmonkey.com/food/bananas/banana_puree.htm" class="external free" title="http://chimp.webmonkey.com/food/bananas/banana_puree.htm" rel="nofollow">http://chimp.webmonkey.com/food/bananas/banana_puree.htm</a>&#8221; that asks people for their names, you might want to access a given name on another one of your Web pages, such as the homepage (<a href="http://chimp.webmonkey.com/" class="external free" title="http://chimp.webmonkey.com/" rel="nofollow">http://chimp.webmonkey.com/</a>.) To allow this, you have to set the &#8220;path&#8221; of the cookie. The &#8220;path&#8221; sets the top level directory from which a cookie can be read. Set the path of a cookie to the top-level directory of your Web pages, and the cookie is readable by all your Web pages.

</p><p>Do this by adding <code>path=/;</code> to your cookie. If you just wanted the cookie readable solely in the &#8220;food&#8221; directory, you&#8217;d add <code>path=/food;</code> to your cookie.



</p><p>A second hitch is that some Web sites have lots of little domains. For example, Webmonkey might have pages at &#8220;chimp.webmonkey.com,&#8221; &#8220;gorilla.webmonkey.com,&#8221; and &#8220;ape.webmonkey.com.&#8221; By default, if a Web page on &#8220;chimp.webmonkey.com&#8221; sets a cookie, only pages on &#8220;chimp.webmonkey.com&#8221; can read it. If we wanted all the machines in the &#8220;webmonkey.com&#8221; domain to read the cookie, we&#8217;d have to add &#8220;domain=webmonkey.com&#8221; to the cookie. Don&#8217;t get clever though. Pages at &#8220;republicans.com&#8221; can&#8217;t set or read cookies from &#8220;democrats.com.&#8221;

</p><p>To put all the above together &#8211; set a cookie on the Web page &#8220;<a href="http://chimp.webmonkey.com/food/bananas/banana_puree.htm" class="external free" title="http://chimp.webmonkey.com/food/bananas/banana_puree.htm" rel="nofollow">http://chimp.webmonkey.com/food/bananas/banana_puree.htm</a>&#8221; that we want to be readable by all Webmonkey pages &#8211; we&#8217;d have to do this:

</p>

<pre class="brush: js">function setCookie()

{

var the_name = prompt("What's your name?","");

var the_cookie = "cookie_puss=" + escape(the_name) + ";"&nbsp;;

var the_cookie = the_cookie + "path=/;";

var the_cookie = the_cookie + "domain=webmonkey.com;";

document.cookie = the_cookie;

}

</pre>

<p>And so ends the cookies lesson. Let&#8217;s review what we&#8217;ve learned so far and then go onto a final exercise.

</p>

<a name="Lesson_2_Review"></a><h3> <span class="mw-headline">Lesson 2 Review</span></h3>

<p>Today was a big day, probably the biggest in this set of lessons. However, the things you learned today take you a significant step closer to the ability to create JavaScripts that are more than just cute. For example, today&#8217;s homework assignment is to add a &#8220;bookmarks&#8221; feature to your do-it-yourself Web browser.

</p><p>Here are the main topics we covered today:

</p>

<dl><dt> Advanced String Handling



</dt><dd>Including

<ul><li> <code>charAt</code> &#8211; getting a character at a certain position

</li><li> <code>indexOf</code> &#8211; getting the position of a character

</li><li> <code>substring</code> &#8211; getting a piece of a string

</li><li> <code>split</code> &#8211; splitting a string up into an array



</li></ul>

</dd></dl>

<dl><dt> Associative Arrays

</dt><dd>Another JavaScript datatype useful for storing things like phone books, password lists, birthdays, and cookie information

</dd><dt> Cookies

</dt><dd>How to set them, read them, and make them permanent

</dd></dl>

<p>Tomorrow we&#8217;ll cover:

</p>

<ul><li> Preloading images to speed up image swaps

</li><li> Creating your own objects and a do-it-yourself virtual pet

</li><li> Getting to hard-to-find objects



</li></ul>

<p><br />

Before closing the JavaScript book entirely for the day, you can hone your knowledge by trying this <a href="http://www.wired.com/wired/webmonkey/stuff/advanced_js_tutorial_files/AJST_homework2.html" class="external text" title="http://www.wired.com/wired/webmonkey/stuff/advanced_js_tutorial_files/AJST_homework2.html" rel="nofollow">homework assignment</a>.

</p><p>OK, ready? <a href="/2010/02/Advanced_JavaScript_Tutorial_-_Lesson_3" title="Tutorial:Advanced JavaScript Tutorial - Lesson 3">Next</a>!

</p><div id='linker_widget' class='contextly-widget'></div>]]></content:encoded>
            <wfw:commentRss>http://www.webmonkey.com/2010/02/advanced_javascript_tutorial_-_lesson_2/feed/</wfw:commentRss>
        <slash:comments>0</slash:comments>

        
    </item>
    
    <item>
        <title>Advanced JavaScript Tutorial &#8211; Lesson 3</title>
        <link>http://www.webmonkey.com/2010/02/advanced_javascript_tutorial_-_lesson_3/</link>
        <comments>http://www.webmonkey.com/2010/02/advanced_javascript_tutorial_-_lesson_3/#comments</comments>
        <pubDate>Tue, 16 Feb 2010 01:45:47 +0000</pubDate>

                <dc:creator>Webmonkey Staff</dc:creator>

        <guid isPermaLink="false">http://stag.wired.com/primate/?p=723</guid>
        		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[thau]]></category>
		<category><![CDATA[wiki]]></category>
        <description><![CDATA[As we learn more and more JavaScript, we can build increasingly complex applications. In the previous lesson, we added long-term memory to our JavaScripts using cookies. Now we&#8217;ll add a sense of time to our growing stock of JavaScript knowledge. Contents Timing Events and Browser Differentiation How to Time Events Timing Loops &#8211; What They [...]]]></description>

            <content:encoded><![CDATA[<!-- wpautop disabled --><p>As we learn more and more JavaScript, we can build increasingly complex applications. In the previous lesson, we added long-term memory to our JavaScripts using cookies. Now we&#8217;ll add a sense of time to our growing stock of JavaScript knowledge.</p>
<br />
<span id="more-723"></span>

<table id="toc" class="toc" summary="Contents"><tbody><tr><td><div id="toctitle"><h2>Contents</h2> </div>

<ol>

<li><a href="#Timing_Events_and_Browser_Differentiation">Timing Events and Browser Differentiation</a>



<ol>

<li><a href="#How_to_Time_Events">How to Time Events</a></li>

<li><a href="#Timing_Loops_-_What_They_Are">Timing Loops &#8211; What They Are</a></li>

<li><a href="#Timing_Loops_-_How_to_Do_Them">Timing Loops &#8211; How to Do Them</a></li>

</ol>

</li>

<li><a href="#How_to_Cancel_a_setTimeout">How to Cancel a setTimeout</a>



<ol>

<li><a href="#A_JavaScript_Clock">A JavaScript Clock</a></li>

<li><a href="#Using_Timers_with_Variables">Using Timers with Variables</a></li>

<li><a href="#Browser_Detection">Browser Detection</a></li>

<li><a href="#How_to_Detect_Browsers">How to Detect Browsers</a></li>



<li><a href="#Object_and_Method_Detection">Object and Method Detection</a></li>

</ol>

</li>

</ol>

</td></tr></tbody></table>



<p><a name="Timing_Events_and_Browser_Differentiation"></a><h3> <span class="mw-headline">Timing Events and Browser Differentiation</span></h3></p>

<p>In JavaScript, the process of moving something around the screen usually involves a loop, where the element is moved little by little over time. The question is, how do you tell JavaScript to &#8220;move that piece over a little bit every 10th of a second or so&#8221;?

</p><p>Unfortunately, this business of moving elements around is where the assortment of browsers differs the most. Almost everything I&#8217;ve covered up until now (except image swaps) works in basically all JavaScript-ready browsers. With dynamic HTML, however, you have to take special measures to make your scripts work across all the different browsers. So after I cover timing events, I&#8217;ll talk about ways to detect the type of browser a visitor is using (allowing you to serve them appropriate content). Luckily these two skills &#8211; timing events and detecting browser type &#8211; will also be useful when it comes to other neat-o features of the newer browsers.

</p><p>Let&#8217;s start with timing events on your pages.

</p>



<a name="How_to_Time_Events"></a><h4> <span class="mw-headline">How to Time Events</span></h4>

<p>It&#8217;s easy to time events in JavaScript. The key commands are the <code>setTimeout()</code> and <code>clearTimeout()</code> methods. With <code>setTimeout()</code>, JavaScript executes a certain command some time in the future. And if you change your mind, <code>clearTimeout()</code> cancels <code>setTimeout</code>.What follows is the basic format of a <code>setTimeout</code>.



</p>

<pre class="brush: js"> var the_timeout = setTimeout("some javascript statement",

                   some_number_of_milliseconds);

</pre>

<p><br />

Here&#8217;s an example:

</p>

<pre class="brush: js"> var the_timeout = setTimeout("alertAndRedirect();",3000);

</pre>

<p>There are three important things to notice about this statement:

</p>

<dl><dt> <code>setTimeout</code> returns a value.

</dt><dd>In this statement, <code>the_timeout</code> is a variable that keeps track of this specific <code>setTimeout</code>. If you ever want to cancel this specific <code>setTimeout</code>, you can refer to it using the variable. We&#8217;ll see an example of this later. And, of course, as is true for all variables, it doesn&#8217;t have to be called <code>the_timeout</code>. It can be called &#8220;Frankenstein&#8221; for all JavaScript cares.



</dd></dl>

<dl><dt> The first parameter to <code>setTimeout</code> is a string that contains a JavaScript statement.

</dt></dl>

<dl><dd>In this example, the first parameter is the string:<code>"alertAndRedirect();"</code><code>alertAndRedirect</code> is just a function I wrote that launches an alert box and redirects to this page when the user clicks &#8220;OK.&#8221; Note that the stuff in quotes is a complete JavaScript statement, with a semicolon and everything. If you executed only this statement, it would call the <code>alertAndRedirect</code> function. The <code>setTimeout</code> merely schedules that statement to occur at a specific time.If you want to see how it works, here&#8217;s the <code>alertAndRedirect() function</code>:



</dd></dl>

<pre class="brush: js"> function alertAndRedirect()

 {

 	alert('ok!  exhale!');

 	window.location.replace("timing.htm");

 }

</pre>

<dl><dt> The second parameter of <code>setTimeout</code> indicates how many milliseconds from now you want to execute the first parameter.

</dt><dd>There are 1,000 milliseconds in a second. So, to have something happen three seconds from now, the second parameter has to be 3,000 milliseconds. JavaScript is told by <code>setTimeout</code> to &#8220;call this statement <i>x</i> many milliseconds from now.&#8221; Remember that, and you&#8217;ll be fine. To make sure you know what&#8217;s going on, here&#8217;s a little exercise: Make a button that tells you when three seconds, six seconds, and nine seconds have passed. Like this one:When you&#8217;ve figured it out, or gotten sick of trying, take a look at my solution to the timer exercise:

</dd></dl>



<p><a href="http://www.wired.com/wired/webmonkey/stuff/advanced_js_tutorial_files/bell_tolls.html" class="external text" title="http://www.wired.com/wired/webmonkey/stuff/advanced_js_tutorial_files/bell_tolls.html" rel="nofollow">Click here</a>.

</p>

<a name="Timing_Loops_-_What_They_Are"></a><h4> <span class="mw-headline">Timing Loops &#8211; What They Are</span></h4>

<p>If you&#8217;re like me, this exercise threw you at first (and if it came naturally, feel free to pat yourself on the back &#8211; you deserve it). Here&#8217;s the right way to do it:have the button&#8217;s <code>onClick</code> call the following function:

</p>

<pre class="brush: js"> function ringBell()

 {

    var timer1 = setTimeout("window.document.the_form.the_text.value='3 seconds!';",3000);

    var timer2 = setTimeout("window.document.the_form.the_text.value='6 seconds!';",6000);

    var timer3 = setTimeout("window.document.the_form.the_text.value='9 seconds!';",9000);

 }

</pre>

<p>It says, &#8220;write &#8217;3 seconds&#8217; three seconds from now, &#8217;6 seconds&#8217; six seconds from now, and &#8217;9 seconds&#8217; nine seconds from now.&#8221; Makes sense, right? However, the following <i>doesn&#8217;t</i> work:



</p>

<pre class="brush: js"> function doDumbTimer()

 {

    var timer1 = setTimeout("window.document.the_form.the_text.value='3 seconds!';",3000);

    var timer2 = setTimeout("window.document.the_form.the_text.value='6 seconds!';",3000);

    var timer3 = setTimeout("window.document.the_form.the_text.value='9 seconds!';",3000);

 }

 </pre>

<p>See what happens when you try this <a href="http://www.wired.com/wired/webmonkey/stuff/advanced_js_tutorial_files/dumb_timer.html" class="external text" title="http://www.wired.com/wired/webmonkey/stuff/advanced_js_tutorial_files/dumb_timer.html" rel="nofollow">faulty timer code</a>? Notice that if you wait three seconds, one of the three timing messages mysteriously appears in the text box and then just stays there. In the bad code above, each of the <code>setTimeouts</code> get executed consecutively, (i.e., it&#8217;s saying, &#8220;write &#8217;3 seconds&#8217; three seconds from now, &#8217;6 seconds&#8217; three seconds from now, and &#8217;9 seconds&#8217; three seconds from now&#8221;). So after three seconds pass, all three things happen, and you end up with whichever one happens to fire last &#8211; definitely not what you want.Once you understand it, <code>setTimeout()</code> is quite easy to use. However, one thorny question does arise:How can you make a timer that does something every <i>two</i> seconds, from now until forever? For example:

</p><p><a href="http://www.wired.com/wired/webmonkey/stuff/advanced_js_tutorial_files/timer.html" class="external text" title="http://www.wired.com/wired/webmonkey/stuff/advanced_js_tutorial_files/timer.html" rel="nofollow">Click here</a>.



</p><p>Don&#8217;t worry about the stop timer button for now, I&#8217;ll cover <code>clearTimeouts</code> in a bit. Just think about how you would get this timer to loop indefinitely. It&#8217;s actually a very important question, and not just a silly exercise. As I mentioned earlier, when you want to make stuff move slowly across the screen using dynamic HTML, execute a small timed loop: &#8220;Move it over a little, wait, move it more, wait &#8230; and so on.&#8221; Are you thinking about it? Well, the answer&#8217;s not an easy one. You can&#8217;t just have a function, like the one above, that changes the text box every two seconds, like so:

</p>

<pre class="brush: js"> function theTimer()

 {

    var timer1 = setTimeout("changeTextBoxTo(2);",2000);

    var timer2 = setTimeout("changeTextBoxTo(4);",4000);

    var timer3 = setTimeout("changeTextBoxTo(6);",6000);

    var timer4 = setTimeout("changeTextBoxTo(8);",8000);

    var timer5 = setTimeout("changeTextBoxTo(10);",10000);

    .

    .

    .



 }

 </pre>

<p>Because, well, you can see why not: If you want something to loop infinitely, and you used this method, you&#8217;d have to have infinite lines of code. Among other problems, like serious carpal tunnel syndrome, it would take a really long time to download a page with an never-ending number of JavaScript lines, so that&#8217;s not really an option. This doesn&#8217;t work either, even though it looks sort of cool:

</p>

 <pre class="brush: js"> function theTimer()

 {

 	the_time = 0;

 	hellIsHot = true;



 	while (hellIsHot == true)

 	{

 	  the_time += 2;

 	  var timer = setTimeout("changeTextBoxTo(the_time);", the_time*1000);

 	}



 }

 </pre>

<p>Study this thing for a while to see what I&#8217;m getting at. But <i>don&#8217;t</i> try running it. The results will make you very unhappy. Let&#8217;s do a few iterations of the &#8220;while&#8221; loop:



</p>

<dl><dt> Iteration 1</dt><dd>

<ul><li> while (hellIsHot == true)&nbsp;:Yup, hell sure is hot.

</li><li> the_time += 2&nbsp;:so now the_time = 2

</li><li> var time = setTimeout(&#8220;changeTextBoxTo(2);&#8221;, 2000)&nbsp;:so, two seconds from now, the textbox will change to &#8220;2.&#8221; That&#8217;s what we want.

</li></ul>

</dd></dl>

<dl><dt> Iteration 2</dt><dd>



<ul><li> while (hellIsHot == true)&nbsp;:Verily, hell is still hot.

</li><li> the_time += 2&nbsp;:so now the_time = 4

</li><li> var time = setTimeout(&#8220;changeTextBoxTo(4);&#8221;, 4000)&nbsp;:so, four seconds from now, the textbox will change to &#8220;4.&#8221; OK, that&#8217;s good.

</li></ul>

</dd></dl>

<dl><dt> Iteration 3</dt><dd>

<ul><li> while (hellIsHot == true)&nbsp;:Nope, hell isn&#8217;t getting any colder.



</li><li> the_time += 2&nbsp;:so now the_time = 6

</li><li> var time = setTimeout(&#8220;changeTextBoxTo(6);&#8221;, 6000)&nbsp;:so, six seconds from now, the textbox will change to &#8220;6.&#8221; Fine.

</li></ul>

</dd></dl>

<dl><dt> Iteration 4</dt><dd>

<ul><li> while (hellIsHot == true)&nbsp;:OK already! It&#8217;s hot!

</li><li> yadda

</li><li> yadda yadda



</li></ul>

</dd></dl>

<p>You get the picture. It looks like this code should do the right thing. Unfortunately, it doesn&#8217;t. Instead it creates this unending loop, scheduling <code>setTimeouts</code> until hell freezes over. There are two problems here. First, while it&#8217;s in the loop, your browser can&#8217;t do anything else. It&#8217;ll basically freeze, spinning its wheels, scheduling <code>setTimeouts</code> forever. Second, every time a <code>setTimeout</code> is scheduled, the browser has to remember what you&#8217;re scheduling and when you want it to run. Eventually your browser will run out of memory. When this happens, your browser will crash, or your computer will crash, or you&#8217;ll get mad and never write another line of JavaScript again. Not good at all. Fortunately, there <i>is</i> a way to write a successful looping timer.

</p>

<a name="Timing_Loops_-_How_to_Do_Them"></a><h4> <span class="mw-headline">Timing Loops &#8211; How to Do Them</span></h4>



<p>To get a timer working in a loop, you have to write a function that calls itself. Happily, this is possible in JavaScript. Here&#8217;s an example:

</p>

<pre class="brush: js"> var the_count = 0;

 var the_timeout;

 function doTimer()

 {

 	window.document.timer_form.the_text.value = the_count;

 	the_count += 2;

 	the_timeout = setTimeout("doTimer();", 2000);

 }

</pre>

<p>This is the timer that was used on the previous page. When a user clicks on the button, it calls this function, which in turn writes the current value of <code>the_count</code> to the textbox. It then increments <code>the_count</code> by two, and then calls itself in a <code>setTimeout</code>. In two seconds, the <code>setTimeout</code> is executed, cleared, and the function runs again. It changes the value in the textbox, increments <code>the_count</code>, and again uses <code>setTimeout</code> to call itself in two seconds. During those two seconds, the browser just sits around, doing the things that browsers do. When two seconds pass, the function runs again. And another <code>setTimeout()</code> is set once <code>the_count</code> is incremented by two. You don&#8217;t run out of memory because there&#8217;s only one <code>setTimeout()</code> running at any given time.



</p><p>This works, whereas the infinite hell-freezing-over loop on the last page didn&#8217;t, because infinite &#8220;while&#8221; loops lock the browser up and prevent anything from happening during the execution of the loop. This <code>setTimeout</code> trick makes sort of a slow loop. In the above example, the browser has two seconds to do things between each iteration.

</p>

<a name="How_to_Cancel_a_setTimeout"></a><h3> <span class="mw-headline">How to Cancel a <code>setTimeout</code></span></h3>

<p>Now that you know how to make a timer loop run infinitely, you&#8217;ll probably want to know how to stop it. This is the magic of <code>clearTimeout</code>. If you look at the HTML of the timer on the previous page, you&#8217;ll see the following form element:

</p>

<pre class="brush: js"> &lt;input type="button" value="stop timer"

  onClick="clearTimeout(the_timeout);"&gt;

</pre>



<p>This is the button you hit to stop the timer. The command to stop a <code>setTimeout</code> is <code>clearTimeout()</code>, which is actually quite simple. When you set a <code>setTimeout</code> like this,

</p>

<pre class="brush: js"> the_timeout = setTimeout("some javascript",3000);

</pre>

<p>you can cancel it like this:

</p>

<pre class="brush: js"> clearTimeout(the_timeout);



</pre>

<p>Simple, no? Now let&#8217;s take a look at a slightly more complicated looping timer:one that actually tells time!

</p>

<a name="A_JavaScript_Clock"></a><h4> <span class="mw-headline">A JavaScript Clock</span></h4>

<p><a href="http://www.wired.com/wired/webmonkey/stuff/advanced_js_tutorial_files/clock.html" class="external text" title="http://www.wired.com/wired/webmonkey/stuff/advanced_js_tutorial_files/clock.html" rel="nofollow">Click here</a>

</p><p>This clock reads the time off your computer and then updates the textbox every half second. I&#8217;m showing you this for two reasons. First, it&#8217;s another example of making a timer by having a function call itself. Second, it shows you a little more about the Date object, which I mentioned back when we covered cookies.

</p><p>Here&#8217;s the code:

</p>

<pre class="brush: js"> function writeTime() {



   // get a date object

   var today = new Date();



   // ask the object for some information

   var hours = today.getHours();

   var minutes = today.getMinutes();

   var seconds = today.getSeconds();



   // fixTime makes the minutes and seconds look right

   // it just sticks a zero in front of numbers less than 10

   minutes = fixTime(minutes);

   seconds = fixTime(seconds);



   // put together the time string and write it out

   var the_time = hours + ":" + minutes + ":" + seconds;

   window.document.the_form.the_text.value = the_time;



   // run this function again in half a second

   the_timeout= setTimeout('writeTime();',500);



 }



 function fixTime(the_time) {



 	if (the_time &lt;10)

 	{

 		the_time = "0" + the_time;

 	}

 	return the_time;

 }

</pre>

<p>It might look a little long, but that&#8217;s just because it&#8217;s well commented. Let&#8217;s go through the code line by line.

</p>



<dl><dt> <code>var today = new Date();</code>

</dt><dd>Just as <code>new Array()</code> creates a new Array object for you to fill, <code>new Date()</code> creates a new Date object. Once you have the object, you can ask it questions about itself. When you create a Date object with nothing between the parentheses, as we&#8217;ve done, JavaScript looks at the computer&#8217;s clock and uses it to create a new Date object. Now that we have a Date object, called &#8220;today,&#8221; we can get information from it.

</dd><dt> <code>var hours = today.getHours();</code>

</dt><dd>This is how to get the current hour. It&#8217;s military time, so if it&#8217;s 2 p.m. when you get the <code>new Date()</code>, <code>getHours()</code> will return &#8220;14.&#8221; Understand that <code>getHours()</code> is a built-in method call of the JavaScript Date object. As is the case with most JavaScript objects, the way to know when you should use <code>getHours</code> is by checking with a good JavaScript reference book.



</dd><dt> <code>var minutes = today.getMinutes(); var seconds = today.getSeconds();</code>

</dt><dd>These lines are just like <code>getHours();</code>.

</dd><dt> <code>minutes = fixTime(minutes);</code>

</dt><dd>One problem with <code>getMinutes</code> is that if it&#8217;s 11:01, <code>getMinutes</code> will return a &#8220;1.&#8221; This is fine unless you want to make a clock like we do, in which case, we want the &#8220;1&#8243; to be written as &#8220;01.&#8221; That&#8217;s what the <code>fixTime</code> function that I wrote does. It&#8217;s a pretty straightforward function, so I&#8217;m not going to describe it. Just take a quick look at it to see what it&#8217;s doing.



</dd><dt> The next two lines put the string together and write it to the form element.

</dt><dd>We&#8217;ve seen this sort of nonsense a million times.

</dd><dt> <code>the_timeout = setTimeout('writeTime();', 500);</code>

</dt><dd>This is the line that makes the loop. It says &#8220;in half a second, call the function again.&#8221; When the function gets called again, it does another <code>today = new Date()</code>, which sends it to the computer&#8217;s clock again. The interval could have been every second, but doing it every half second helps keep the time more accurate.

</dd></dl>

<p>OK, enough of the looping timer trick. There&#8217;s one more thing you should know about timers:how to use them with variables.

</p>

<a name="Using_Timers_with_Variables"></a><h4> <span class="mw-headline">Using Timers with Variables</span></h4>

<p>Like I mentioned earlier, setting a <code>setTimeout</code> is like marking a time in the future for JavaScript to execute a statement. This is fine and dandy when your <code>setTimeout</code> is something like this:



</p>

<pre class="brush: js"> var the_timeout = setTimeout("alert('Hello!');", 60000);

</pre>

<p>Here you&#8217;re telling JavaScript to wait one minute and then throw up a &#8220;Hello!&#8221; alert box. But what if you want to do something like this:

</p>

<pre class="brush: js"> var the_string = "hello";

 var the_timeout = setTimeout("alert(the_string);", 60000);

</pre>

<p>This tells JavaScript to wait one minute and throw up an alert box that contains whatever variable provided by <code>the_string</code>. So after a minute, JavaScript looks for a variable called <code>the_string</code> and calls <code>alert()</code> with that variable. The problem? In a minute&#8217;s time, <code>the_string</code> might contain something totally different from &#8220;Hello!&#8221; In fact, if you had the above two lines of JavaScript inside a function, the <code>setTimeout</code> would probably give you an error. For instance, if you had a function like this:



</p>

<pre class="brush: js"> function alertInAMinute()

 {

     var the_string = "hello";

     var the_timeout = setTimeout("alert(the_string);", 60000);

 }

</pre>

<p>And then you called the function inside a link like so:

</p>

<pre class="brush: js"> &lt;a href="#" onClick="alertInAMinute(); return false;"&gt;blah!&lt;/a&gt;

</pre>

<p>This would probably produce an error because you defined the variable called <code>the_string</code> inside the function using <code>var</code>. Remember:When you use <code>var</code> inside a function, as far as JavaScript is concerned, it exists only inside that function. This function creates a variable called <code>the_string</code>, sets the <code>setTimeout</code>, then exits. Because you used <code>var</code>, the variable called <code>the_string</code> is erased from JavaScript&#8217;s memory. And then, when JavaScript looks for <code>the_string</code> in its memory a moment later, it&#8217;s nowhere to be found, and you are dished up an error.



</p><p>This problem occurs because you&#8217;re passing a variable to <code>setTimeout</code>. Eliminate the problem by passing it the <i>value</i> of the variable instead of the variable itself. Here&#8217;s how:

</p>

<pre class="brush: js"> function alertInAMinute()

 {

     var the_string = "hello";

     var the_timeout = setTimeout("alert(" + the_string + ");",60000);

 }

</pre>

<p>This code pulls the <code>the_string</code> variable out from inside the quotes of <code>setTimeout</code>. And because the variable isn&#8217;t in quotes, JavaScript puts in the value of the variable.

</p><p>You may be asking why I bothered with a variable in the first place. Well, I&#8217;m simplifying things to make a point. When you tackle today&#8217;s homework, you&#8217;ll see where this really makes a difference.



</p><p>OK, enough of timers. As I said earlier, timers are used all over the place in dynamic HTML, so they&#8217;re worth learning. But don&#8217;t get too swept up in multimedia merriment &#8211; to make all this safe for the teeming millions who can&#8217;t see dynamic HTML, you need to know how to detect what browsers your visitors are using.

</p>

<a name="Browser_Detection"></a><h4> <span class="mw-headline">Browser Detection</span></h4>

<p><font color="RED">This section (obviously) needs to be updated.</font>

</p><p>Almost everything I&#8217;ve covered so far works on all JavaScript-enabled browsers. However, there are some things that just don&#8217;t fly on certain browsers. MSIE 3.0, for one, doesn&#8217;t support image swapping. So if you have a page that depends on image swapping to function correctly, either you nix the image swapping altogether, or you furnish MSIE 3.0 visitors with information tailor-made for their browser.

</p><p>There are a few approaches to dealing with browsers with different capabilities. The most straightforward method is to determine what browser someone is using and then serve up the appropriate browser-specific information.

</p><p>There are several ways to do this. Some sites ask you to choose which browser you&#8217;re using right up front; e.g., &#8220;Click here if you&#8217;re using Netscape.&#8221; But this isn&#8217;t an ideal solution for a number of reasons. For one thing, it&#8217;s a hassle for the user (and, with impatient users, that extra click may mean the difference between staying or backing out). It also means that you have to maintain duplicate (or maybe even more) versions of the same pages.

</p><p>An alternative is to use JavaScript to figure out what browser someone is using, and automatically route the visitor to a set of pages that works for that browser. Unfortunately, this still forces you to maintain two or more versions of each page, which is really a drag.

</p><p>A much better solution is to make your pages smart enough to look one way to some browsers and another way to other browsers (which is what we&#8217;ll concentrate on for the rest of today&#8217;s lesson).

</p>

<a name="How_to_Detect_Browsers"></a><h4> <span class="mw-headline">How to Detect Browsers</span></h4>

<p><font color="RED">This section (obviously) needs to be updated.</font>



</p><p>Along with the Document object, each browser window has a Navigator object, which has two properties containing all the information about the sort of browser you&#8217;re using. These are <code>appName</code> and <code>appVersion</code>.

</p><p>The application name is <code>appName</code>. If you&#8217;re using a version of Netscape, and you have this line in your JavaScript:

</p>

<pre class="brush: js"> var the_browser_name = navigator.appName;

</pre>

<p>Then <code>the_browser_name</code> will be &#8220;Netscape.&#8221; For MSIE, <code>the_browser_name</code> would be &#8220;Microsoft Internet Explorer&#8221; (each browser company comes up with its own name). So, if you just want to know whether someone&#8217;s using Netscape or MSIE, use <code>appName</code>.



</p><p>More information is stored in the <code>appVersion</code>. A sample <code>appVersion</code> is &#8220;4.03 [en] (Win95; I),&#8221; which is the browser I&#8217;m using as I type this very tutorial. It&#8217;s Netscape version 4.03, English International, for Win95/NT. Whatever. Beyond the version number, you probably won&#8217;t need all that information. Happily, getting the version number out of this monster string is quite easy:You just grab the first number. The quickest way to do this is with a function called <code>parseFloat()</code>, which pulls the first thing that looks like a decimal number out of the string and returns it:

</p>

<pre class="brush: js"> var the_browser_version = navigator.appVersion;

 var the_version_number = parseFloat(the_browser_version);

</pre>

<p>Unfortunately, this little trick won&#8217;t work for Internet Explorer 5.0 or later because Microsoft decided to start their appVersion string with the numbers 4.0. Why did they do this? To irk us all! Luckily, except for some crazy IE5 specific stuff, JavaScript is the same in IE5 and IE4, so in general it&#8217;s ok for your scripts to be a bit misinformed. If you REALLY want to be sure you know what browser someone is using, refer to Dr. Richard Blaylock&#8217;s <a href="/2010/02/Detect_Which_Browsers_Are_Visiting_Your_Site" title="Tutorial:Detect Which Browsers Are Visiting Your Site">browser detector library</a>.

</p><p>OK, let&#8217;s do something useful with this information. Click the button below to see an incredibly straightforward use of the Navigator object.

</p><p>Here are the two relevant functions. Clicking on the button calls <code>browserSizeUp()</code>:



</p>

<pre class="brush: js"> function browserSizeUp()



 {

    var browser = navigator.appName;

    var version = versionNumber();



    if ((browser == "Netscape" ||

         browser == "Microsoft Internet Explorer") &amp;&amp; (version &gt;= 4))



    {

    alert("The browser doctor says:Now that's a pretty fancy browser

           you got there!");



    } else {



    alert("The browser doctor says:Hmm. Maybe it's time to upgrade.");



    }



 }



 function versionNumber() {



   // return version number (e.g., 4.03)



   return parseFloat(navigator.appVersion)

 }

</pre>

<p>What&#8217;s happening? If we like the user&#8217;s browser, we give one alert. We dish up a different alert if we think he or she needs to get modern. In a real-life application, you&#8217;d use <code>document.writeln()</code> to generate HTML that&#8217;s suitable for different browsers.

</p><p>What users see depends on which browser their using. Unfortunately, with all the different browsers, browser versions, and platforms out there, it&#8217;s nearly impossible to keep track of which browsers support what features. And it&#8217;s only going to get worse as the number of browsers grows and the number of features you have to keep track of continues to increase.

</p><p>Luckily, there&#8217;s a way to preserve your sanity. Read on and learn about object and method detection.

</p>

<a name="Object_and_Method_Detection"></a><h4> <span class="mw-headline">Object and Method Detection</span></h4>



<p>Ultimately, your best approach is to determine what feature you need for any given bit of JavaScript code, and then make sure that the browser has that feature.

</p><p>For example, we know that some browsers can do image swaps and others can&#8217;t. Good thing this ability is easy to detect:just make sure that the browser has the <code>document.images object</code>:

</p>

<pre class="brush: js"> if (document.images)

 {

 	do lots of image swap stuff

 }

</pre>

<p>This makes sure that your image-swap code will be run only by browsers that support image swaps. If the <code>document.images</code> object doesn&#8217;t exist, the <code>if</code> test fails and the code doesn&#8217;t run.

</p><p>This sort of trick works for methods and functions, too. Not all browsers have every method. For example, in Netscape 4 you can actually move windows around the screen using the <code>window.moveTo()</code> method. If you want to check to see if that method exists before you invoke it, do this:



</p>

<pre class="brush: js">

 if (window.moveTo)

 {

 	make that window fly

 }



</pre>

<p>By making sure the browser supports the feature you want to use before you invoke it, you ensure that your script will work without any obnoxious script errors. By employing a feature-checking strategy, rather than a browser-checking one, you don&#8217;t have to keep track of the capabilities of every browser in every version on every platform.

</p><p>OK, that&#8217;s all about browser detection. But while we&#8217;re on the topic of browsers, let&#8217;s take a look at another browser-centered object: the History object.

</p><p>If you look at the JavaScript Object Hierarchy, you&#8217;ll see we&#8217;ve touched on all but two of the top-level objects: Packages and History. Packages will have to wait for a Java tutorial, but History is JavaScript specific and very useful.

</p><p>History contains the list of URLs that your browser has visited. Every browser has a way to call up a list of the pages you&#8217;ve visited recently. Clicking and holding down on your browsers back button generally does the trick. The History object lets you jump backward and forward in this list using the <code> window.history.back()</code> and <code>window.history.forward()</code> methods. The back link should act just like the back button on your browser.

</p><p>These two methods are most useful inside frames, where the browser&#8217;s back button tends to take you to unexpected pages. It also makes a good addition to our ever-growing Webmonkey browser, which (surprise, surprise) is part of today&#8217;s homework. But first, let&#8217;s review. Today we covered two things that will help you move from old-tyme static HTML to the newfangled world of dynamic HTML: timing events and methods of dealing with browser incompatibilities.  With the JavaScript you know now, learning dynamic HTML will be a snap.



</p><p>Tomorrow, we&#8217;ll end our coverage of JavaScript objects and syntax. But don&#8217;t be too sad &#8212; this isn&#8217;t the end but the beginning. <i>True</i> JavaScript knowledge comes only from extensive practice and hacking. By the end of tomorrow, you&#8217;ll be ready to confidently head out into the wild world of JavaScript to hone your skills with endless coding.

</p><p>We&#8217;ll also cover the finer points of the use of JavaScript with images, including JavaScript in client-side image maps and preloading images to make your image swaps work quickly (or just <i>work</i>). After that, we&#8217;ll take a long excursion into the world of object-oriented programming. You know about Date objects and Window objects already. Tomorrow we&#8217;ll learn how to create our own objects and how to access and control them in several different ways.

</p><p>Before going onto the <a href="/2010/02/Advanced_JavaScript_Tutorial_-_Lesson_4" title="Tutorial:Advanced JavaScript Tutorial - Lesson 4">Next</a>, you might want to try <a href="http://www.wired.com/wired/webmonkey/stuff/advanced_js_tutorial_files/AJST_homework3.html" class="external text" title="http://www.wired.com/wired/webmonkey/stuff/advanced_js_tutorial_files/AJST_homework3.html" rel="nofollow">this homework assignment</a> to solidify your understanding of the JavaScript objects we already know.

</p><div id='linker_widget' class='contextly-widget'></div>]]></content:encoded>
            <wfw:commentRss>http://www.webmonkey.com/2010/02/advanced_javascript_tutorial_-_lesson_3/feed/</wfw:commentRss>
        <slash:comments>1</slash:comments>

        
    </item>
    
    <item>
        <title>Advanced JavaScript Tutorial &#8211; Lesson 4</title>
        <link>http://www.webmonkey.com/2010/02/advanced_javascript_tutorial_-_lesson_4/</link>
        <comments>http://www.webmonkey.com/2010/02/advanced_javascript_tutorial_-_lesson_4/#comments</comments>
        <pubDate>Tue, 16 Feb 2010 01:45:47 +0000</pubDate>

                <dc:creator>Webmonkey Staff</dc:creator>

        <guid isPermaLink="false">http://stag.wired.com/primate/?p=725</guid>
        		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[thau]]></category>
		<category><![CDATA[wiki]]></category>
        <description><![CDATA[In the previous lesson, we looked at the many different things you can do with text and strings. Today we&#8217;ll focus on two different types of data:images and objects. By the end of this lesson, you&#8217;ll know how to: Use image maps with JavaScript Preload images to speed up your image swaps Create your own [...]]]></description>

            <content:encoded><![CDATA[<!-- wpautop disabled --><p>In the previous lesson, we looked at the many different things you can do with text and strings. Today we&#8217;ll focus on two different types of data:images and objects. By the end of this lesson, you&#8217;ll know how to:

</p>
<ul><li> Use image maps with JavaScript
</li><li> Preload images to speed up your image swaps
</li><li> Create your own objects to make big scripts comprehensible
</li><li> Use associative arrays to rapidly access all the objects in your scripts
</li></ul>
<p>We&#8217;ll get the ball rolling with image maps.
</p>
<br />
<span id="more-725"></span>
<table id="toc" class="toc" summary="Contents"><tbody><tr><td><div id="toctitle"><h2>Contents</h2> </div>

<ol>

<li><a href="#Image_Maps_and_JavaScript">Image Maps and JavaScript</a></li>

<li><a href="#Preloading_Images_-_What.27s_It_All_About.3F">Preloading Images &#8211; What&#8217;s It All About?</a></li>



<li><a href="#Preloading_Images_-_How.27s_It_Done.3F">Preloading Images &#8211; How&#8217;s It Done?</a></li>

<li><a href="#Object_Advantage">Object Advantage</a></li>

<li><a href="#Creating_Your_Own_Objects">Creating Your Own Objects</a></li>

<li><a href="#Your_Object-Oriented_Virtual_Pet">Your Object-Oriented Virtual Pet</a></li>

<li><a href="#Evaluating_Strings">Evaluating Strings</a></li>



<li><a href="#Getting_at_Hard-to-Reach_Objects">Getting at Hard-to-Reach Objects</a></li>

<li><a href="#Another_Way_to_Get_at_Hard-to-Reach_Objects">Another Way to Get at Hard-to-Reach Objects</a></li>

<li><a href="#Lesson_4_Review">Lesson 4 Review</a></li>

</ol>

</td></tr></tbody></table>



<a name="Image_Maps_and_JavaScript"></a><h4> <span class="mw-headline">Image Maps and JavaScript</span></h4>



<p>An image map is made up of regions, and each region has an associated hyperlink. Clicking on one area takes you to the associated link. Here&#8217;s a basic example, swiped (and slightly modified) from Patrick Corcoran&#8217;s image-map tutorial.

</p><p><a href="http://www.wired.com/wired/webmonkey/stuff/advanced_js_tutorial_files/imagemap1.html" class="external text" title="http://www.wired.com/wired/webmonkey/stuff/advanced_js_tutorial_files/imagemap1.html" rel="nofollow">Click here</a>.

</p><p>Though this is one single image, Patrick has designated areas of the image to link to different HREFs. You see image maps like this all over the place, most frequently as a navigational element.  As a quick review, here&#8217;s the HTML for the image map above. (I should note that the image tag in this example is broken up into multiple lines so that it displays correctly on this page. The real link is one big line. OK? OK.)

</p>

<pre class="brush: js"> &lt;img src="http://www.wired.com/wired/webmonkey/stuff/my_image_image_maps.gif" border=0

 WIDTH=160 HEIGHT=140 ismap usemap="#foo"&gt;



 &lt;map name="foo"&gt;

 &lt;area name="yellow" href="http://www.webmonkey.com/" coords="20,20,70,60"&gt;

 &lt;area name="red" href="http://www.hits.org/" coords="90,20,140,60"&gt;



 &lt;area name="blue" href="http://www.hotwired.com/surf/central/" coords="20,80,70,120"&gt;

 &lt;area name="green" href="http://www.animationexpress.com" coords="90,80,140,120"&gt;

 &lt;/map&gt;

</pre>

<p>Notice that the &lt;img src&gt; tag has an element that says <code>usemap="#foo"</code>. This tells the image to look for a map tag named &#8220;foo&#8221; and apply that map to the image. The map can go anywhere on the page, but it&#8217;s generally a good idea to put the map near the image, just like you see here, so that it is easy for you to find and edit. The map has a &#8220;begin&#8221; and &#8220;end&#8221; tag, with a bunch of area tags in between. Each area tag defines a region using the <code>coords element</code> and assigns that region an HREF. The coords element is a string of numbers, each representing a pixel in the image. When defining a square, the pixels should be listed in this order:top left, top right, bottom left, bottom right.  Adding JavaScript to these image maps is as easy as adding it to an HREF. In fact, JavaScript treats area tags almost exactly like it does HREFs. You can stick <code>onClicks</code>, <code>onMouseOvers</code>, and <code>onMouseOuts</code> in the area tag, and they will do what you expect.



</p><p>Here&#8217;s the above example, with a little JavaScript added:

</p><p><a href="http://www.wired.com/wired/webmonkey/stuff/advanced_js_tutorial_files/area_maps.html" class="external text" title="http://www.wired.com/wired/webmonkey/stuff/advanced_js_tutorial_files/area_maps.html" rel="nofollow">Click here</a>.

</p><p>The new JavaScript-enhanced map looks like this:

</p>

<pre class="brush: js">

 &lt;map name="javascript_foo"&gt;

 &lt;area name="yellow" href="http://www.webmonkey.com/"

    onMouseOver="writeInForm('All Hail Webmonkey!');" coords="20,20,70,60"&gt;



 &lt;area name="red" href="http://www.hits.org/"

    onMouseOver="writeInForm('Humboldt Institute of Technological Studies');" coords="90,20,140,60"&gt;



 &lt;area name="blue" href="http://www.hotwired.com/surf/central/"

    onMouseOver="writeInForm('The good, the bad, and the utterly useless');" coords="20,80,70,120"&gt;



 &lt;area name="green" href="http://www.animationexpress.com"

    onMouseOver="writeInForm('The real animaniacs');" coords="90,80,140,120"&gt;



 &lt;/map&gt;

</pre>

<p>It&#8217;s pretty much the same as the original; the only difference is that inside each &lt;area&gt; tag there&#8217;s an <code>onMouseOver</code> that calls a function that I wrote, called <code>writeInForm()</code>, which looks like this:



</p>

<pre class="brush: js"> &lt;script language="JavaScript"&gt;

 &lt;!-- hide me



 function writeInForm(text_to_write)

 {

     window.document.the_form.the_text.value= text_to_write;

 }



 // show me --&gt;

 &lt;/script&gt;

</pre>

<p>Simple, eh? For something a little more complicated, let&#8217;s learn how to preload images using JavaScript.

</p>

<a name="Preloading_Images_-_What.27s_It_All_About.3F"></a><h4> <span class="mw-headline">Preloading Images &#8211; What&#8217;s It All About?</span></h4>

<p>One of the main problems with image swaps is that JavaScript will only tell the browser to download an image when it needs it for a swap. If you have a big image, and you swap in another on a mouseover, the browser has to download the new image. That can take awhile and ruin the fluid rollover effect you&#8217;re shooting for. To see what I&#8217;m talking about, <a href="http://www.wired.com/wired/webmonkey/stuff/advanced_js_tutorial_files/image_swapping.html" class="external text" title="http://www.wired.com/wired/webmonkey/stuff/advanced_js_tutorial_files/image_swapping.html" rel="nofollow">click here</a>.



</p><p>If you have a slow connection, you will have to wait for a fairly large image to load after you do the mouseover. Since some browsers won&#8217;t swap in an image if it&#8217;s not stored in the cache, you may not see any image swapping at all. In order to avoid these nasty problems, preload the images when the page first loads.

</p>

<a name="Preloading_Images_-_How.27s_It_Done.3F"></a><h4> <span class="mw-headline">Preloading Images &#8211; How&#8217;s It Done?</span></h4>

<p>It&#8217;s not terribly hard to preload your images. All you have to do is create a new Image object, then assign the image to preload to the src of that image Just like so:

</p>

<pre class="brush: js"> var an_image = new Image();

 an_image.src = "my_nice_image.gif";

</pre>

<p>Setting the .src of the new image automatically downloads the image to the user&#8217;s hard drive, assuming, of course, the cache is turned on. The image is read off the hard drive, instead of downloaded. Try mousing over the links below. The image swap should happen pretty quickly.

</p><p><a href="http://www.wired.com/wired/webmonkey/stuff/advanced_js_tutorial_files/image_swapping2.html" class="external text" title="http://www.wired.com/wired/webmonkey/stuff/advanced_js_tutorial_files/image_swapping2.html" rel="nofollow">Click here</a>.

</p><p>The only thing left is to learn how to make the preload happen when the page first loads in the browser, before any rollover action. Happily, this is pretty straightforward. The body tag has an event handler called <code>onLoad</code>, which is called once a page finishes loading. If you have a body tag that looks like this:

</p>



<pre class="brush: js"> &lt;body onLoad="doPreload();"&gt;

</pre>

<pre class="brush: js">The <code>doPreload()</code> function will be called when the page is done loading. The code for the functions that do the loading looks like this:

</pre>

<pre class="brush: js"> function doPreload()

 {



    var the_images = new Array('stuff3a/kwmatt.jpg','stuff3a/matbon.jpg',

    'stuff3a/lunchMat.jpg');

    preloadImages(the_images);

 }



 function preloadImages(the_images_array) {



    for(var loop = 0; loop &lt; the_images_array.length; loop++)



    {

  	var an_image = new Image();

 	an_image.src = the_images_array[loop];

    }

 }

</pre>

<p>Because I put that <code>onLoad</code> event handler in the body tag, the function <code>doPreload()</code> gets called when the page finishes loading. <code>doPreload()</code> creates an array of the names of images to preload and passes that array to <code>preloadImages()</code>, which loops through the array. With each pass through the loop, it creates a new Image object and assigns an image to the src of that image object. Not too hard, hmm? That Image object is pretty useful, right? I&#8217;m glad you think so, because now it&#8217;s time to move on to some mind-blowing &#8211; and trickier &#8211; things. Take a break now, because on the next page we&#8217;re going to enter the wide world of object creation.



</p>

<a name="Object_Advantage"></a><h4> <span class="mw-headline">Object Advantage</span></h4>

<p>We&#8217;ve seen plenty of examples of JavaScript&#8217;s built-in objects and how they&#8217;re used:Window, Image, Document, Form, and a bevy of other objects. Remember:An object is just a special kind of data, made up of properties and methods. Properties are the things that an object knows about itself, while methods are the things that the object knows how to do.

</p><p>For example, the Window object in JavaScript has properties, like <code>window.status</code>, which can be read and set. By setting the status property of the Window object to a string, it makes that string appear in the window&#8217;s status bar. Window also has methods, like <code>window.focus()</code>, which brings a window forward. If this stuff is unfamiliar to you, you should probably read <a href="/2010/02/JavaScript_Tutorial_-_Lesson_5" title="Tutorial:JavaScript Tutorial - Lesson 5">Part I, Day 5</a>  for more details.

</p><p>Objects provide a great way to organize information. First, we deal with real-life objects all the time. A monkey, for example, is an object. Its properties include height, weight, furriness, and sassiness. All monkeys have the same set of properties. It&#8217;s the <i>values</i> of those properties that makes one monkey different from another. Monkeys also have methods, or things they do, like <code>play()</code>, <code>eat()</code>, <code>sleep()</code>.



</p><p>Objects are also handy because they allow you to preserve the &#8220;sense&#8221; of words. Take the notion of <code>focus()</code> in JavaScript, for example. <code>Focus()</code>, appropriately enough, brings things into focus. When <code>focus()</code> is applied to a window, it brings the window forward. Blur does the reverse &#8211; try it.

</p><p><a href="http://www.wired.com/wired/webmonkey/stuff/advanced_js_tutorial_files/focus.html" class="external text" title="http://www.wired.com/wired/webmonkey/stuff/advanced_js_tutorial_files/focus.html" rel="nofollow">Click here</a>.

</p><p>However, when you apply <code>focus()</code> to a text box, it puts a typing cursor inside the box.

</p><p><a href="http://www.wired.com/wired/webmonkey/stuff/advanced_js_tutorial_files/focus_form.html" class="external text" title="http://www.wired.com/wired/webmonkey/stuff/advanced_js_tutorial_files/focus_form.html" rel="nofollow">Click here</a>.



</p><p>Spooky, huh? JavaScript knows that focus does one thing for a window and something else for a textbox. The idea of focus is the same in both cases, so it makes sense to call it the same thing. But it also makes sense that <code>focus()</code> does slightly different things for two different objects. This notion of having one method name do different things for different objects is called &#8220;polymorphism,&#8221; and it&#8217;s fundamental to object-oriented programming.

</p><p>Just as you can have the same method do different things for different objects, you can also have the same property mean different things in different objects. The <code>length</code> property, for example, works for both strings and arrays. The <code>string.length</code> returns the length of a string, while <code>array.length</code> returns the number of things in the array. Both properties are called length, but they mean slightly different things in the context of different objects.

</p><p>Objects also make it easy to cut and paste code together. If you have a good library of objects, you can just copy an entire object and plunk it into whatever script you need. This is a lot harder when you don&#8217;t have your code organized into clear objects.

</p><p>Since objects are so handy, JavaScript gives you the ability to create your own.

</p>



<a name="Creating_Your_Own_Objects"></a><h4> <span class="mw-headline">Creating Your Own Objects</span></h4>

<p>Objects help you organize information in an easily understandable way. Let&#8217;s start with the frivolous example of constructing an employee database, then use the lessons we learn to tackle something far more complex and relevant to our lives: writing a JavaScript virtual pet.

</p><p>For the purposes of this exercise, let&#8217;s put aside all those issues concerning the objectification of the worker in modern capitalist society, and consider each employee as an object with a certain set of properties and methods. Each employee has a name, title, salary, birthday, address, and so on. Employees can be promoted, go on vacation, transferred, or put on kitchen duty. An object represents all of this information, and the employee object is like a template. Each employee has the same types of properties &#8211; an age, name, title &#8211; but the values of the properties differ from employee to employee. Joe is an employee with one age and title, Jane is an employee with another age and title. Both are employees, hence they have the same properties. It&#8217;s the values of those properties that differ between employees.

</p><p>To write your own object, you need to start with the template. In object-oriented programming, the template is called the object&#8217;s constructor. Once you have the template, you can create new instances of the object, like this:

</p>

<pre class="brush: js"> var fred = new Employee("Fred Flintstone", 33, "Surface Miner", 20000);

 var barney = new Employee("Barney Rubble", 33, "Slacker", 40000);

 var boss = new Employee("Mr. Slate",50, "CEO", 1000000);

</pre>

<p>After you&#8217;ve created these instances of the Employee object, you can do stuff like this:

</p>

<pre class="brush: js"> barney.promotion("Chief Slacker","10");

 fred.fired();

 boss.vacation(365);

</pre>

<p>If you want to promote Barney to Chief Slacker and give him a 10 percent raise, fire Fred, and note that the CEO is taking the year off.

</p><p>Of course you have to write the constructor and the method calls yourself. Start with just the properties. Here is the Employee constructor:



</p>

<pre class="brush: js"> function Employee(name, age, title, salary)

 {

 	this.name = name;

 	this.age = age;

 	this.title = title;

 	this.salary = salary;

 }

</pre>

<p>Notice that a constructor is just a function. Inside the function you need to assign things to <code>this.property_name</code>. We&#8217;re not just setting the age to 0, we&#8217;re setting <code>this.age</code> to 0. The same is true for <code>this.name</code>, <code>this.title</code>, etc.

</p><p>You can pass parameters into constructors. When we call the Employee constructor &#8230;

</p>

<pre class="brush: js"> var barney = new Employee("Barney Rubble", 33, "Slacker", 40000);



</pre>

<p>&#8230; and then in the Employee function &#8230;

</p>

<pre class="brush: js"> this.name = name;

</pre>

<p>&#8230; we&#8217;re setting the name of this employee to whatever we passed into the Employee constructor function.

</p><p>The reason for all the &#8220;this&#8221; stuff in the constructor is that you&#8217;re going to have more than one employee at a time. In order for your methods and constructor to work, <i>which</i> employee you&#8217;re dealing with must be clear. That&#8217;s what &#8220;this&#8221; is:the instance of the object at hand. Showing you methods might help make things more clear.

</p><p>Methods are just functions attached to objects. First, define the function, then assign the function to the object (inside the object&#8217;s constructor function). Take the <code>promotion()</code> method as an example:

</p>

<pre class="brush: js"> function promotion(new_title,percent_raise)

 {

 	var salary_increase = this.salary * percent_raise;

 	this.salary = this.salary + salary_increase;

 	this.title = new_title;

 }



</pre>

<p>This function calculates what the employee&#8217;s new salary should be and assigns that, along with the new title, to the employee. JavaScript knows <i>which</i> employee you&#8217;re talking about by using &#8220;this.&#8221; So if you write:

</p>

<pre class="brush: js"> barney.promotion("Chief Slacker",10);

</pre>

<p>Then &#8220;this&#8221; is Barney. It&#8217;s definitely a little weird and takes some time to get used to it. But once you start thinking in terms of objects, it soon becomes habit.

</p><p>The last step to building the object is to tie the method to the object. As I mentioned earlier, you do this inside the constructor. To tie the promotion method to the Employee object, you&#8217;d write the <code>promotion()</code> function, then add this to the constructor:

</p>

<pre class="brush: js"> this.promotion = promotion;



</pre>

<p>Here&#8217;s the Employee constructor with the promotion method added:

</p>

<pre class="brush: js"> function Employee(name, age, title, salary)

 {

 	this.name = name;

 	this.age = age;

 	this.title = title;

 	this.salary = salary;



 	this.promotion = promotion;

 }



 function promotion(new_title,percent_raise)

 {

 	var salary_increase = this.salary * percent_raise;

 	this.salary = this.salary + salary_increase;

 	this.title = new_title;

 }

</pre>

<p>To add other information, say, the office in which an employee works, make a property named &#8220;office.&#8221; And then if you wanted to record a change in the employee&#8217;s venue, you&#8217;d create a method named <code>transfer()</code>.

</p><p>Got that? Now on to more complicated and important object-oriented JavaScript, like creating the virtual pet.

</p>

<a name="Your_Object-Oriented_Virtual_Pet"></a><h4> <span class="mw-headline">Your Object-Oriented Virtual Pet</span></h4>

<p>You are now the proud owner of not one, but two virtual pets. It&#8217;s your responsibility to keep them healthy. If their health drops below zero, they die. Let there be life by <a href="http://www.wired.com/wired/webmonkey/stuff/advanced_js_tutorial_files/virtual_pet.html" class="external text" title="http://www.wired.com/wired/webmonkey/stuff/advanced_js_tutorial_files/virtual_pet.html" rel="nofollow">clicking here</a>.



</p><p>As you&#8217;ve probably guessed, I&#8217;m a tad bitter about my inadequacies as a virtual pet owner. My poor pets die young every time. Anyway, this entire thing was programmed using objects. Each pet is an instantiation of a Pet object. Each pet has these properties:

</p>

<ul><li> health

</li><li> happiness

</li><li> hunger

</li><li> age

</li><li> pet_name

</li><li> form_number &#8211; the HTML form the pet lives in These properties are affected by the following methods:

</li><li> <code>play()</code> &#8211; increases happiness



</li><li> <code>feed()</code> &#8211; decreases hunger

</li><li> <code>medicate()</code> &#8211; increases health a little bit

</li><li> <code>makeOlder()</code> &#8211; makes the pet older

</li><li> <code>display()</code> &#8211; displays information about the pet in the status box So, with this in mind, let&#8217;s create a Pet object. The first thing we have to do is make a constructor. Here is the basic constructor (which we&#8217;ll create without the method calls for now):

</li></ul>



 <pre class="brush: js"> function Pet(pet_name, form_number)

{

	this.pet_name = pet_name;

	this.form_number = form_number;

	this.happiness = Math.random() * 5; //random number between 0 and 4.99.

	this.health = Math.random() * 5 + 2; // random number between 2 and 6.99

	this.display = display;

	this.age = 0;

	this.hunger = Math.random() * 5;

}

</pre>

<p>This constructor takes two parameters:the name of the pet and the position of the form in which that pet should be displayed. To create two pets, we do this:

</p>

<pre class="brush: js"> pet1 = new Pet(window.document.form_1.name_textfield.value, 0);

 pet2 = new Pet(window.document.form_2.name_textfield.value, 1);

</pre>

<p>The constructor is written to make each virtual pet different. It uses the <code>Math.random()</code> method to generate random numbers between zero and one. The <code>Math.random()</code> method isn&#8217;t perfectly random, but for our purposes it&#8217;s good enough, since it does allow us to give each pet a different initial hunger, health, and happiness. The name of the pet is set to whatever name gets passed to the constructor, and the pet&#8217;s age starts at zero. The last two lines set the number of the pet&#8217;s form and puts the name of the new pet into the appropriate textbox. Remember that the first form on a page can be referred to as <code>window.document.forms[0]</code>, the second form on a page is <code>window.document.forms[1]</code>, and so on. We have the properties; let&#8217;s work on the methods. Rather than outline each method, I&#8217;ll just show you a few of them to get you started:



</p><p><br />

</p>

 <pre class="brush: js"> function feed()

{

	var meal_quality = Math.random() * 2;

	this.hunger = this.hunger - meal_quality;

	if(this.hunger &lt; 0)

	{

		this.hunger = 0;

	}

	this.display();

}

</pre>

<p>This is the method used to feed the pet. If you execute the comment <code>pet1.feed()</code>, this method gets called. First, it generates a random number between zero and two. Then it subtracts this number from the hunger of the appropriate pet. We make sure that the hunger isn&#8217;t less than zero, and then we call the display method. The display method looks like this:

</p>

<pre class="brush: js"> function display()

{

	var the_string = "";

	if(this.health == min_health)

	{

		the_string = this.pet_name + " is dead!";

	} else {

		the_string += "Health: " + parseInt(this.health);

		the_string += ", Age: " + this.age;

		the_string += ", Happiness: " + parseInt(this.happiness);

		the_string += ", Hunger: " + parseInt(this.hunger);

		the_string += ".";

	}

	window.document.forms[this.form_number].status_textfield.value = the_string;

}</pre>

<p>This method constructs a string and displays it in the correct textbox. The <code>form_number</code> property drops the status information into the proper textbox. When we created each pet, we gave it a <code>form_number</code> &#8211; <code>pet1</code> got the form number 0, and <code>pet2</code> got the form number 1. Using this <code>form_number</code>, we know that the status of <code>pet1</code> should go into <code>window.document.forms[0].status_textfield.value</code> and the status of <code>pet2</code> should go into <code>window.document.forms[1].status_textfield.value</code>. The last line of this method determines which form to drop the status using <code>this.form_number</code>. The other interesting thing in this method is the <code>parseInt</code> function. Thanks to the way we generated the random numbers, the values for things like health and happiness look something like this:2.738993720. They&#8217;re real numbers, but they can get pretty long. So <code>parseInt</code> chops off everything after the decimal point; e.g., <code>parseInt(2.738)</code> ends up as simply 2.The third interesting method is <code>makeOlder()</code>. It ages the pet and makes it a little more hungry and a little less happy. This method gets called every second using a <code>setTimeout</code>, which I&#8217;ll show you next. I won&#8217;t go through the whole <code>makeOlder()</code> method, just enough to give you an idea about what it&#8217;s doing.



</p>

<pre class="brush: js"> function makeOlder()

{

	var good_happiness = 5;

	var max_hunger = 5;

	this.age += 1

	var happiness_change = Math.random() * 2;

	this.happiness = this.happiness - happiness_change;

	var hunger_change = Math.random() * 2;

	this.hunger += hunger_change;

	if(this.hunger &gt; max_hunger)

	{

		this.happiness = this.happiness - Math.random() * 2;

		this.health = this.health - Math.random() * 2;

	}

}

</pre>

<p>As you can see, the method adds one to the age of the pet, decreases its happiness, and increases its hunger by some random amount. Then a set of rules, only one of which is shown here, says, &#8220;If the pet is really hungry, make it more unhappy and less healthy.&#8221; Now that we have these methods, we will add them to the constructor to make a complete virtual pet object:

</p>

<pre class="brush: js">function Pet(pet_name, form_number)

{

	this.pet_name = pet_name;

	this.form_number = form_number;

	this.happiness = Math.random() * 5; //random number between 0 and 4.99.

	this.health = Math.random() * 5 + 2; // random number between 2 and 6.99

	this.display = display;

	this.age = 0;

	this.hunger = Math.random() * 5;



	this.play = play;

	this.feed = feed;

	this.medicate = medicate;

	this.makeOlder = makeOlder;

}

</pre>

<p>The last piece of the picture is the code that sics the <code>makeOlder()</code> method on each pet every three seconds. This function is called when you hit the start button.

</p>

<pre class="brush: js"> function progress_time()

{

	pet1.makeOlder();

	pet2.makeOlder();

	timeout = setTimeout("progress_time();", 3000);

	pet1.display();

	pet2.display();

}



</pre>

<p>As you see, it calls <code>makeOlder()</code> on each pet and calls itself again one second later. After a second passes, the function gets called yet again. The pets age and the <code>setTimeout</code> is called. This continues until an overworked user calls <code>clearTimeout(the_time_out)</code>. This example utilizes almost everything we&#8217;ve learned to date. If you understood what&#8217;s going on, you know a big heap of JavaScript. Take another break before you go on to today&#8217;s last topic:using JavaScript shortcuts to get at hard-to-reach objects.

</p>

<a name="Evaluating_Strings"></a><h4> <span class="mw-headline">Evaluating Strings</span></h4>

<p>JavaScript has a bunch of built-in tricks to make coding easier. One of these tricks is the <code>eval()</code> function, which takes a string and executes it as if it were a JavaScript expression. I actually talked about eval a little bit in <a href="/2010/02/JavaScript_Tutorial_-_Lesson_5" title="Tutorial:JavaScript Tutorial - Lesson 5">Part I, Day 5</a>, but here&#8217;s a little example for you to review:



</p>

<pre class="brush: js"> var the_unevaled_answer = "2 + 3";

 var the_evaled_answer = eval("2 + 3");

 alert("the un-evaled answer is " + the_unevaled_answer + " and the evaled answer is " + the_evaled_answer);

</pre>

<p>If you <a href="http://www.wired.com/wired/webmonkey/stuff/advanced_js_tutorial_files/silly_eval.html" class="external text" title="http://www.wired.com/wired/webmonkey/stuff/advanced_js_tutorial_files/silly_eval.html" rel="nofollow">run this silly eval code</a>, you&#8217;ll see that it actually executes the string &#8220;2 + 3&#8243; in JavaScript. So, when you set <code>the_evaled_answer</code> equal to <code>eval("2 + 3")</code>, JavaScript figures out and then returns the sum of two and three. This may seem like a silly thing to do, but it can get way more interesting. For example, you can use eval to create functions entirely on the fly, based on user input. This could be used to make programs that actually alter themselves over time. They could evolve, mutate, become sentient, maybe even take over the world. In practice, eval is rarely used, but you might see people using it to access hard-to-reach objects.

</p>

<a name="Getting_at_Hard-to-Reach_Objects"></a><h4> <span class="mw-headline">Getting at Hard-to-Reach Objects</span></h4>

<p>One of the problems with the Document Object Model Hierarchy is that it&#8217;s sometimes a pain to get to the object of your desire. For example, here is the function to ask the user for an image to swap:



</p><p><a href="http://www.wired.com/wired/webmonkey/stuff/advanced_js_tutorial_files/simple_swap.html" class="external text" title="http://www.wired.com/wired/webmonkey/stuff/advanced_js_tutorial_files/simple_swap.html" rel="nofollow">Click here</a>.

</p><p>You could use this function:

</p>

<pre class="brush: js"> function swapOne()

 {

 	var the_image = prompt("change parrot or cheese","");

 	var the_image_object;



 	if (the_image == "parrot")

 	{

 		the_image_object = window.document.parrot;

 	} else {

 		the_image_object = window.document.cheese;

 	}



 	the_image_object.src = "ant.gif";

 }

</pre>

<p>With these image tags:

</p>

<pre class="brush: js"> &lt;img src="http://www.wired.com/images/archivetuff3a/parrot.gif" name="parrot"&gt;

 &lt;img src="http://www.wired.com/images/archivetuff3a/cheese.gif" name="cheese"&gt;

</pre>

<p>Note the lines that look like this:



</p>

<pre class="brush: js"> the_image_object = window.document.parrot;

</pre>

<p>This assigns the image object parrot to a variable. Although it might look strange, it&#8217;s perfectly legal. But what happens if you have 100 images instead of just two? You&#8217;d have to have a huge <code>if-then-else</code> statement. It would be nice if you could just do this:

</p>

<pre class="brush: js"> function swapTwo()

 {

 	var the_image = prompt("change parrot or cheese","");

 	window.document.the_image.src = "ant.gif";

 }

</pre>

<p>Unfortunately, JavaScript will look for an image named <code>the_image</code> rather than simply know you want <code>the_image</code> to be &#8220;cheese,&#8221; if the user typed &#8220;cheese&#8221; into the prompt box, or &#8220;parrot,&#8221; if he or she typed &#8220;parrot.&#8221; And thus you get an error saying something like, &#8220;Never heard of the object called <code>the_image</code>.&#8221;



</p><p>Luckily, eval can help you get at the image object you want.

</p>

<pre class="brush: js"> function simpleSwap()

 {

 	var the_image = prompt("change parrot or cheese","");

 	var the_image_name = "window.document." + the_image;

 	var the_image_object = eval(the_image_name);

 	the_image_object.src = "ant.gif";

 }

</pre>

<p>If the user types &#8220;parrot&#8221; into the prompt box, the second line creates a string that looks like <code>window.document.parrot</code>. Then the eval on the third line says, &#8220;Give me the object <code>window.document.parrot</code>&#8221; &#8211; which is the image object you want. And once you have that image object, you can change its source to <code>ant.gif</code>. Funky, no? It&#8217;s actually pretty useful, and people do it a lot.

</p><p>If you don&#8217;t like <code>eval()</code>, there is another way to access hard-to-reach objects.

</p><p>If you don&#8217;t like <code>eval()</code>, there is another way to access hard-to-reach objects.



</p>

<a name="Another_Way_to_Get_at_Hard-to-Reach_Objects"></a><h3> <span class="mw-headline">Another Way to Get at Hard-to-Reach Objects </span></h3>

<p>Here&#8217;s what we&#8217;ve learned so far about getting at an image object:

</p>

<pre class="brush: js">function simpleSwap()

{

var the_image = prompt("change parrot or cheese","");

var the_image_name = "window.document." + the_image;

var the_image_object = eval(the_image_name);

the_image_object.src = "ant.gif";

}

</pre>

<p>As it turns out, you can refer to images by their name in the images-associative array, like this <code>window.document.images["parrot"].src</code>. This is just like referring to images by their index number in the forms array, as in <code>window.document.images[0].src</code>. Therefore, the above code can be rewritten as

</p>

<pre class="brush: js">function simpleSwap()

{

var the_image = prompt("change parrot or cheese","");

window.document.images[the_image].src = "ant.gif";

}

</pre>

<p>You can use this trick to locate all sorts of objects. If you have a textbox in a form, like this:



</p>

<pre class="brush: js">&lt;form name="the_form"&gt;

&lt;input type="text" name="the_text_box"&gt;

&lt;/form&gt;

</pre>

<p>You could change the text in the textbox like this:

</p>

<pre class="brush: js">window.document.forms["the_form"].elements["the_text_box"].value = "hello!";

</pre>

<p>Now you know several ways to access and change information in objects. Using the form example above, we can access the textbox in four different ways:

</p><p>var the_form_name = &#8220;the_form&#8221;;

var the_element_name = &#8220;the_text_box&#8221;;

</p><p>1. window.document.forms[0].elements[0].value = &#8220;hello!&#8221;;

</p><p>2. window.document.forms[the_form_name].elements[the_element_name].value = &#8220;hello!&#8221;;

</p><p>3. window.document.the_form.the_text_box.value = &#8220;hello!&#8221;;



</p><p>4. var the_element_string = &#8220;window.document.&#8221; + the_form_name + &#8220;.&#8221; + the_element_name;

</p><p>var the_element = eval(the_element_string);

</p><p>the_element_string.value = &#8220;hello!&#8221;;

</p><p>Whichever method you use depends on your mood, your comfort level, and what information you have available to you at the time. And that&#8217;s it for today&#8217;s lesson. Let us review.

</p>

<a name="Lesson_4_Review"></a><h3> <span class="mw-headline">Lesson 4 Review</span></h3>

<p>Today we covered many topics, vast and deep. We started with a brief discussion of client-side image maps, and we learned how to add JavaScript just like you to links. After that we learned how to preload images through a clever use of the Image object. Creating a new Image object and assigning an image to that object&#8217;s src automatically loads the image into cache. Because Image and other objects are so great, we took a long sally into the world of objects and object-oriented programming. This journey ended in the creation of a virtual pet, complete with its own properties and methods. Finally, we learned how to use <code>eval()</code> and associative arrays to manipulate objects that might otherwise be hard to access. Object-oriented programming is a relatively new and funky idea. By understanding how it works, we take a huge step toward becoming a programmer for the next millennium. And as we come to the end of today&#8217;s lesson, we are also done with JavaScript. We&#8217;ve covered the length and breadth of the language. Sure, a few scattered things remain &#8212; some basic debugging and optimization techniques, for instance, which will be very useful now that you&#8217;re able to write big, complex programs. But, essentially speaking, you are now a JavaScript Master! Before you tackle the <a href="/2010/02/Advanced_JavaScript_Tutorial_-_Lesson_5" title="Tutorial:Advanced JavaScript Tutorial - Lesson 5">final Lesson</a>, go ahead and test your mastery on today&#8217;s <a href="http://www.wired.com/wired/webmonkey/stuff/advanced_js_tutorial_files/AJST_homework4.html" class="external text" title="http://www.wired.com/wired/webmonkey/stuff/advanced_js_tutorial_files/AJST_homework4.html" rel="nofollow">homework assignment</a>.

</p><div id='linker_widget' class='contextly-widget'></div>]]></content:encoded>
            <wfw:commentRss>http://www.webmonkey.com/2010/02/advanced_javascript_tutorial_-_lesson_4/feed/</wfw:commentRss>
        <slash:comments>0</slash:comments>

        
    </item>
    
    <item>
        <title>Advanced JavaScript Tutorial &#8211; Lesson 5</title>
        <link>http://www.webmonkey.com/2010/02/advanced_javascript_tutorial_-_lesson_5/</link>
        <comments>http://www.webmonkey.com/2010/02/advanced_javascript_tutorial_-_lesson_5/#comments</comments>
        <pubDate>Tue, 16 Feb 2010 01:45:47 +0000</pubDate>

                <dc:creator>Webmonkey Staff</dc:creator>

        <guid isPermaLink="false">http://stag.wired.com/primate/?p=727</guid>
        		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[thau]]></category>
		<category><![CDATA[wiki]]></category>
        <description><![CDATA[Wow &#8211; you made it to the last and final lesson! Stunning. As a reward for all your hard work, I&#8217;ve made this lesson extremely relaxing &#8211; no nitty-gritty code to wrap your mind around and no hairy homework, just coding theory and pointers to resources. The topics for the day are: Tools to help [...]]]></description>

            <content:encoded><![CDATA[<!-- wpautop disabled --><p>Wow &#8211; you made it to the last and final lesson! Stunning. As a reward for all your hard work, I&#8217;ve made this lesson extremely relaxing &#8211; no nitty-gritty code to wrap your mind around and no hairy homework, just coding theory and pointers to resources.

</p><p>The topics for the day are:

</p>
<ul><li> Tools to help you write JavaScript
</li><li> Debugging techniques
</li><li> Tips for making your JavaScript code run quickly
</li></ul>
<p>
</p>
<br />
<span id="more-727"></span>
<table id="toc" class="toc" summary="Contents"><tbody><tr><td><div id="toctitle"><h2>Contents</h2> </div>

<ol>

<li><a href="#Tools_of_the_Trade">Tools of the Trade</a></li>

<li><a href="#Debugging_Techniques">Debugging Techniques</a></li>

<li><a href="#Printing_Variables">Printing Variables</a></li>



<li><a href="#Common_Programming_Mistakes">Common Programming Mistakes</a></li>

<li><a href="#Fixing_Bugs">Fixing Bugs</a></li>

<li><a href="#Good_Coding_Practices">Good Coding Practices</a></li>

<li><a href="#Optimizing_Your_JavaScript_for_Speed">Optimizing Your JavaScript for Speed</a></li>

<li><a href="#What.27s_Next.3F">What&#8217;s Next?</span></a></li>



</ol>

</td></tr></tbody></table>



<a name="Tools_of_the_Trade"></a><h4> <span class="mw-headline">Tools of the Trade</span></h4>

<p>To tell the truth, I don&#8217;t use anything other than a word processor to write JavaScript. Call me old-school &#8211; crusty even. Though plenty of tools out there write JavaScript for you, the code they generate is pretty obtuse and difficult to change. If you really want to use a tool to create JavaScript, I suggest Dreamweaver, which pumps out some amazing JavaScripts in very little time. However, if you ever want to tweak the scripts later, be prepared to look at some awfully ungainly code.

</p><p>You can also find tools that help you debug JavaScript. I don&#8217;t use these either. Netscape has one, and so does Microsoft, but I&#8217;ve never met anyone who&#8217;s successfully used these debuggers. Go ahead, prove me wrong. But until someone convinces me that a product is worth buying (hint, hint, hint &#8211; send me that free software), I prefer to debug the old-fashioned way.

</p>

<a name="Debugging_Techniques"></a><h4> <span class="mw-headline">Debugging Techniques</span></h4>

<p>As you program JavaScript more and more, you&#8217;ll begin to understand those opaque error messages JavaScript gives you. And once you understand the common errors of your ways, you&#8217;ll soon know what pitfalls to avoid, and the raw code you generate will be less and less error-prone. Programming is definitely a skill that improves dramatically over time. But no matter how skilled you become, you&#8217;re still going to spend some time debugging.

</p><p>If you&#8217;ve been doing your homework, or have ever tried writing JavaScripts of your own, you know that a considerable hunk of your scripting time is spent debugging. This is normal &#8211; it&#8217;s just one of those things programmers have to do. In fact, according to numerous studies, 50 percent of the average programmer&#8217;s time is spent figuring out what&#8217;s wrong with code.

</p><p>The key is to learn how to debug your programs efficiently. I have several tips to help you figure out why your program isn&#8217;t doing what it should, or to avoid writing buggy code in the first place:

</p>

<ul><li> Print out variables in various ways



</li><li> Watch for common mistakes

</li><li> Think before coding

</li></ul>

<p><br />

Let&#8217;s start with printing those variables.

</p>

<a name="Printing_Variables"></a><h4> <span class="mw-headline">Printing Variables</span></h4>

<p>Once you find a bug, you can get rid of it. Unfortunately, finding the suckers isn&#8217;t always easy &#8211; most of your debugging time is spent just figuring out the location of the error.

</p><p>One of the most tried-and-true debugging methods is to put simple statements in your code that print out what&#8217;s going on. Let&#8217;s say you&#8217;re having a problem with these two functions:

</p>

<pre class="brush: js"> function getName()

 {

    var first_name = prompt("what's your first name?","");

    var last_name = prompt("what's your last name?","");

    var the_name = first_name + " " + last_name;

 }



 function theGreeting()

 {

    var the_name = "";

    the_name = getName();



    if (the_name == "Dave Thau")

    {

 	alert("Hello, oh greatest one!");

    } else {

 	alert("Ahoy palloi!");

    }

 }

</pre>



<p>Give this example a <a href="http://www.wired.com/wired/webmonkey/stuff/advanced_js_tutorial_files/wrong.html" class="external text" title="http://www.wired.com/wired/webmonkey/stuff/advanced_js_tutorial_files/wrong.html" rel="nofollow">try</a> and see if you can figure out what&#8217;s wrong (Netscape 3.x users may experience some error check problems due to the nature of this, and the following Javascript examples). If you enter random names into the alert boxes, you get the greeting &#8220;Ahoy palloi!&#8221; However, if you enter &#8220;Dave&#8221; in the first prompt box and &#8220;Thau&#8221; in the second, you&#8217;re supposed to get the message &#8220;Hello, oh greatest one!&#8221; Instead, you still get the &#8220;Ahoy palloi!&#8221; message. Obviously, something&#8217;s wrong with the functions. In this simple example, you could probably find the errors just by looking at the JavaScript. However, as your scripts get more and more complicated, finding your errors just by eyeballing them grows increasingly difficult.

</p><p>If JavaScript doesn&#8217;t catch your error, and you can&#8217;t figure it out just by looking at your script, it sometimes helps to print out variables. The easiest way to do this is with an <code>alert()</code>, like this:

</p>

<pre class="brush: js"> // theGreeting gets a name using getName, then presents one or two

 // alert boxes depending on what the name is

 //



 function getName()

 {

    var first_name = prompt("what's your first name?","");

    var last_name = prompt("what's your last name?","");

    var the_name = first_name + " " + last_name;

    alert("in getName, the_name is: " + the_name);

 }



 // theGreeting gets a name using getName, then presents

 // one of two alert boxes depending on what the name is

 //



 function theGreeting()

 {

    var the_name = "";

    the_name = getName();



    alert("after getName, the_name = " + the_name);



    if (the_name == "Dave Thau")

    {

 	alert("hello, oh greatest one!");

    } else {

 	alert("ahoy palloi!");

    }

 }

</pre>

<p>Notice we&#8217;ve placed alerts at all the important points. Now try <a href="http://www.wired.com/wired/webmonkey/stuff/advanced_js_tutorial_files/wrong2.html" class="external text" title="http://www.wired.com/wired/webmonkey/stuff/advanced_js_tutorial_files/wrong2.html" rel="nofollow">the version with lots of alert boxes</a>. If you enter the names &#8220;Dave&#8221; and &#8220;Thau,&#8221; you&#8217;ll notice that the first alert says &#8220;in getName, the_name is: Dave Thau,&#8221; but the second alert says &#8220;after getName, the_name = undefined,&#8221; which tells you things got messed up right after the last line of <code>getName()</code>. Somehow, <code>the_name</code> is OK just before the function exits, but <code>theGreeting</code> doesn&#8217;t correctly set the variable <code>the_name</code>. When you&#8217;ve written a function that does the right thing, but has problems returning a value, the first thing you should check is whether you&#8217;re actually returning the value. And sure enough, that&#8217;s the problem here. The <code>getName()</code> function figures out the name, but never returns it. So we need to add <code>return the_name;</code> at the end of the function.



</p><p>Putting a bunch of alert boxes in your code is very helpful. Unfortunately, hitting &#8220;OK&#8221; every other line is also sort of a pain.

</p><p>You can do a few things to debug your code without the hassle of the alert box. One option is to write your debugging messages to a text area inside a form. Another possibility is to write the debugging messages to another window. Here&#8217;s an example of debugging code that <a href="http://www.wired.com/wired/webmonkey/stuff/advanced_js_tutorial_files/wrong3.html" class="external text" title="http://www.wired.com/wired/webmonkey/stuff/advanced_js_tutorial_files/wrong3.html" rel="nofollow">writes debugging messages</a>.

</p><p>A third trick that can make your debugging experience more pleasant involves creating different debugging levels and then setting a &#8220;debug&#8221; variable. Here&#8217;s the JavaScript that actually runs on this page:

</p>

 <pre class="brush: js"> // debug can be either none, alert, or textarea depending

 // on the kind of debugging I want to do

 //

 var debug = "none";



 // function getName gets a first and last name, concatenates

 // them with a space in between, and returns the name

 //

 function getName()

 {

    var first_name = prompt("what's your first name?","");

    var last_name = prompt("what's your last name?","");

    var the_name = first_name + " " + last_name;



    var error_message = "in getName, the_name is: " + the_name;

    doError("in getName, the_name is: " + the_name);

 }



 // theGreeting gets a name using getName, then presents

 // one of two alert boxes depending on what the name is

 //

 function theGreeting()

 {

    var the_name = "";

    the_name = getName();



    doError("after getName, the_name = " + the_name);



    if (the_name == "Dave Thau")

    {

 	alert("hello, oh greatest one!");

    } else {

 	alert("ahoy palloi!");

    }

 }





 // doError is the error handling routine

 // depending on the type of debug message

 // it presents either no debug message, an alert

 // or puts the message in a textarea

 //

 function doError(the_message)

 {

    if (debug == "alert")

    {

 	alert(the_message);

    } else if (debug == "textarea") {

 	window.document.the_form.the_text.value += the_message + "&lt;br&gt;n";

    }

 }

 </pre>

<p>Notice that I&#8217;ve defined a variable called &#8220;debug&#8221; that can be either &#8220;none,&#8221; &#8220;alert,&#8221; or &#8220;textarea.&#8221; Then when I want to generate an error message, I send it to the function <code>doError()</code>, which either does nothing, presents an alert box with the message, or sticks the message in a text area, depending on how I set the debug variable. You can set the debug variable to &#8220;textarea,&#8221; when you have lots of errors that you want to look at simultaneously. Then, when you&#8217;re ready to show your code to the world, you can just set debug to &#8220;none,&#8221; and the error message will no longer show up, which saves you the hassle of having to find and remove all your debug statements.

</p><p>Often, programmers create different debug levels, such as &#8220;none,&#8221; &#8220;brief,&#8221; and &#8220;extreme.&#8221; &#8220;Brief&#8221; will print a few debug messages along the way, &#8220;extreme&#8221; will print a lot of debugging messages, and &#8220;none&#8221; will of course print no messages.

</p><p>If you build your debugging system like this, you can set the debug level to &#8220;brief&#8221; while you&#8217;re coding, and &#8220;none&#8221; when you&#8217;re ready to make your JavaScript public. Then, if something totally weird starts happening, and you don&#8217;t know where to look for the problem, you can set the debug level to &#8220;extreme&#8221; and wade through all the debug messages until you find something suspicious.



</p><p>OK, enough about debugging systems. Let&#8217;s turn now to common mistakes made by JavaScript coders.

</p>

<a name="Common_Programming_Mistakes"></a><h4> <span class="mw-headline">Common Programming Mistakes</span></h4>

<p>Most mistakes are just silly syntactic ones. It takes a long time to remember to close all those quotes, curly braces, and parentheses, but luckily the automatic JavaScript bug detector catches most of those errors for you. Though JavaScript bug detectors keep improving as browsers get more sophisticated, a few bugs still slip through the cracks. Here are a few common ones to look out for:

</p>

<dl><dt> Messing up variable or function names.

</dt><dd> Mistakes with capitalization and pluralization of variable and function names are annoyingly typical and sometimes the JavaScript bug detector fails to catch them. By creating and adhering to a naming convention for your variables and functions, you can greatly reduce the number of these mixups. For instance, I name my variables in all lower case and with underscores in the place of spaces ( <code>my_variable</code>, <code>the_date</code>, <code>an_example_variable</code>), and I use in-fix notation for my functions ( <code>addThreeNumbers()</code>, <code>writeError()</code>, etc.). I avoid pluralizing anything because I always forget which variables are plural and which variables aren&#8217;t.



</dd><dt> Accidentally using reserved words.

</dt><dd> Some words can&#8217;t be used as variables because they&#8217;re already in use by JavaScript. For example, you can&#8217;t have a variable named &#8220;if&#8221; because it&#8217;s actually a part of JavaScript &#8211; if you use &#8220;if,&#8221; you&#8217;ll wreak all kinds of havoc. While you&#8217;d have to be pretty deranged to name a variable &#8220;if,&#8221; a variable called &#8220;document&#8221; may be more tempting. Unfortunately, &#8220;document&#8221; is a JavaScript object. Another often used, but generally problematic thing to call a variable is &#8220;name&#8221; (form elements have &#8220;names&#8221;). Naming a variable &#8220;name&#8221; doesn&#8217;t always cause problems, only sometimes, which can be even more confusing &#8211; all the more reason to avoid calling a variable &#8220;name.&#8221; Unfortunately, different browsers have different reserved words, so there&#8217;s no way to know exactly which words to eschew. The safest course of action is to avoid words that are part of JavaScript as well as those found in HTML. If you&#8217;re having problems with a variable and you can&#8217;t figure out what&#8217;s wrong, try renaming the variable. If that works, then you&#8217;ve probably stumbled across a reserved word.

</dd><dt> Remembering that you need two equals signs in logical tests.

</dt><dd> Some browsers catch this error, and some don&#8217;t. This is a very common mistake and extremely difficult to catch if the browser doesn&#8217;t point it out for you. Here&#8217;s an example of the error:

</dd></dl>

<pre class="brush: js"> var the_name = prompt("what's your name?", "");

 if (the_name = "the monkey")

 {

 	alert("hello monkey!");

 } else {

 	alert("hello stranger.");

 }

</pre>

<p>This code will throw up the &#8220;hello monkey!&#8221; alert box regardless of what you type into the prompt, which isn&#8217;t what we want. That&#8217;s because there&#8217;s only one equals sign in the <code>if-then</code> statement, which tells JavaScript that you want to set one thing equal to another thing. Let&#8217;s say you type &#8220;robbie the robot&#8221; into the prompt. Initially, <code>the_name</code> will be &#8220;robbie the robot.&#8221; But then the <code>if</code> statement tells JavaScript that you want to set <code>the_name</code> = &#8220;the monkey.&#8221; So JavaScript happily follows your command, and sends a &#8220;true&#8221; message to the <code>if-then statement</code>, and the alert box shows up with the &#8220;hello monkey!&#8221; message every time. This insidious bug can drive you belfry batty. So concentrate on doubling those equals signs.



</p>

<dl><dt> Accidentally quoting variables, or forgetting to quote strings.

</dt><dd> This one gets me time and time again. The only way JavaScript knows the difference between a variable and a string is that strings have quotes around them and variables don&#8217;t. Here&#8217;s an obvious error:

</dd></dl>

<pre class="brush: js"> var the_name = 'koko the gorilla';

 alert("the_name is very happy");

</pre>

<p>This will produce an alert box that says &#8220;the_name is very happy,&#8221; even though <code>the_name</code> is a variable. This is because once JavaScript sees quotes around something, it stops thinking about it, so by putting <code>the_name</code> in quotes, you stop JavaScript from looking it up in its memory. Here&#8217;s a less obvious extension of this bug (which we saw in Day 3):

</p>



<pre class="brush: js"> function wakeMeIn3()

 {

 	var the_message = "Wake up!  Hey!  Hey!  WAKE UP!!!!";

 	setTimeout("alert(the_message);", 3000);

 }

  </pre>

<p>The problem here is that you&#8217;re telling JavaScript to execute <code>alert(the_message)</code> in three seconds. Three seconds from now, however, <code>the_message</code> no longer exists because you&#8217;ve exited the function. The solution to this problem is this:

</p>

<pre class="brush: js"> function wakeMeIn3()

 {

 	var the_message = "Wake up!";

 	setTimeout("alert('" + the_message+ "');", 3000);

 }

 </pre>

<p>By pulling <code>the_message</code> out of the quotes like this, the command <code>"alert('Wake up!');"</code> is scheduled by the <code>setTimeout</code>, which is what you want.



</p><p>These are just some of the harder-to-debug errors that might sneak into your code. Once you&#8217;ve found your bugs, there are good and bad ways to go about fixing them. Lucky for you, I can give you the benefit of my trials and errors.

</p>

<a name="Fixing_Bugs"></a><h4> <span class="mw-headline">Fixing Bugs</span></h4>

<p>Finding a bug, though sometimes difficult, is only the first step. Next you have to get rid of it. Here are a few things you should do as you crush those bugs:

</p>

<dl><dt> Copy your program first.

</dt><dd> Some bugs are really hard to get rid of. In fact, sometimes a little bug can drive you so crazy that, in the process of eradicating it, you destroy your entire program. Saving your program before you start debugging is the best way to ensure that a bug doesn&#8217;t get the best of you.

</dd><dt> Fix one bug at a time.

</dt><dd> If you know about several bugs, fix each one and test your fix before you move on to the next bug. Fixing a lot of bugs all at once without checking your work is just an invitation for even more bugs.

</dd><dt> Beware of voodoo coding.



</dt><dd> Sometimes you know a bug exists, but you don&#8217;t really know why. Lets say you have a variable called &#8220;index,&#8221; and for some reason &#8220;index&#8221; is always one less than you think it should be. You can do one of two things: sit there for a while and figure out <i>why</i> it&#8217;s coming up short or just shrug, add one to index before using it, and move on. The latter method is called voodoo programming. When you start thinking &#8220;What the hell &#8211; why is index two instead of three? Well &#8230; I&#8217;ll just make it work for now and fix it later,&#8221; you&#8217;re slapping a Band-Aid on a potentially serious wound. Voodoo programming may work in the short term, but you&#8217;re looking at long-term doom &#8211; if you don&#8217;t understand your code enough to really get rid of a bug, that bug will come back to haunt you. It will either return in the form of yet another weird error that you can&#8217;t figure out, or it&#8217;ll make your code extremely hard to understand for the next poor soul cursed to look at it.

</dd><dt> Look for similar bugs.

</dt><dd> In some ways, the ability to cut and paste code is the worst thing for programmers. Often, you&#8217;ll write some JavaScript in one function and then cut and paste it into another function. And if the first function had a problem, you now have problems in two functions. I&#8217;m not saying you shouldn&#8217;t cut and paste code. But bugs have a way of multiplying, so if you find one, you should look for others that are similar. (Or just make sure something works before you start creating multiple versions of it.) Misspelled variable names are the kind of thing that crops up several times in one JavaScript &#8211; misspell <code>the_name</code> as <code>teh_name</code> in one place, chances are you&#8217;ve done it someplace else.

</dd><dt> If all else fails &#8230;



</dt><dd> If you&#8217;re sitting there, staring at a bug, and you just can&#8217;t figure out what&#8217;s going on (or if you can&#8217;t even find the bug in the first place, but you know it&#8217;s there because your program isn&#8217;t working right), the best thing to do is walk away from your computer. Go read a book, take a stroll around the corner, get a tasty beverage &#8211; do something, anything, but don&#8217;t think about the program or the problem. This technique is called &#8220;incubation&#8221; in some circles, and it works amazingly well. After you&#8217;ve had a little break and relaxed, try finding the bug again. You&#8217;ll approach the problem with a refreshed vision that&#8217;s often quite illuminating. Incubation works because it breaks you out of a (dare I say it?) dysfunctional mindset. If you follow a wrong path for too long, you sometimes get stuck with no room in which to turn around. The best thing to do when this happens is find a way to start down a new path. I know it&#8217;s touchy-feely, but it works. Really!

</dd><dt> And if <i>that</i> doesn&#8217;t work &#8230;

</dt><dd> Ask someone for help. Sometimes you wear such a rut in your problem with repetitious thought patterns, only someone with a fresh eye can see the hole in your logic. In structured coding environments, programmers periodically review one another&#8217;s code. This is appropriately named &#8220;code review,&#8221; and it not only helps iron out bugs, it also results in better code. Don&#8217;t be afraid to show other people your JavaScripts. It makes you a better JavaScripter.

</dd><dt> But the absolute <i>best</i> way to eradicate bugs is &#8230;

</dt><dd> to create bug-free code from the get-go.

</dd></dl>



<a name="Good_Coding_Practices"></a><h4> <span class="mw-headline">Good Coding Practices</span></h4>

<p>The key to good programming is to write programs for people, not computers. If you keep in mind that someone else will probably read your JavaScript, you&#8217;ll write much clearer code. The clearer your code, the less likely you are to make mistakes. Clever coding is cute, but it&#8217;s the clever coder that gets the bug. The best rule of thumb is KISS, Keep It Simple, Sweetie.

</p><p>Another helpful technique is to comment <i>before</i> you start writing any code. This forces you to think about the problem before diving right on into it. Once you&#8217;ve written the comments, you can write the code right below each one. Here&#8217;s an example of a function written this way.

</p><p><b>Step 1: Write the comments</b>

</p>

<pre class="brush: js">

 //function beSassy()

 //  beSassy asks for a user's name, chooses a random

 //  insult and returns an alert box with the user's

 //  name and the insult.

 function beSassy()

 {

 	//  first write a list of insults

 	//



 	//  next get the user's name

 	//



 	//  then choose a random insult

 	//



 	//  finally, return the personalized sass

 	//

 }



'''Step 2: Fill in the code'''





 //function beSassy()

 //  beSassy asks for a user's name, chooses a random

 //  insult and returns an alert box with the user's

 //  name and the insult.

 function beSassy()

 {

 	//  first write a list of insults

 	//

 	var the_insult_list = new Array;

 	the_insult_list[0] = "your shoe lace is untied";

 	the_insult_list[1] = "your mama!";

 	the_insult_list[2] = "it's hard to be insulting";



 	//  next get the user's name

 	//

 	var the_name = prompt("What's your name?", "");



 	//  then choose a random insult

 	//

 	var the_number =  Math.random() * 5;

 	var insult_number = parseInt(the_number);

 	var the_insult = the_insult_list[insult_number];



 	//  finally, return the personalized sass

 	//

 	alert("Hey " + the_name + " " + the_insult);

 }

</pre>

<p>This comment-first policy not only forces you to think before you code, it also makes the task of coding seem a lot easier &#8211; by breaking things down into little, easily coded sections, your problem looks less like Everest and more like a bunch of pleasant rolling hills.

</p><p><b>And finally &#8230;</b>



</p>

<dl><dt> Always end your statements with semicolons.

</dt><dd> Although it&#8217;s not strictly necessary, you should get into the habit of ending all your statements with a semicolon since it clears the way for code to come. Forget that semicolon, and suddenly the next line of perfectly good code generates an error.

</dd><dt> Initialize your variables with &#8220;var&#8221; unless you have a good reason not to.

</dt><dd> Localizing all your variables using &#8220;var&#8221; reduces the chance that one function will mess up the workings of another, unrelated function.

</dd></dl>

<p>OK, now that you know how to code, let&#8217;s learn how to make your JavaScript run quickly.

</p>

<a name="Optimizing_Your_JavaScript_for_Speed"></a><h4> <span class="mw-headline">Optimizing Your JavaScript for Speed</span></h4>

<p>Once you&#8217;ve gotten your JavaScript working, you might want to get it working <i>faster.</i> Before I go into the ways to speed up your code, let me bend your ear about something called the 80/20 rule. You get 80 percent of the improvement of optimization with the first 20 percent of the work you do. Eking out that remaining 20 percent of speed is a huge pain, and often results in completely unreadable and difficult-to-manage code. In short, if your JavaScript is running slowly, there are a few very simple things you can do to speed it up, but unless your script is still really slow, I wouldn&#8217;t bother optimizing beyond that.



</p><p>Here are a few easy methods of getting the lead out of your code.

</p><p><b>Limit the amount of work you do inside loops</b>.

</p><p>The most common cause of a really slow program is repeated work inside a loop. If a command only needs to execute once, there&#8217;s no reason to put it in a loop. For example:

</p>

<pre class="brush: js"> var index = 0;

 while (index &lt;10)

 {

    var the_date = new Date();

    var the_day = the_date.getDay();

    var the_name = prompt("what's the kid's name? " ,"");

    alert("On " + the_day + " " + the_name + " is a very special person.");

    index++;

 }

</pre>

<p>This program loops 10 times. Each time it figures out what day it is, asks for a kid&#8217;s name, and then prints out &#8220;On Monday, so-and-so is a very special person.&#8221;

</p><p>But the day never changes. It&#8217;s always today. So there&#8217;s no need to put the first two lines inside the loop. Rather than execute them 10 times, pull them out of the loop and save time by executing them only once:

</p>

<pre class="brush: js"> var index = 0;

 var the_date = new Date();

 var the_day = the_date.getDay();

 while (index &lt;10)

 {

    var the_name = prompt("what's the kid's name? " ,"");

    alert("On " + the_day + " " + the_name + " is a very special person.");

    index++;

 }

 </pre>

<p><b>Order <code>if-then-else</code> statements from most likely to least likely</b>.



</p><p>Because <code>if-then-else</code> statements end once they&#8217;ve found something true, you can reduce the number of statements that execute by putting the ones most likely to be true first. For example:

</p>

<pre class="brush: js"> var pet = prompt("what kind of pet do you have?", "");

 if (pet  == "cat")

 {

 	doCatStuff();

 } else if (pet == "dog")

 {

 	doDogStuff();

 } else if (pet == "bird")

 {

 	doBirdStuff();

 } else if (pet == "lizard")

 {

 	doLizardStuff();

 }

 </pre>

<p>On average, this list of <code>if</code> clauses will execute fewer logical tests than if it went from lizard to dog.

</p><p><b>Minimize repeated expressions</b>.

</p><p>If you find yourself repeatedly calculating a specific expression, like var pi = 22/7, it&#8217;s probably a good idea to just calculate it once and access it as a global variable. For example, instead of this:

</p>

<pre class="brush: js"> function theArea(radius)

 {

 	var pi = 22/7;

 	var area = pi * radius * radius;

 	return area;

 }



 function theCircumference(radius)

 {

 	var pi = 22/7;

 	var circumference = 2 * pi * radius;

 	return circumference;

 }

 </pre>



<p>do this

</p>

<pre class="brush: js"> var pi = 22/7;

 function theArea(radius)

 {

 	var area = pi * radius * radius;

 	return area;

 }



 function theCircumference(radius)

 {

 	var circumference = 2 * pi * radius;

 	return circumference;

 }

</pre>

<p>Yeah, I know that I&#8217;m using a global variable here, and I said that it was a bad idea. However, numbers like pi, which will never change during your program, are the exception to this rule. By calculating pi only once, you save an extra calculation. A small savings in time, perhaps, but it all adds up. These are just a few things you should look for if your code is too slow. They&#8217;re pretty obvious, but you&#8217;d be surprised how often you can overlook simple optimizations like these.

</p><p>And that, my friends, brings us to the end of today&#8217;s lesson, which in turn brings the entire Advanced JavaScript tutorial to a close. And if you&#8217;ve come this far, and you&#8217;ve read even half of the last five lessons, you&#8217;ve seen a lot of JavaScript. In fact, if you&#8217;ve understood most of what I&#8217;ve covered in the 10 lessons that span Parts I and II, you can safely call yourself a JavaScript acolyte. The road to true mastery now lies only with practice.

</p>

<a name="What.27s_Next.3F"></a><h4> <span class="mw-headline">What&#8217;s Next?</span></h4>

<p>Now that you have a working understanding of JavaScript, you can write some pretty serious JavaScripts. It&#8217;s time to move on to some of JavaScript&#8217;s many applications. Add dynamic HTML to your skill set, and you&#8217;ll be ready to achieve your wildest dreams. Well some of them anyway.

</p><p>But above all, you need to practice, practice, practice. Swipe existing code and mangle it beyond all recognition. Write scripts from the blank page up. Strive to create bug-free code, and become a master at fixing the bugs that slip through anyway. Keep your eyes peeled for interesting and new applications of JavaScript, and figure out how they&#8217;re done. It doesn&#8217;t even matter if your code works perfectly or not, because it all teaches you something. The more you learn, the better &#8211; and faster &#8211; your code becomes and the easier it is for you to create it.

</p><p>Now go forth young JavaScripter, and do me proud!

</p><p>Thau! </p><p><div id='linker_widget' class='contextly-widget'></div>]]></content:encoded>
            <wfw:commentRss>http://www.webmonkey.com/2010/02/advanced_javascript_tutorial_-_lesson_5/feed/</wfw:commentRss>
        <slash:comments>0</slash:comments>

        
    </item>
    </channel>
</rss>