Vous êtes sur la page 1sur 149

JavaScript & Ajax

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

Joel Boonstra / Agathon Group Bootcamp '08

What We'll Be Covering



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

JavaScript

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

The Basics

How to include
<script src="file.js"></script> <script> var foo = {}; </script>

http://javascript.crockford.com/script.html
6

How Not to Include


<script src="file.js" language="javascript"></script> <script type="text/javascript" language="JavaScript"> <!-var foo = {}; // --> </script>

http://javascript.crockford.com/script.html
7

Syntax

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

Basic Variables

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

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

// numbers don't get quotes var num1 = 4; var num2 = -10.5; // strings are surrounded by quotes var string1 = "This is a string"; var string2 = 'Single quotes work'; // variables don't need to have a value var empty; // boolean values--no quotes! var bool1 = true; var bool2 = false;

10

Comparisons, Tests & Math

11

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"); } else { alert("At least one is falsey") }

12

Things that are false



""

(empty string)

false 0

(the number)

null undefined NaN

13

Things that are true

Everything else e.g., "0", "false", "


", []

14

1 2 3 4 5 6 7 8

var a = "0", b = 0, c = 10; // equality if (a == b) { alert("They're the same!"); } else { alert("They're different!"); }

15

1 2 3 4 5 6 7 8

var a = "0", b = 0, c = 10; // equality if (a == b) { alert("They're the same!"); } else { alert("They're different!"); }

15

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

var a = "0", b = 0, c = 10; // equality if (a == b) { alert("They're the same!"); } else { alert("They're different!"); } // identity if (a === b) { alert("They're identical!"); } else { alert("They're different!"); }

15

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

var a = "0", b = 0, c = 10; // equality if (a == b) { alert("They're the same!"); } else { alert("They're different!"); } // identity if (a === b) { alert("They're identical!"); } else { alert("They're different!"); }

15

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

var a = "0", b = 0, c = 10; // equality if (a == b) { alert("They're the same!"); } else { alert("They're different!"); } // identity if (a === b) { alert("They're identical!"); } else { alert("They're different!"); } if (b < c) { alert("b is less!"); }

15

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

var a = "0", b = 0, c = 10; // equality if (a == b) { alert("They're the same!"); } else { alert("They're different!"); } // identity if (a === b) { alert("They're identical!"); } else { alert("They're different!"); } if (b < c) { alert("b is less!"); }

15

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

var a = "0", b = 0, c = 10; // equality if (a == b) { alert("They're the same!"); } else { alert("They're different!"); } // identity if (a === b) { alert("They're identical!"); } else { alert("They're different!"); } if (b < c) { alert("b is less!"); }

15

Identity vs. Equality



=== and !== test identity; they check type

and value
== and != test value only, and do automatic

conversion from, e.g., strings to numbers identity is more strict, but less error-prone

16

1 2 3 4

// addition, var a = 10 + var b = 20 var c = 30 *

subtraction 5; 10; 4;

17

1 2 3 4 5 6 7 8 9 10

// addition, var a = 10 + var b = 20 var c = 30 *

subtraction 5; 10; 4;

// be careful when adding var d = '10'; var e = '15'; var result = d + e; alert(result);

17

1 2 3 4 5 6 7 8 9 10

// addition, var a = 10 + var b = 20 var c = 30 *

subtraction 5; 10; 4;

// be careful when adding var d = '10'; var e = '15'; var result = d + e; alert(result);

17

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

// addition, var a = 10 + var b = 20 var c = 30 *

subtraction 5; 10; 4;

// be careful when adding var d = '10'; var e = '15'; var result = d + e; alert(result); // be sure you're adding numbers var result2 = Number(d) + Number(e); alert(result2);

17

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

// addition, var a = 10 + var b = 20 var c = 30 *

subtraction 5; 10; 4;

// be careful when adding var d = '10'; var e = '15'; var result = d + e; alert(result); // be sure you're adding numbers var result2 = Number(d) + Number(e); alert(result2);

17

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

// addition, var a = 10 + var b = 20 var c = 30 *

subtraction 5; 10; 4;

// be careful when adding var d = '10'; var e = '15'; var result = d + e; alert(result); // be sure you're adding numbers var result2 = Number(d) + Number(e); alert(result2);

17

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, or by looping

18

19

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

// 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

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', '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]); // arrays can contain whatever var misc = [ 'some string', 2, { key: 'value' } ]; alert(misc[2]);

19

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', '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]); // arrays can contain whatever var misc = [ 'some string', 2, { key: 'value' } ]; alert(misc[2]);

19

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', 'Crystal']; // and can have things added names.push('Richard'); alert(names.join('; ')); // we can get just one item from an array alert(names[1]); // arrays can contain whatever var misc = [ 'some string', 2, { key: 'value' } ]; alert(misc[2]); // or they can be empty var nothing = [];

19

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

20

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

20

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

20

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

20

Functions

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

21

1 2 3 4 5 6

// functions return values var num = 4; function cubeIt(number) { return Math.pow(number, 3); } var cube = cubeIt(num);

