You are on page 1of 149

JavaScript & Ajax

Joel Boonstra / Agathon Group
Bootcamp '08

http://agathongroup.com/talks/bootcamp08/

1

What We'll Be Covering




JavaScript
Ajax: DOM, Events, and XMLHttpRequest
Enhancing our demo site
jQuery
Your Time

2

JavaScript

3

but can be used well JavaScript and CSS are friends 4 .• • • JavaScript is not Java • • JavaScript is a powerful language JavaScript can be used beyond the browser JavaScript has been abused.

The Basics 5 .

crockford. </script> http://javascript.js"></script> <script> var foo = {}.html 6 .How to include <script src="file.com/script.

html 7 .com/script.How Not to Include <script src="file. // --> </script> http://javascript.crockford.js" language="javascript"></script> <script type="text/javascript" language="JavaScript"> <!-var foo = {}.

Syntax • • lines end with semicolons • • line comments start with // variable and function names are casesensitive. and can't contain spaces or dashes block comments surround code with /* */ 8 .

Basic Variables • • • • Strings contain zero or more characters Numbers can be integers or decimals Boolean values are true or false Variables can change type 9 .

// boolean values--no quotes! var bool1 = true. var string2 = 'Single quotes work'. var num2 = -10.1 2 3 4 5 6 7 8 9 10 11 12 13 14 // numbers don't get quotes var num1 = 4. // variables don't need to have a value var empty. // strings are surrounded by quotes var string1 = "This is a string". var bool2 = false. 10 .5.

Comparisons. Tests & Math 11 .

} else { alert("At least one is falsey") } 12 .1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 /* block quotes can span several lines and are useful for commenting out chunks of code */ // test a value var num1 = 5. var num2 = 0. if (num1) { alert("num1 is truthy"). } // test multiple if (num1 && num2) { alert("Both are truthy").

Things that are false • • • • • • "" (empty string) false 0 (the number) null undefined NaN 13 .

. " ". "false". "0".g.Things that are true • • Everything else e. [] 14 .

1 2 3 4 5 6 7 8 var a = "0". b = 0. } 15 . c = 10. } else { alert("They're different!"). // equality if (a == b) { alert("They're the same!").

} 15 . } else { alert("They're different!").1 2 3 4 5 6 7 8 var a = "0". // equality if (a == b) { alert("They're the same!"). c = 10. b = 0.

} // identity if (a === b) { alert("They're identical!"). } 15 . } else { alert("They're different!"). // equality if (a == b) { alert("They're the same!").1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 var a = "0". } else { alert("They're different!"). c = 10. b = 0.

b = 0. // equality if (a == b) { alert("They're the same!"). } 15 . c = 10. } else { alert("They're different!").1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 var a = "0". } else { alert("They're different!"). } // identity if (a === b) { alert("They're identical!").

b = 0. } else { alert("They're different!"). } 15 . } // identity if (a === b) { alert("They're identical!"). } if (b < c) { alert("b is less!"). c = 10. // equality if (a == b) { alert("They're the same!").1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 var a = "0". } else { alert("They're different!").

} if (b < c) { alert("b is less!").1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 var a = "0". } else { alert("They're different!"). } else { alert("They're different!"). } // identity if (a === b) { alert("They're identical!"). // equality if (a == b) { alert("They're the same!"). c = 10. b = 0. } 15 .

} // identity if (a === b) { alert("They're identical!"). } if (b < c) { alert("b is less!"). } else { alert("They're different!"). c = 10. } 15 . // equality if (a == b) { alert("They're the same!"). b = 0.1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 var a = "0". } else { alert("They're different!").

strings to numbers 16 ..g. and do automatic • identity is more strict. but less error-prone and value conversion from. Equality • === and !== test identity. e. they check type • == and != test value only.Identity vs.

4. var a = 10 + var b = 20 var c = 30 * subtraction 5.1 2 3 4 // addition. 17 . 10.

alert(result). var a = 10 + var b = 20 var c = 30 * subtraction 5. // be careful when adding var d = '10'. var e = '15'.1 2 3 4 5 6 7 8 9 10 // addition. var result = d + e. 17 . 10. 4.

