Welcome to the Webmonkeys JavaScript tutorial. This page contains many useful examples of JavaScript in action. Do note however, this tutorial is still a work-in-progress.

If you haven't already, please check out the older Webmonkeys tutorial covering JavaScript here. It covers much of the same material and is a great place for a beginner to start experimenting with JavaScript. Also, Webmonkeys has created a basic web page template to demonstrate the placement of CSS styles and JavaScript ( page | zip ).

Before we begin, I would also like to point out some of the awesome frameworks this tutorial utilizes. Of course, there are plenty of more besides what we have used here. See the below links:

jQuery: http://jquery.com/

jQuery UI: http://jqueryui.com/

Twitter Bootstrap: http://twitter.github.com/bootstrap/

Let's go!

The Basics

Variables are dynamic in JavaScript and do not need to be declared with a specific type. Other than that, just take a glimpse at the following. It should be pretty straightforward if you know another language.

/* 
*  Basic JavaScript Syntax
*  ... and a multi-line comment
*/

var x = 1; // Int variable
var y = x + 1; // y == 2
x--; // x == 0
y = "Siebel"; // loosely-typed, so y can now be a string

var a = "Hello"; // String variable
var b = " World!"
var c = a + b; // "Hello World!"

// If - Else Statement (same as most languages)
if(x == 0) {
    // Do something.
} else {
    // Do something else.
}

Loops

Loops basically act as you would expect. JavaScript does have a handy loop to iterate through an array or other container (for-each loop).

// For loop
var i=0;
for (i = 0; i <= 5; i++) {
    document.write(i + " ");
}

// While loop
i = 0;
while (i <= 5) {
    document.write(i + " ");
    i++;
}

// For-each loop (using associative array)
var country = {name:"Germany", capital:"Berlin", population:81,702,329};
for (x in country) {
    document.write(country[x] + " ");
}

Functions

Functions are a little different in JavaScript. No return type is listed with the function signature. Function parameters may be listed, but they do not require a specific type. JavaScript is dynamically interpreted and expects the variables to be of the correct type.

Also, it is important to discuss the scope of JavaScript variables. Variables declared using "var" within a function can only be accessed within that function. This variable is destroyed when the function is exited. Variables outside the function are accessible from all JavaScript on that page.

// Displays dialog with the given message.
function displayAlert(message) {
    alert(message);
}

// Multiplies a and b
function product(a,b) {
    return a*b;
}

Arrays

In JavaScript, arrays are treated as objects. Additionally, JavaScript dynamically sizes arrays (similar in functionality to C++ vectors or Java ArrayLists).

var myArray = new Array(10); // Array of size 10

var emptyArray = []; // New, empty array

var colorArray = ['Red', 'Green', 'Blue']; // Initializing an array with pre-defined data
document.writeln(colorArray[0]); // Will output:  Red
document.writeln(colorArray.length); // Gets array length (outputs 3)

var crazyArray = [3, "Hello World!", function() {return true;}]; // Arrays can store any type

var xArray = [0, 1, 2, 3];
var yArray = [4, 5, 6, 7];
var zArray = [xArray, yArray];  // Multi-dimension arrays
document.writeln(zArray[1][2]); // Will output:  6

Classes

For our purposes, classes will not be a big part of the JavaScript we write. Here is one basic example of a class, although there are better ways (see JavaScript prototypes).

function Car (color) {
    this.color = color;
    this.year = "2011";
    this.model = "Mustang";
    this.getInfo = function() {
        return this.year + ' ' + this.color + ' ' + this.model;
    };
}

Background Information

Most browsers provide a set of methods that allow JavaScript to manipulate the DOM (Document Object Model) of web pages. This allows JavaScript to dynamically alter just about anything on the page.

However, not all browsers provide a consistent set of methods to control the DOM. Therefore, JavaScript frameworks like jQuery and Prototype are highly recommended. These frameworks make it significantly easier to control various aspects of a page. This tutorial focuses on jQuery.

Resources

Currently, this part of the JavaScript tutorial is still under development. Until it is complete, I highly recommend looking at the tutorials on the jQuery website regarding selectors and traversing. Being able to select and manipulate any part of a web page is an invaluable skill. Here is one tutorial on jQuery selectors:

http://docs.jquery.com/Tutorials:How_to_Get_Anything_You_Want

Background Information

Up until now, we've been discussing JavaScript in regards to smaller chunks of code (i.e. manipulating part of a page). However, several frameworks make it very easy to use JavaScript to implement major features of a site. Need tabs that dynamically load fresh content? No problem. How about a lightbox for your online photo gallery? Yes, this is also easily done with the right framework.

Resources

As with the general purpose JavaScript frameworks, there are just as many that specialize in JavaScript UI construction and manipulation. Two popular ones that work well with jQuery are jQuery UI and jQuery Tools. Below are the links to their websites... check them out! They have plenty of awesome examples that will help you do nearly anything you can imagine.

jQuery UI

jQuery Tools

Definition

AJAX stands for Asynchronous JavaScript and XML. It is a programming technique that emphasizes using asynchronous requests to get tasks done in the browser without refreshing the page. Using AJAX, web applications like GMail rarely (if ever) need to perform a refresh in the browser. The content on the page is handled dynamically with JavaScript and requests to the server.

Exercise 1: Coin Flip

For this activity, you will need to flip a coin at random and display the correct picture. Here are your instructions.

  1. The textarea below is where you may run your code. Imagine that the textArea is acting as a function named coinFlip(), and whatever you type into the textarea will run upon hitting the button.
  2. Hide any coins by setting the "display" property of anything with a class of "coin" to none.
  3. Generate a random number, either 0 (heads) or 1 (tails). You could very easily do this using pure JavaScript and Math.random(), but that's not interesting. Instead, do it by sending a post request to the following URL: http://www.acm.uiuc.edu/webmonkeys/2011/examples/php/RandomInt.php. For this post request, you need two variables to be sent: "min" should equal 0 and "max" should equal 1. The script at the URL calculates a random integer between minimum and maximum (inclusive) and will return it. See here (or the solution) for help.
  4. If the integer is 0, set "display" to "block" for any element with an ID of "heads". If it is 1, set "display" to "block" for any element with an ID of "tails".

If you are curious as to what the PHP script looks like, you can see it here.

Exercise 2: Login Check

For this activity, you will connect a login form to an online "database". Many login systems online require that the user refresh his or her page to continue logging into the site. However, through AJAX, our "users" will be able to log in without refreshing the page.

For testing purposes, the username is "admin" and the password is "webmonkey".

  1. The textarea below is where you may run your code. Imagine that the textArea is acting as a function named checkLogin(), and whatever you type into the textarea will run upon hitting the button.
  2. Hide any previous messages by setting "display" to "none" for any element with a class of "login-message".
  3. Send the values from the username and password fields to the following URL: http://www.acm.uiuc.edu/webmonkeys/2011/examples/php/RandomInt.php. The username textbox has a unique ID of "login-username". Likewise, the password textbox has a unique ID of "login-password".
  4. If the retrieved status is "success", display the element with ID "login-success" and insert the login message into the paragraph element with ID "login-success-message".
  5. Else, the retrieved status is "failure." Display the element with ID "login-error" and insert the login error message into the paragraph element with ID "login-error-message".

If you are curious as to what the PHP script looks like, you can see it here.