22

1 2 3 4 5 6 7

// functions return values var num = 4; function cubeIt(number) { return Math.pow(number, 3); } var cube = cubeIt(num); alert(cube);

22

1 2 3 4 5 6 7

// functions return values var num = 4; function cubeIt(number) { return Math.pow(number, 3); } var cube = cubeIt(num); alert(cube);

22

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

// 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); }

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

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 // functions can be assigned like variables 2 var sayHi = function (who) { 3 alert('Hello, ' + who); 4 }

23

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

// 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

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, ' + who); } sayHi('Joel'); // functions can be passed like variables var sayBye = function () { alert('Bye'); } setTimeout(sayBye, 3000); // functions don't even need names setTimeout(function () { sayHi('Kedron'); }, 6000);

23

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, ' + who); } sayHi('Joel'); // functions can be passed like variables var sayBye = function () { alert('Bye'); } setTimeout(sayBye, 3000); // functions don't even need names setTimeout(function () { sayHi('Kedron'); }, 6000);

23

Objects

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

24

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

25

1 2 3 4 5 6 7 8 9 10 11 12 13

// objects are initialized like arrays var directory = { peter: 81, joel: 82, alan: 83 }, ext = null; // the for..in loop lets us access the // object's data for (person in directory) { ext = directory[person]; 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, joel: 82, alan: 83 }, ext = null; // the for..in loop lets us access the // object's data for (person in directory) { ext = directory[person]; 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, joel: 82, alan: 83 }, ext = null; // the for..in loop lets us access the // object's data for (person in directory) { ext = directory[person]; 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, joel: 82, alan: 83 }, ext = null; // the for..in loop lets us access the // object's data for (person in directory) { ext = directory[person]; alert('Call ' + person + ' at x' + ext); }

25

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, joel: 82, alan: 83 }, ext = null; // the for..in loop lets us access the // object's data for (person in directory) { ext = directory[person]; alert('Call ' + person + ' at x' + ext); } // objects can be created empty, and then // added to var stillNone = {}; stillNone.some = 'some value';

25

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

26

1 2 3 4 5 6 7 8 9

// objects can contain other stuff var thesaurus = { good: ['great', 'awesome'], bad: ['terrible', 'evil'] }, word, synonym; for (word in thesaurus) { synonym = thesaurus[word].join(' and '); alert(word + ' synonyms: ' + synonym); }

26

1 2 3 4 5 6 7 8 9

// objects can contain other stuff var thesaurus = { good: ['great', 'awesome'], bad: ['terrible', 'evil'] }, word, synonym; for (word in thesaurus) { synonym = thesaurus[word].join(' and '); alert(word + ' synonyms: ' + synonym); }

26

1 2 3 4 5 6 7 8 9

// objects can contain other stuff var thesaurus = { good: ['great', 'awesome'], bad: ['terrible', 'evil'] }, word, synonym; for (word in thesaurus) { synonym = thesaurus[word].join(' and '); alert(word + ' synonyms: ' + synonym); }

26

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'], bad: ['terrible', 'evil'] }, word, synonym; for (word in thesaurus) { synonym = thesaurus[word].join(' and '); alert(word + ' synonyms: ' + synonym); } // objects can contain functions var talker = { hi : function () { alert('hi!'); }, bye : function () { alert('bye!'); } };

26

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', 'awesome'], bad: ['terrible', 'evil'] }, word, synonym; for (word in thesaurus) { synonym = thesaurus[word].join(' and '); alert(word + ' synonyms: ' + synonym); } // objects can contain functions var talker = { hi : function () { alert('hi!'); }, bye : function () { alert('bye!'); } }; setTimeout(talker.hi, 3000); setTimeout(talker.bye, 6000);

26

Scope

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

27

1 2 3 4 5 6

// when not inside a function, variables // belong to the window object var string1 = 'Global string'; // not using 'var' implies global string2 = 'Another';

28

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'; // not using 'var' implies global string2 = 'Another'; // even inside functions function testFunc() { string3 = 'Also global'; var string4 = 'Not global'; } testFunc();

28

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

// when not inside a function, variables // belong to the window object var string1 = 'Global string'; // not using 'var' implies global string2 = 'Another'; // even inside functions function testFunc() { string3 = 'Also global'; var string4 = 'Not global'; } testFunc(); // string3 bled through; string4 is gone alert(string3); alert(string4);

28

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

// when not inside a function, variables // belong to the window object var string1 = 'Global string'; // not using 'var' implies global string2 = 'Another'; // even inside functions function testFunc() { string3 = 'Also global'; var string4 = 'Not global'; } testFunc(); // string3 bled through; string4 is gone alert(string3); alert(string4);

28

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

// when not inside a function, variables // belong to the window object var string1 = 'Global string'; // not using 'var' implies global string2 = 'Another'; // even inside functions function testFunc() { string3 = 'Also global'; var string4 = 'Not global'; } testFunc(); // string3 bled through; string4 is gone alert(string3); alert(string4);

28

Closure

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