var e = '15'. var result = d + e. 4. var a = 10 + var b = 20 var c = 30 * subtraction 5. // be careful when adding var d = '10'. 10.1 2 3 4 5 6 7 8 9 10 // addition. 17 . alert(result).

var result = d + e. alert(result). var a = 10 + var b = 20 var c = 30 * subtraction 5. var e = '15'. alert(result2). // be sure you're adding numbers var result2 = Number(d) + Number(e). 10.1 2 3 4 5 6 7 8 9 10 11 12 13 14 // addition. 17 . 4. // be careful when adding var d = '10'.

// be sure you're adding numbers var result2 = Number(d) + Number(e). var e = '15'. alert(result). 17 . var result = d + e.1 2 3 4 5 6 7 8 9 10 11 12 13 14 // addition. 4. 10. // be careful when adding var d = '10'. var a = 10 + var b = 20 var c = 30 * subtraction 5. alert(result2).

alert(result).1 2 3 4 5 6 7 8 9 10 11 12 13 14 // addition. // be careful when adding var d = '10'. alert(result2). var result = d + e. // be sure you're adding numbers var result2 = Number(d) + Number(e). 10. var a = 10 + var b = 20 var c = 30 * subtraction 5. 4. var e = '15'. 17 .

or by looping 18 .Arrays • • • • Arrays contain a list of items Arrays start counting at zero Arrays can grow and shrink as needed Items in an array are accessed by numbers.

19 .

')).join('. alert(names. 19 . 'Topher'. 'Crystal'].1 2 3 4 5 6 // arrays can be created with stuff in them var names = ['Jeff'. // and can have things added names.push('Richard').

1
2
3
4
5
6

// arrays can be created with stuff in them
var names = ['Jeff', 'Topher', 'Crystal'];
// and can have things added
names.push('Richard');
alert(names.join('; '));

19

1
2
3
4
5
6
7
8
9

// arrays can be created with stuff in them
var names = ['Jeff', 'Topher', 'Crystal'];
// and can have things added
names.push('Richard');
alert(names.join('; '));
// we can get just one item from an array
alert(names[1]);

19

1
2
3
4
5
6
7
8
9

// arrays can be created with stuff in them
var names = ['Jeff', 'Topher', 'Crystal'];
// and can have things added
names.push('Richard');
alert(names.join('; '));
// we can get just one item from an array
alert(names[1]);

19

2. { key: 'value' } ]. alert(misc[2]).1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 // arrays can be created with stuff in them var names = ['Jeff'. // we can get just one item from an array alert(names[1]). // and can have things added names. 19 . 'Crystal']. 'Topher'. ')).join('. alert(names. // arrays can contain whatever var misc = [ 'some string'.push('Richard').

alert(names. 19 . // and can have things added names.push('Richard'). // arrays can contain whatever var misc = [ 'some string'. // we can get just one item from an array alert(names[1]). ')). { key: 'value' } ]. 'Topher'. 2.join('.1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 // arrays can be created with stuff in them var names = ['Jeff'. alert(misc[2]). 'Crystal'].

push('Richard'). // or they can be empty var nothing = [].join('. // arrays can contain whatever var misc = [ 'some string'. alert(names.1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 // arrays can be created with stuff in them var names = ['Jeff'. 'Topher'. 19 . alert(misc[2]). // we can get just one item from an array alert(names[1]). 2. ')). 'Crystal']. // and can have things added names. { key: 'value' } ].

20 .1 // build an array with some values 2 var finishers = [ 3 'Bolt'. pos. results = ''. finisher. 'Thompson'. 'Dix' 4 ].

5 6 // loop through and keep track of results 7 for (var i = 0. i < finishers. pos.length. i++) { 8 finisher = finishers[i]. results = ''. finisher.1 // build an array with some values 2 var finishers = [ 3 'Bolt'. 11 } 20 . 'Thompson'. 'Dix' 4 ]. 9 pos = i + 1. 10 results += finisher + " finished in position " + pos + '\n'.

i < finishers. results = ''. 9 pos = i + 1. 10 results += finisher + " finished in position " + pos + '\n'. 20 . 'Dix' 4 ]. 'Thompson'. 11 } 12 alert(results).1 // build an array with some values 2 var finishers = [ 3 'Bolt'.length. i++) { 8 finisher = finishers[i]. 5 6 // loop through and keep track of results 7 for (var i = 0. pos. finisher.

