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!
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 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 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;
}
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
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;
};
}
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.
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
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.
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.
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.
For this activity, you will need to flip a coin at random and display the correct picture. Here are your instructions.
If you are curious as to what the PHP script looks like, you can see it here.
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".
If you are curious as to what the PHP script looks like, you can see it here.