29

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; return function () { alert(storage); }; };

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); }; }; var memory = remember('a secret');

30

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); }; }; var memory = remember('a secret'); setTimeout(memory, 3000);

30

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); }; }; var memory = remember('a secret'); setTimeout(memory, 3000);

30

pp. 15-34
31

Sidetrack: Developing JavaScript

32

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

33

No Firefox?

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

34

Ajax (nally)

35

What is Ajax?

At one point, an acronym for Asynchronous JavaScript and XML Doesn't necessarily use XML Not necessarily Asynchronous

36

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

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.</p> <h2>Second-level header</h2> <h2>Another second-level header</h2> </body> </html>

view
40

41

Useful, compatible methods



document.getElementById('main') document.getElementsByTagName('h2') document.createElement('p') document.createTextNode('hello')

http://quirksmode.org/dom/w3c_core.html
42

document.getElementById('main');

43

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.getElementById('main'); // Firebug logging console.log(header); </script> </body>

view
44

document.getElementsByTagName('h2');

45

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 h2s = document.getElementsByTagName('h2'); // Firebug logging console.log(h2s); </script> </body>

view
46

document.createElement('p');

47

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.</p> <h2>Second-level header</h2> <h2>Another second-level header</h2> <script> var para = document.createElement('p'); // Firebug logging console.log(para); </script> </body>

view
48

document.createTextNode('A new paragraph');

49

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 text = document.createTextNode( 'A new paragraph' ); console.log(text); </script> </body> </html>

view
50

para.appendChild(text);

51

11 12 13 14 15 16 17 18

<script> var para = document.createElement('p'); var text = document.createTextNode( 'A new paragraph' ); para.appendChild(text); console.log(para); </script>

view
52

53

54

12 13 14 15 16 17 18 19

// create the paragraph and text nodes var para = document.createElement('p'); var text = document.createTextNode( 'A new paragraph' ); // add the text to the paragraph para.appendChild(text);

view
55

12 13 14 15 16 17 18 19 20 21 22 23

// create the paragraph and text nodes var para = document.createElement('p'); var text = document.createTextNode( 'A new paragraph' ); // add the text to the paragraph para.appendChild(text); // fetch the body element var body = document.getElementsByTagName('body')[0];

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.createElement('p'); var text = document.createTextNode( 'A new paragraph' ); // add the text to the paragraph para.appendChild(text); // fetch the body element var body = document.getElementsByTagName('body')[0]; // after 4 seconds, append our new paragraph setTimeout(function () { body.appendChild(para); }, 4000);

view
55

More Manipulation

getAttribute('href') setAttribute('class', 'newClass') parentNode previousSibling nextSibling nodeValue

56

1 2 3 4 5 6 7 8 9 10 11 12 13

<html> <head> <style type="text/css"> .special { font-weight: bold; color: red; } </style> </head> <body> <h1 id="main">Main Header</h1> <p class="special">This is special.</p> <p>This is not.</p> </body> </html>

view
57

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

view
58

13 14 15 16 17 18 19 20 21 22 23 24 25 26 27

// get our elements var main = document.getElementById('main'); var p = document.getElementsByTagName('p')[1]; // wait 3 seconds to set main's class setTimeout(function () { main.setAttribute('class', 'special');

}, 3000);

view
58

13 14 15 16 17 18 19 20 21 22 23 24 25 26 27

// get our elements var main = document.getElementById('main'); var p = document.getElementsByTagName('p')[1]; // wait 3 seconds to set main's class setTimeout(function () { main.setAttribute('class', 'special'); // then wait another 3 to set p's setTimeout(function () { p.setAttribute('class', 'special'); }, 3000); }, 3000);

view
59

pp. 34-43
60

Events

61

Events: When Stuff Happens



onclick onsubmit onload setTimeout() / clearTimeout() setInterval() / clearInterval()

http://quirksmode.org/dom/events/index.html
62

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

63

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

view
64

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

view
64

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

view
64

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

view
64

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

65

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

view
66

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

view
66

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

view
66

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

view
66

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

}; var addpara = function () { div.innerHTML += para; };

view
66

XMLHttpRequest (xhr)

67

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 signicant abuse; could break the back button, reloading, screen readers

68

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

69

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

view
70

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

view
70

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

view
70

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

view
70

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

} var changer = function () { };

view
70

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

view
71

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

view
71

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

view
71

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

view
71

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

view
71

Is it really that easy?

72

Is it really that easy?


No

72

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

73

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

74

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

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

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

var xhr = getXHR(), div; window.onload = function () { div = document.getElementById('results') if (xhr) { xhr.onreadystatechange = changer; xhr.open('GET', 'php/slow.php', true); xhr.send(null); } div.innerHTML += '<p>Waiting...</p>'; } // do something, when something happens var changer = function () { if (xhr.readyState == 4) { if (xhr.status == 200) { div.innerHTML = xhr.responseText; } } };

view
77

pp. 47-65
78

Tomorrow

Enhancing our site jQuery Your Time

79

Vous aimerez peut-être aussi