results = ''. 9 pos = i + 1. 'Thompson'.1 // build an array with some values 2 var finishers = [ 3 'Bolt'. 11 } 12 alert(results). 5 6 // loop through and keep track of results 7 for (var i = 0.length. 'Dix' 4 ]. 20 . 10 results += finisher + " finished in position " + pos + '\n'. i < finishers. finisher. i++) { 8 finisher = finishers[i]. pos.

Functions • • functions can have a name or be anonymous • functions can have their own "scope" functions can be passed around like other variables 21 .

1 2 3 4 5 6 // functions return values var num = 4. 3). function cubeIt(number) { return Math.pow(number. } var cube = cubeIt(num). 22 .

alert(cube).pow(number. function cubeIt(number) { return Math. 3). } var cube = cubeIt(num).1 2 3 4 5 6 7 // functions return values var num = 4. 22 .

alert(cube).pow(number. function cubeIt(number) { return Math. } var cube = cubeIt(num). 22 . 3).1 2 3 4 5 6 7 // functions return values var num = 4.

inside. alert(cube).'. outside. alert(string1).1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 // functions return values var num = 4.pow(number. // functions have their own private scope var string1 = 'string1. outside. 3). var printGlobal = function () { var string2 = 'string2.'. function cubeIt(number) { return Math. } 22 . } var cube = cubeIt(num).'. alert(string2). var string2 = 'string2.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

// functions return values
var num = 4;
function cubeIt(number) {
return Math.pow(number, 3);
}
var cube = cubeIt(num);
alert(cube);
// functions have their own private scope
var string1 = 'string1, outside.';
var string2 = 'string2, outside.';
var printGlobal = function () {
var string2 = 'string2, inside.';
alert(string1);
alert(string2);
}
printGlobal();

22

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

// functions return values
var num = 4;
function cubeIt(number) {
return Math.pow(number, 3);
}
var cube = cubeIt(num);
alert(cube);
// functions have their own private scope
var string1 = 'string1, outside.';
var string2 = 'string2, outside.';
var printGlobal = function () {
var string2 = 'string2, inside.';
alert(string1);
alert(string2);
}
printGlobal();

22

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

// functions return values
var num = 4;
function cubeIt(number) {
return Math.pow(number, 3);
}
var cube = cubeIt(num);
alert(cube);
// functions have their own private scope
var string1 = 'string1, outside.';
var string2 = 'string2, outside.';
var printGlobal = function () {
var string2 = 'string2, inside.';
alert(string1);
alert(string2);
}
printGlobal();

22

outside. function cubeIt(number) { return Math.'.'. alert(cube). 22 . alert(string1). alert(string2).pow(number. 3). var string2 = 'string2. } var cube = cubeIt(num). inside.'.1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 // functions return values var num = 4. outside. // functions have their own private scope var string1 = 'string1. } printGlobal(). var printGlobal = function () { var string2 = 'string2.

' + who).1 // functions can be assigned like variables 2 var sayHi = function (who) { 3 alert('Hello. 4 } 23 .

1 2 3 4 5 // functions can be assigned like variables var sayHi = function (who) { alert('Hello. ' + who). 23 . } sayHi('Joel').

1
2
3
4
5

// functions can be assigned like variables
var sayHi = function (who) {
alert('Hello, ' + who);
}
sayHi('Joel');

23

1
2
3
4
5
6
7
8
9
10

// functions can be assigned like variables
var sayHi = function (who) {
alert('Hello, ' + who);
}
sayHi('Joel');
// functions can be passed like variables
var sayBye = function () {
alert('Bye');
}

