Web Programming Step by Step

Chapter 7
JavaScript for Interactive Web Pages

Except where otherwise noted, the contents of this presentation are Copyright 2009 Marty Stepp and Jessica Miller.

Valid XHTML 1.1 Valid CSS!

7.1: Key JavaScript Concepts

What is JavaScript? (7.1)

JavaScript vs. Java

Java + mary jane, da endo, aight = JavaScript

JavaScript vs. PHP

JS <3 php

Client-side scripting (7.1.1)

client-side scripting

Why use client-side programming?

PHP already allows us to create dynamic web pages. Why also use a client-side language like JavaScript?

Event-driven programming

event

Buttons: <button>

the most common clickable UI control (inline)

<button>Click me!</button>

Linking to a JavaScript file: script

<script src="filename" type="text/javascript"></script>
<script src="example.js" type="text/javascript"></script>

A JavaScript statement: alert

alert("message");
alert("IE6 detected.  Suck-mode enabled.");
alert

JavaScript functions

function name() {
	statement ;
	statement ;
	...
	statement ;
}
function myFunction() {
	alert("Hello!");
	alert("How are you?");
}

Event handlers

<element attributes onclick="function();">...
<button onclick="myFunction();">Click me!</button>

Document Object Model (DOM) (7.1.4)

a set of JavaScript objects that represent each element on the page

DOM

Accessing elements: getElementById

var name = document.getElementById("id");
<button onclick="myFunction2();">Click me!</button>
<span id="output">replace me</span>
function myFunction2() {
	var span = document.getElementById("output");
	span.innerHTML = "Hello, how are you?";
}

7.2: JavaScript Syntax

Variables and types (7.2.1, 7.2.3)

var name = expression;
var clientName = "Connie Client";
var age = 32;
var weight = 127.4;

Number type (7.2.2)

var enrollment = 99;
var medianGrade = 2.8;
var credits = 5 + 4 + (2 * 3);

Comments (same as Java) (7.2.4)

// single-line comment

/* multi-line comment */

DOM object properties (7.2.5)

<div id="main" class="foo bar">
	<p>Hello, <em>very</em> happy to see you!</p>
	<img id="icon" src="images/borat.jpg" alt="Borat" />
</div>
var div = document.getElementById("main");
var image = document.getElementById("icon");

DOM properties for other elements

<input id="studentid" type="text" size="7" maxlength="7" />
<input id="freshman" type="checkbox" checked="checked" /> Freshman?
var sid = document.getElementById("studentid");
var frosh = document.getElementById("freshman");

Debugging common errors (7.2.6)

Debugging JS code in Firebug

Firebug JS

JSLint

JSLint

Debugging checklist

"My program does nothing"

Since Javascript has no compiler, many errors will cause your Javascript program to just "do nothing." Some questions you should ask when this happens:

Is my JS file loading?

Is it reaching the code I want it to run?

Object 'foo' has no properties

Common bug: bracket mismatches

function foo() {
	...   // missing closing curly brace!

function bar() {
	...
}

String type (7.2.7)

var s = "Connie Client";
var fName = s.substring(0, s.indexOf(" "));   // "Connie"
var len = s.length;                           // 13
var s2 = 'Melvin Merchant';

More about String

for loop (same as Java) (7.2.8)

for (initialization; condition; update) {
	statements;
}
var sum = 0;
for (var i = 0; i < 100; i++) {
	sum = sum + i;
}
var s1 = "hello";
var s2 = "";
for (var i = 0; i < s.length; i++) {
	s2 += s1.charAt(i) + s1.charAt(i);
}
// s2 stores "hheelllloo"

Math object (7.2.9)

var rand1to10 = Math.floor(Math.random() * 10 + 1);
var three = Math.floor(Math.PI);

Special values: null and undefined (7.2.10)

var ned = null;
var benson = 9;

// at this point in the code,
//   ned is null
//   benson's 9
//   caroline is undefined

7.3: Program Logic

Logical operators (7.3.1, 7.3.4)

if/else statement (same as Java) (7.3.2)

if (condition) {
	statements;
} else if (condition) {
	statements;
} else {
	statements;
}

Boolean type (7.3.3)

var iLike190M = true;
var ieIsGood = "IE6" > 0;   // false
if ("web dev is great") {  /* true */ }
if (0) {  /* false */ }

while loops (same as Java) (7.3.5)

while (condition) {
	statements;
}
do {
	statements;
} while (condition);

7.4: Advanced JavaScript Syntax

Scope, global and local variables (7.4.1)

// global code; like "main"
var count = 1;
f2();
f1();

function f1() { 
	var x = 999;
	count = count * 10;
}
function f2() { count++; }

Function parameters/return (7.4.3)

function name(parameterName, ..., parameterName) {
	statements;
	return expression;
}
function quadratic(a, b, c) {
	return -b + Math.sqrt(b * b - 4 * a * c) / (2 * a);
}

Calling functions (same as Java)

name(parameterValue, ..., parameterValue);
var root = quadratic(1, -3, 2);

Common bug: spelling error

function foo() {
	Bar();   // capitalized wrong
...
function bar() {
	...
}

Arrays (7.4.2)

var name = [];                          // empty array
var name = [value, value, ..., value];   // pre-filled
name[index] = value;                     // store element
var ducks = ["Huey", "Dewey", "Louie"];

var stooges = [];        // stooges.length is 0
stooges[0] = "Larry";    // stooges.length is 1
stooges[1] = "Moe";      // stooges.length is 2
stooges[4] = "Curly";    // stooges.length is 5
stooges[4] = "Shemp";    // stooges.length is 5

Array methods

var a = ["Stef", "Jason"];   // Stef, Jason
a.push("Brian");             // Stef, Jason, Brian
a.unshift("Kelly");          // Kelly, Stef, Jason, Brian
a.pop();                     // Kelly, Stef, Jason
a.shift();                   // Stef, Jason
a.sort();                    // Jason, Stef

Splitting strings: split and join

var s = "the quick brown fox";
var a = s.split(" ");          // ["the", "quick", "brown", "fox"]
a.reverse();                   // ["fox", "brown", "quick", "the"]
s = a.join("!");               // "fox!brown!quick!the"

Popup boxes (7.4.4)

alert("message");     // message
confirm("message");   // returns true or false
prompt("message");    // returns user input string
alert confirm prompt

Extra random JavaScript stuff

JavaScript in HTML body (example)

<script type="text/javascript">
	JavaScript code
</script>

The typeof function

typeof(value)

The arguments array

function example() {
	for (var i = 0; i < arguments.length; i++) {
		alert(arguments[i]);
	}
}

example("how", "are", "you");   // alerts 3 times

The "for each" loop

for (var name in arrayOrObject) {
	do something with arrayOrObject[name];
}

Associative arrays / maps

var map = [];
map[42] = "the answer";
map[3.14] = "pi";
map["champ"] = "suns";

Date object

var today = new Date();               // today
var midterm = new Date(2007, 4, 4);   // May 4, 2007

Injecting Dynamic Text: document.write

document.write("message");

The eval (evil?) function

eval("JavaScript code");
eval("var x = 7; x++; alert(x / 2);");  // alerts 4
Dr. Evil