23

1
2
3
4
5
6
7
8
9
10
11

// functions can be assigned like variables
var sayHi = function (who) {
alert('Hello, ' + who);
}
sayHi('Joel');
// functions can be passed like variables
var sayBye = function () {
alert('Bye');
}
setTimeout(sayBye, 3000);

23

' + who). } setTimeout(sayBye. 3000). // functions can be passed like variables var sayBye = function () { alert('Bye').1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 // functions can be assigned like variables var sayHi = function (who) { alert('Hello. 23 . // functions don't even need names setTimeout(function () { sayHi('Kedron'). 6000). } sayHi('Joel'). }.

3000). ' + who). } setTimeout(sayBye. // functions don't even need names setTimeout(function () { sayHi('Kedron'). // functions can be passed like variables var sayBye = function () { alert('Bye'). } sayHi('Joel'). 23 . 6000). }.1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 // functions can be assigned like variables var sayHi = function (who) { alert('Hello.

arrays. with a bit more power. • • Most things in JavaScript are actually objects. • Objects map keys to values. including more objects. values can be whatever you like. functions. 24 .Objects • Objects are also containers. like arrays. Keys must be strings. The browser provides some objects. and we can create our own.

1 // objects are initialized like arrays 2 var directory = { 3 peter: 81. 25 . 5 alan: 83 6 }. ext = null. 4 joel: 82.

ext = null. alan: 83 }. alert('Call ' + person + ' at x' + ext)..1 2 3 4 5 6 7 8 9 10 11 12 13 // objects are initialized like arrays var directory = { peter: 81.in loop lets us access the // object's data for (person in directory) { ext = directory[person]. joel: 82. // the for. } 25 .

. alan: 83 }. joel: 82.in loop lets us access the // object's data for (person in directory) { ext = directory[person]. } 25 .1 2 3 4 5 6 7 8 9 10 11 12 13 // objects are initialized like arrays var directory = { peter: 81. // the for. ext = null. alert('Call ' + person + ' at x' + ext).

ext = null. alan: 83 }.1 2 3 4 5 6 7 8 9 10 11 12 13 // objects are initialized like arrays var directory = { peter: 81.in loop lets us access the // object's data for (person in directory) { ext = directory[person]. joel: 82. // the for. alert('Call ' + person + ' at x' + ext). } 25 ..

1 2 3 4 5 6 7 8 9 10 11 12 13 // objects are initialized like arrays var directory = { peter: 81. ext = null.in loop lets us access the // object's data for (person in directory) { ext = directory[person]. // the for.. alan: 83 }. joel: 82. alert('Call ' + person + ' at x' + ext). } 25 .

alert('Call ' + person + ' at x' + ext).in loop lets us access the // object's data for (person in directory) { ext = directory[person].. ext = null. 25 .some = 'some value'.1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 // objects are initialized like arrays var directory = { peter: 81. alan: 83 }. } // objects can be created empty. and then // added to var stillNone = {}. stillNone. joel: 82. // the for.

'evil'] 5 }. word. 4 bad: ['terrible'. synonym.1 // objects can contain other stuff 2 var thesaurus = { 3 good: ['great'. 'awesome']. 26 .

bad: ['terrible'.1 2 3 4 5 6 7 8 9 // objects can contain other stuff var thesaurus = { good: ['great'. synonym. for (word in thesaurus) { synonym = thesaurus[word]. alert(word + ' synonyms: ' + synonym).join(' and '). 'awesome']. } 26 . word. 'evil'] }.

} 26 . bad: ['terrible'.1 2 3 4 5 6 7 8 9 // objects can contain other stuff var thesaurus = { good: ['great'. for (word in thesaurus) { synonym = thesaurus[word].join(' and '). synonym. alert(word + ' synonyms: ' + synonym). 'evil'] }. 'awesome']. word.

for (word in thesaurus) { synonym = thesaurus[word]. 'evil'] }.join(' and ').1 2 3 4 5 6 7 8 9 // objects can contain other stuff var thesaurus = { good: ['great'. synonym. } 26 . alert(word + ' synonyms: ' + synonym). word. bad: ['terrible'. 'awesome'].

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 // objects can contain other stuff var thesaurus = { good: ['great'. 'awesome']. alert(word + ' synonyms: ' + synonym). word. 'evil'] }. bye : function () { alert('bye!'). } }. } // objects can contain functions var talker = { hi : function () { alert('hi!'). }. 26 .join(' and '). bad: ['terrible'. synonym. for (word in thesaurus) { synonym = thesaurus[word].

for (word in thesaurus) { synonym = thesaurus[word].join(' and '). bad: ['terrible'. setTimeout(talker. 'awesome']. bye : function () { alert('bye!'). 26 . setTimeout(talker. alert(word + ' synonyms: ' + synonym). } // objects can contain functions var talker = { hi : function () { alert('hi!').bye. 3000). 6000). 'evil'] }. } }. synonym.hi. }.1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 // objects can contain other stuff var thesaurus = { good: ['great'. word.

• In browsers. google maps.) share the same global scope when included. • External scripts (flickr.Scope • Unless declared with var inside a function. a variable is global. etc. global variables belong to the browser-provided window object. 27 .

variables // belong to the window object var string1 = 'Global string'. 28 .1 2 3 4 5 6 // when not inside a function. // not using 'var' implies global string2 = 'Another'.

28 . var string4 = 'Not global'. // not using 'var' implies global string2 = 'Another'. // even inside functions function testFunc() { string3 = 'Also global'.1 2 3 4 5 6 7 8 9 10 11 12 13 // when not inside a function. variables // belong to the window object var string1 = 'Global string'. } testFunc().

// even inside functions function testFunc() { string3 = 'Also global'. // string3 bled through. variables // belong to the window object var string1 = 'Global string'. var string4 = 'Not global'. alert(string4). } testFunc(). // not using 'var' implies global string2 = 'Another'.1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 // when not inside a function. 28 . string4 is gone alert(string3).

string4 is gone alert(string3). var string4 = 'Not global'.1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 // when not inside a function. 28 . } testFunc(). alert(string4). variables // belong to the window object var string1 = 'Global string'. // not using 'var' implies global string2 = 'Another'. // string3 bled through. // even inside functions function testFunc() { string3 = 'Also global'.

} testFunc(). // string3 bled through. 28 . alert(string4). string4 is gone alert(string3). // even inside functions function testFunc() { string3 = 'Also global'. // not using 'var' implies global string2 = 'Another'. variables // belong to the window object var string1 = 'Global string'.1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 // when not inside a function. var string4 = 'Not global'.

• Closures are a nice antidote to global variables.Closure • Functions can remember variables after their execution has ended. • Variables in closure are available only to the function. not outside. 29 .

return function () { alert(storage).1 2 3 4 5 6 7 8 // functions remember their variables // even after they're done running var remember = function (what) { var storage = "I'm remembering " + what. }. }. 30 .

1 2 3 4 5 6 7 8 9 // functions remember their variables // even after they're done running var remember = function (what) { var storage = "I'm remembering " + what. return function () { alert(storage). 30 . var memory = remember('a secret'). }. }.

}. setTimeout(memory. var memory = remember('a secret'). 3000).1 2 3 4 5 6 7 8 9 10 // functions remember their variables // even after they're done running var remember = function (what) { var storage = "I'm remembering " + what. }. return function () { alert(storage). 30 .

}. 30 . 3000). setTimeout(memory. return function () { alert(storage).1 2 3 4 5 6 7 8 9 10 // functions remember their variables // even after they're done running var remember = function (what) { var storage = "I'm remembering " + what. }. var memory = remember('a secret').

15-34 31 .pp.

Sidetrack: Developing JavaScript 32 .

• • • • Essential Firefox addon Seriously Let's give it a try http://getfirebug.com/ 33 .

com/ blackbirdjs/ 34 .gscottolson.No Firefox? • • Re-consider • • Safari has a developer console IE7 has a decent developer toolbar for debugging in a pinch Blackbird: http://www.

Ajax (finally) 35 .

an acronym for Asynchronous JavaScript and XML • • Doesn't necessarily use XML Not necessarily Asynchronous 36 .What is Ajax? • At one point.

Discuss 37 .

What is Ajax? • A collection of technologies for adding rich interaction to a website. • • • • DOM interaction / manipulation Responding to events Webserver interaction Quick demo 38 .

DOM Interaction / Manipulation 39 .

</p> <h2>Second-level header</h2> <h2>Another second-level header</h2> </body> </html> view 40 .1 2 3 4 5 6 7 8 9 10 11 12 <html> <head> <title>DOM test</title> </head> <body> <h1 id="main">Main Header</h1> <p><b>Welcome</b> to the test.

41 .

Useful.getElementsByTagName('h2') document.createTextNode('hello') http://quirksmode.html 42 .createElement('p') document.org/dom/w3c_core.getElementById('main') document. compatible methods • • • • document.

document.getElementById('main'). 43 .

</script> </body> view 44 .getElementById('main').log(header).1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 <html> <head> <title>DOM test</title> </head> <body> <h1 id="main">Main Header</h1> <p><b>Welcome</b> to the test.</p> <h2>Second-level header</h2> <h2>Another second-level header</h2> <script> var header = document. // Firebug logging console.

45 .getElementsByTagName('h2').document.

</script> </body> view 46 .</p> <h2>Second-level header</h2> <h2>Another second-level header</h2> <script> var h2s = document.log(h2s).1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 <html> <head> <title>DOM test</title> </head> <body> <h1 id="main">Main Header</h1> <p><b>Welcome</b> to the test. // Firebug logging console.getElementsByTagName('h2').

createElement('p').document. 47 .

</script> </body> view 48 .1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 <html> <head> <title>DOM test</title> </head> <body> <h1 id="main">Main Header</h1> <p><b>Welcome</b> to the test.createElement('p').log(para). // Firebug logging console.</p> <h2>Second-level header</h2> <h2>Another second-level header</h2> <script> var para = document.

createTextNode('A new paragraph'). 49 .document.

</p> <h2>Second-level header</h2> <h2>Another second-level header</h2> <script> var text = document. console.log(text).1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 <html> <head> <title>DOM test</title> </head> <body> <h1 id="main">Main Header</h1> <p><b>Welcome</b> to the test.createTextNode( 'A new paragraph' ). </script> </body> </html> view 50 .

para.appendChild(text). 51 .

console. para.11 12 13 14 15 16 17 18 <script> var para = document.createTextNode( 'A new paragraph' ).log(para).createElement('p').appendChild(text). </script> view 52 . var text = document.

53 .

54 .

var text = document.12 13 14 15 16 17 18 19 // create the paragraph and text nodes var para = document. // add the text to the paragraph para.createTextNode( 'A new paragraph' ).createElement('p'). view 55 .appendChild(text).

12 13 14 15 16 17 18 19 20 21 22 23 // create the paragraph and text nodes var para = document. // add the text to the paragraph para.appendChild(text).createTextNode( 'A new paragraph' ). var text = document.getElementsByTagName('body')[0]. // fetch the body element var body = document. view 55 .createElement('p').

view 55 .12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 // create the paragraph and text nodes var para = document. 4000). // add the text to the paragraph para.appendChild(para). // fetch the body element var body = document. // after 4 seconds.getElementsByTagName('body')[0]. var text = document.appendChild(text).createTextNode( 'A new paragraph' ).createElement('p'). }. append our new paragraph setTimeout(function () { body.

More Manipulation • • • • • • getAttribute('href') setAttribute('class'. 'newClass') parentNode previousSibling nextSibling nodeValue 56 .

</p> <p>This is not. } </style> </head> <body> <h1 id="main">Main Header</h1> <p class="special">This is special.special { font-weight: bold.1 2 3 4 5 6 7 8 9 10 11 12 13 <html> <head> <style type="text/css"> . color: red.</p> </body> </html> view 57 .

view 58 .getElementsByTagName('p')[1].getElementById('main').13 // get our elements 14 var main = document. 15 var p = 16 document.

// wait 3 seconds to set main's class setTimeout(function () { main.setAttribute('class'. var p = document. view 58 .getElementById('main'). 3000). }. 'special').13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 // get our elements var main = document.getElementsByTagName('p')[1].

setAttribute('class'. 3000).13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 // get our elements var main = document. // then wait another 3 to set p's setTimeout(function () { p. var p = document.getElementsByTagName('p')[1]. view 59 . 'special').setAttribute('class'.getElementById('main'). }. // wait 3 seconds to set main's class setTimeout(function () { main. 'special'). }. 3000).

pp. 34-43 60 .

Events 61 .

org/dom/events/index.html 62 .Events: When Stuff Happens • • • • • onclick onsubmit onload setTimeout() / clearTimeout() setInterval() / clearInterval() http://quirksmode.

</h1> <ul> <li><a href="dom_08.dom_09.html">Next</a></li> </ul> </body> </html> 63 .html">Previous</a></li> <li><a href="dom_10.js"></script> </head> <body> <h1>Testing events.html 1 2 3 4 5 6 7 8 9 10 11 12 13 <html> <head> <title>Events</title> <script src="dom_09.

onload = function () { view 64 .js 1 window.dom_09.

onload = function () { 2 var links = 3 document. view 64 .js 1 window.getElementsByTagName('a').dom_09.

i++) { 5 links[i].js 1 window. 6 } 7 }.getElementsByTagName('a').onclick = clicker. 4 for (i = 0. view 64 .dom_09.length. i < links.onload = function () { 2 var links = 3 document.

js 1 2 3 4 5 6 7 8 9 10 11 12 window.onclick = clicker.onload = function () { var links = document. } }. for (i = 0.href). var clicker = function () { alert('You clicked ' + this. i < links.getElementsByTagName('a').dom_09. }. return false. view 64 .length. i++) { links[i].

dom_10.js"></script> <title>Timeout/Interval testing</title> <style> p { color: blue.html 1 2 3 4 5 6 7 8 9 10 11 12 13 <html> <head> <script src="dom_10. } </style> </head> <body> <h1>New paragraphs will appear below</h1> <div id="test"></div> </body> </html> 65 .

js 1 var div.dom_10. 2 para = '<p>new paragraph!</p>'. view 66 .

dom_10.onload = function () { 4 div = document.getElementById('test'). view 66 . 3 window.js 1 var div. 2 para = '<p>new paragraph!</p>'.

dom_10. 500).onload = function () { 4 div = document. 3 window. 2 para = '<p>new paragraph!</p>'. 5 6 // run a function every half-second 7 var i = setInterval(addpara. view 66 .js 1 var div.getElementById('test').

12 clearInterval(i). 4000).js 1 var div. 5 6 // run a function every half-second 7 var i = setInterval(addpara. 14 }.getElementById('test'). 500). 2 para = '<p>new paragraph!</p>'. 3 window.dom_10.log('all done'). 13 }. 8 9 // clear it out after four seconds 10 setTimeout(function () { 11 console. view 66 .onload = function () { 4 div = document.

innerHTML += para. clearInterval(i). // run a function every half-second var i = setInterval(addpara.log('all done'). view 66 . 4000).onload = function () { div = document.getElementById('test'). }.dom_10. var addpara = function () { div. }. para = '<p>new paragraph!</p>'. window.js 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 var div. }. 500). // clear it out after four seconds setTimeout(function () { console.

XMLHttpRequest (xhr) 67 .

screen readers 68 . reloading.xhr • Fetches content from the server without reloading the browser • Response from the server can be handled in a variety of ways • Restricted to same domain as browser window • Potential for significant abuse. could break the back button.

html 1 2 3 4 5 6 7 8 9 10 11 <html> <head> <script src="js/xhr.js"></script> <title>XHR testing</title> </head> <body> <h1>Results will go below</h1> <div id="results"></div> </body> </html> 69 .js"></script> <script src="ajax_01.ajax_01.

view 70 .ajax_01.onload = function () { 2 var xhr = getXHR().js 1 window.

js 1 window. view 70 .ajax_01.onreadystatechange = changer.onload = function () { 2 var xhr = getXHR(). 3 if (xhr) { 4 // what to do when things happen 5 xhr.

ajax_01.onreadystatechange = changer. 'result2.onload = function () { 2 var xhr = getXHR().open('GET'. 3 if (xhr) { 4 // what to do when things happen 5 xhr. 9 true). 6 7 // the URL we want to go to 8 xhr.html'.js 1 window. view 70 .

open('GET'.onload = function () { 2 var xhr = getXHR().onreadystatechange = changer. 13 } 14 } view 70 .send(null). 10 11 // perform the request 12 xhr. 9 true).js 1 window.html'. 'result2. 3 if (xhr) { 4 // what to do when things happen 5 xhr.ajax_01. 6 7 // the URL we want to go to 8 xhr.

if (xhr) { // what to do when things happen xhr.onreadystatechange = changer. view 70 . } var changer = function () { }.ajax_01. // the URL we want to go to xhr.html'. true). } // perform the request xhr. 'result2.send(null).js 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 window.open('GET'.onload = function () { var xhr = getXHR().

js 18 // do something.ajax_02. when something happens 19 var changer = function () { view 71 .

js 18 // do something.ajax_02.readyState == 4) { view 71 . when something happens 19 var changer = function () { 20 if (xhr.

readyState == 4) { 21 if (xhr.status == 200) { view 71 .ajax_02. when something happens 19 var changer = function () { 20 if (xhr.js 18 // do something.

when something happens 19 var changer = function () { 20 if (xhr.innerHTML = 23 xhr.status == 200) { 22 div.js 18 // do something. view 71 .ajax_02.readyState == 4) { 21 if (xhr.responseText.

ajax_02.js 18 // do something.innerHTML = 23 xhr. 24 } 25 } 26 }. when something happens 19 var changer = function () { 20 if (xhr.status == 200) { 22 div.responseText.readyState == 4) { 21 if (xhr. view 71 .

Is it really that easy? 72 .

Is it really that easy? No 72 .

18 }.1 var getXHR = function () { 2 var xhr = false. 73 . 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 return xhr.

18 }.1 var getXHR = function () { 2 var xhr = false. 5 } 6 7 8 9 10 11 12 13 14 15 16 17 return xhr. 3 if (window. 74 .XMLHttpRequest) { 4 xhr = new XMLHttpRequest().

XMLHttpRequest) { 4 xhr = new XMLHttpRequest(). 3 if (window.XMLHTTP'). 5 } 6 else if (window. 18 }. 14 15 } 16 } 17 return xhr.1 var getXHR = function () { 2 var xhr = false.ActiveXObject) { 7 try { 8 xhr = new ActiveXObject('Msxml2. 9 } catch (e) { 10 11 12 13 xhr = false. 75 .

9 } catch (e) { 10 try { 11 xhr = new ActiveXObject('Microsoft.1 var getXHR = function () { 2 var xhr = false. 76 .XMLHTTP').XMLHttpRequest) { 4 xhr = new XMLHttpRequest(). 3 if (window. 12 } catch (e) { 13 xhr = false. 5 } 6 else if (window. 18 }.XMLHTTP'). 14 } 15 } 16 } 17 return xhr.ActiveXObject) { 7 try { 8 xhr = new ActiveXObject('Msxml2.

open('GET'.1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 var xhr = getXHR(). view 77 .php'.getElementById('results') if (xhr) { xhr.readyState == 4) { if (xhr. true). when something happens var changer = function () { if (xhr. } } }. xhr. } div..send(null).status == 200) { div. div. } // do something. xhr. window.innerHTML += '<p>Waiting.onload = function () { div = document.innerHTML = xhr.responseText.onreadystatechange = changer.</p>'. 'php/slow..

47-65 78 .pp.

Tomorrow • • • Enhancing our site jQuery Your Time 79 .