Javascript - The Definitive Guide

This book covers the JavaScript language and the JavaScript APIs implemented by web browsers.


David Flanagan


1098 Pages

80059 Reads

60 Downloads

English

PDF Format

13.4 MB

Java Script

Download PDF format


  • David Flanagan   
  • 1098 Pages   
  • 13 Feb 2015
  • Page - 1

    read more..

  • Page - 2

    read more..

  • Page - 3

    JavaScript: The Definitive Guide read more..

  • Page - 4

    read more..

  • Page - 5

    SIXTH EDITION JavaScript: The Definitive Guide Beijing • Cambridge • Farnham • Köln • Sebastopol • Tokyo read more..

  • Page - 6

    JavaScript: The Definitive Guide, Sixth Edition Editor: Production Editor: Proofreader: Indexer: Cover Designer: Interior Designer: Illustrator: Printing History: read more..

  • Page - 7

    read more..

  • Page - 8

    read more..

  • Page - 9

    Table of Contents Preface .................................................................... xiii 1. Introduction to JavaScript ................................................ 1 Part I. Core JavaScript 2. Lexical Structure ....................................................... 21 3. Types, Values, and Variables ............................................. 29 4. Expressions and Operators read more..

  • Page - 10

    5. Statements ........................................................... 87 6. Objects .............................................................. 115 7. Arrays ............................................................... 141 viii | Table of Contents read more..

  • Page - 11

    8. Functions ............................................................ 163 9. Classes and Modules ................................................... 199 10. Pattern Matching with Regular Expressions ............................... 251 11. JavaScript Subsets and Extensions ....................................... 265 12. Server-Side JavaScript ................................................. 289 Table of Contents | ix read more..

  • Page - 12

    Part II. Client-Side JavaScript 13. JavaScript in Web Browsers ............................................. 307 14. The Window Object ................................................... 341 15. Scripting Documents .................................................. 361 16. Scripting CSS ......................................................... 413 17. Handling Events ...................................................... 445 x read more..

  • Page - 13

    18. Scripted HTTP ........................................................ 491 19. The jQuery Library .................................................... 523 20. Client-Side Storage .................................................... 587 21. Scripted Media and Graphics ............................................ 613 22. HTML5 APIs .......................................................... 667 Table of Contents | xi read more..

  • Page - 14

    Part III. Core JavaScript Reference Core JavaScript Reference .................................................... 719 Part IV. Client-Side JavaScript Reference Client-Side JavaScript Reference .............................................. 859 Index .................................................................... 1019 xii | Table of Contents read more..

  • Page - 15

    Preface xiii read more..

  • Page - 16

    A Note About Piracy Conventions Used in This Book Constant width Constant width italic Example Code xiv | Preface read more..

  • Page - 17

    Errata and How to Contact Us Acknowledgments <canvas> Preface | xv read more..

  • Page - 18

    xvi | Preface read more..

  • Page - 19

    CHAPTER 1 Introduction to JavaScript 1 read more..

  • Page - 20

    JavaScript: Names and Versions 2 | Chapter 1: Introduction to JavaScript read more..

  • Page - 21

    <canvas> Exploring JavaScript <script> console.log() console.log() alert() Introduction to JavaScript | 3 read more..

  • Page - 22

    1.1 Core JavaScript // Anything following double slashes is an English-language comment. // Read the comments carefully: they explain the JavaScript code. // variable is a symbolic name for a value. // Variables are declared with the var keyword: var x; // Declare a variable named x. // Values can be assigned to variables with an read more..

  • Page - 23

    x = null; // Null is a special value that means "no value". x = undefined; // Undefined is like null. // JavaScript's most important data type is the object. // An object is a collection of name/value pairs, or a string to value map. var book = { // Objects are read more..

  • Page - 24

    3 - 2 // => 1: subtraction 3 * 2 // => 6: multiplication 3 / 2 // => 1.5: division points[1].x - points[0].x // => 1: more complicated operands work, too "3" + "2" // read more..

  • Page - 25

    plus1(y) // => 4: y is 3, so this invocation returns 3+1 var square = function(x) { // Functions are values and can be assigned to vars return x*x; // Compute the function's value }; // Semicolon marks the end of the assignment. square(plus1(y)) read more..

  • Page - 26

    } factorial2(5) // => 120: 1*2*3*4*5 r() // Define a constructor function to initialize a new Point object function Point(x,y) { // By convention, constructors start with capitals this.x = x; // this keyword is the new object being initialized this.y = y; // Store read more..

  • Page - 27

    <script> <html> <head> <script src="library.js"></script> <!-- include a library of JavaScript code --> </head> <body> <p>This is a paragraph of HTML</p> <script> // And this is some client-side JavaScript code // literally embedded within the HTML file </script> <p>Here is more HTML.</p> </body> </html> <script> function moveon() { read more..

  • Page - 28

    log.innerHTML = "<h1>Debug Log</h1>"; // Define initial content document.body.appendChild(log); // Add it at end of document } // Now wrap the message in its own <pre> and append it to the log var pre = document.createElement("pre"); // Create a <pre> tag var text read more..

  • Page - 29

    <button onclick="hide(this); debug('hide button 2');">Hide2</button> World // The "load" event occurs when a document is fully loaded. Usually we // need to wait for this event before we start running our JavaScript code. window.onload = function() { // Run this function when the document loads // Find all <img> tags in the document var images = read more..

  • Page - 30

    <canvas> 1.2.1 Example: A JavaScript Loan Calculator 12 | Chapter 1: Introduction to JavaScript read more..

  • Page - 31

    <canvas> <!DOCTYPE html> <html> <head> <title>JavaScript Loan Calculator</title> <style> /* This is a CSS style sheet: it adds style to the program output */ .output { font-weight: bold; } /* Calculated values in bold */ #payment { text-decoration: underline; } /* For element with id="payment" */ #graph { border: solid black 1px; read more..

  • Page - 32

    <tr><td>Total interest:</td> <td>$<span class="output" id="totalinterest"></span></td></tr> <tr><th>Sponsors:</th><td colspan=2> Apply for your loan with one of these fine lenders: <div id="lenders"></div></td></tr> </table> <!-- The rest of this example is JavaScript read more..

  • Page - 33

    catch(e) { /* And ignore those errors */ } // Finally, chart loan balance, and interest and equity payments chart(principal, interest, monthly, payments); } else { // Result was Not-a-Number or infinite, which means the input was // incomplete or invalid. Clear any read more..

  • Page - 34

    // Encode the user's input as query parameters in a URL var url = "getLenders.php" + // Service url plus "?amt=" + encodeURIComponent(amount) + // user data in query string "&apr=" + encodeURIComponent(apr) + "&yrs=" + encodeURIComponent(years) + read more..

  • Page - 35

    g.lineTo(paymentToX(payments), amountToY(0)); // Down to lower right g.closePath(); // And back to start g.fillStyle = "#f88"; // Light red g.fill(); read more..

  • Page - 36

    g.fillRect(rightEdge-3, y-0.5, 3,1); // Draw the tick mark g.fillText(String(ticks[i].toFixed(0)), // And label it. rightEdge-5, y); } } </script> </body> </html> 18 | Chapter 1: Introduction to JavaScript read more..

  • Page - 37

    PART I Core JavaScript read more..

  • Page - 38

    read more..

  • Page - 39

    CHAPTER 2 Lexical Structure 2.1 Character Set 2.1.1 Case Sensitivity while online Online OnLine ONLINE onclick onClick onclick 21 read more..

  • Page - 40

    2.1.2 Whitespace, Line Breaks, and Format Control Characters \u0020 \u0009 \u000B \u000C \u00A0 \uFEFF \u000A \u000D \u2028 \u2029 \u200F \u200E \u200D \u200C \uFEFF 2.1.3 Unicode Escape Sequences \u \u00E9 "café" === "caf\u00e9" // => true 2.1.4 Normalization \u00E9 \u0301 22 | Chapter 2: Lexical Structure read more..

  • Page - 41

    2.2 Comments // /* */ // This is a single-line comment. /* This is also a comment */ // and here is another comment. /* * This is yet another comment. * It has multiple lines. */ 2.3 Literals 12 // The number twelve 1.2 // The number one point two "hello world" // A string of text read more..

  • Page - 42

    _dummy $str var sí = true; var π = 3.14; 2.4.1 Reserved Words break delete function return typeof case do if switch var catch else in this read more..

  • Page - 43

    arguments encodeURI Infinity Number RegExp Array encodeURIComponent isFinite Object String Boolean Error isNaN parseFloat SyntaxError Date eval read more..

  • Page - 44

    var a; a = 3; console.log(a); var a a a a; a = 3; var y = x + f (a+b).toString() f var y = x + f(a+b).toString(); ( [ / + - / + - ( [ var x = 0 // Semicolon omitted here ;[x,x+1,x+2].forEach(console.log) // Defensive ; keeps this statement separate return break continue return true; 26 | Chapter 2: Lexical Structure read more..

  • Page - 45

    return; true; return true; return break continue ++ −− ++ -- x ++ y x; ++y; x++; y 2.5 Optional Semicolons | 27 Core JavaScript read more..

  • Page - 46

    read more..

  • Page - 47

    CHAPTER 3 Types, Values, and Variables null undefined null undefined null undefined 29 read more..

  • Page - 48

    new a a sort() sort() a a.sort(); // The object-oriented version of sort(a). null undefined null undefined 30 | Chapter 3: Types, Values, and Variables read more..

  • Page - 49

    == var 3.1 Numbers ± ± double double 3.1 Numbers | 31 Core JavaScript read more..

  • Page - 50

    3.1.1 Integer Literals 0 3 10000000 0xff // 15*16 + 15 = 255 (base 10) 0xCAFE911 0377 // 3*64 + 7*8 + 7 = 255 (base 10) 3.1.2 Floating-Point Literals [digits][.digits][(E|e)[(+|-)]digits] 3.14 2345.789 .333333333333333333 6.02e23 // 6.02 × 1023 1.4738223E-32 // 1.4738223 × 10−32 32 | Chapter 3: Types, Values, and Variables read more..

  • Page - 51

    3.1.3 Arithmetic in JavaScript + - * / % Math Math.pow(2,53) // => 9007199254740992: 2 to the power 53 Math.round(.6) // => 1.0: round to the nearest integer Math.ceil(.6) // => 1.0: round up to an integer Math.floor(.6) // => 0.0: round down to an integer Math.abs(-5) read more..

  • Page - 52

    Infinity NaN Number Infinity // A read/write variable initialized to Infinity. Number.POSITIVE_INFINITY // Same value, read-only. 1/0 // This is also the same value. Number.MAX_VALUE + 1 // This also evaluates to Infinity. Number.NEGATIVE_INFINITY // These read more..

  • Page - 53

    1/2 1/8 1/1024 1/10 1/100 0.1 0.1 var x = .3 - .2; // thirty cents minus 20 cents var y = .2 - .1; // twenty cents minus 10 cents x == y // => false: the two values are not the same! x == .1 // => false: .3-.2 is not equal to .1 y == .1 // => true: .2-.1 is equal to read more..

  • Page - 54

    later.toString() // => "Fri Jan 01 2010 17:10:30 GMT-0800 (PST)" later.toUTCString() // => "Sat, 02 Jan 2010 01:10:30 GMT" later.toLocaleDateString() // => "01/01/2010" later.toLocaleTimeString() // => "05:10:30 PM" later.toISOString() // => "2010-01-02T01:10:30.000Z"; read more..

  • Page - 55

    \ \n "two\nlines" // A string representing 2 lines written on one line "one\ // A one-line string written on 3 lines. ECMAScript 5 only. long\ line" \ <button onclick="alert('Thank you')">Click Me</button> 3.2.2 Escape Sequences in String Literals \ \n \' 'You\'re right, it can\'t be a quote' \xA9 \u \u03c0 π 3.2 Text | 37 read more..

  • Page - 56

    Sequence Character represented \0 The NUL character (\u0000) \b Backspace (\u0008) \t Horizontal tab (\u0009) \n Newline (\u000A) \v Vertical tab (\u000B) \f Form feed (\u000C) \r Carriage return (\u000D) \" Double quote (\u0022) \' Apostrophe or single quote (\u0027) \\ Backslash (\u005C) \x XX The Latin-1 character specified by the two hexadecimal digits XX \u XXXX The Unicode character read more..

  • Page - 57

    s.split(", ") // => ["hello", "world"] split into substrings s.replace("h", "H") // => "Hello, world": replaces all instances s.toUpperCase() // => "HELLO, WORLD" replace() toUpperCase() charAt() s = "hello, world"; s[0] read more..

  • Page - 58

    text.replace(pattern, "#"); // => "testing: #, #, #" text.split(/\D+/); // => ["","1","2","3"]: split on non-digits 3.3 Boolean Values true false a == 4 a 4 true a 4 false if/else true false if (a == 4) b = b + 1; else a = a + 1; a 4 1 b 1 a false undefined null 0 -0 NaN "" read more..

  • Page - 59

    if (o) ... if o null if false null undefined if o null 0 "" toString() && || ! true false if ((x == 0 && y == 0) || !(z == 0)) { // x and y are both zero or z is non-zero } 3.4 null and undefined null typeof null null null null null nil undefined null undefined undefined typeof 3.4 null and undefined | 41 Core JavaScript read more..

  • Page - 60

    null undefined == === false null undefined . [] undefined null null 3.5 The Global Object undefined Infinity NaN isNaN() parseInt() eval() Date() RegExp() String() Object() Array() this var global = this; // Define a global variable to refer to the global object window this 42 | Chapter 3: Types, Values, and Variables read more..

  • Page - 61

    3.6 Wrapper Objects . m o o.m() var s = "hello world!"; // A string var word = s.substring(s.indexOf(" ")+1, s.length); // Use string properties s new String(s) Number() Boolean() null undefined TypeError var s = "test"; // Start with a string value. s.len = 4; read more..

  • Page - 62

    String() Number() Boolean() var s = "test", n = 1, b = true; // A string, number, and boolean value. var S = new String(s); // A String object var N = new Number(n); // A Number object var B = new Boolean(b); // A Boolean object S N B s n b == === typeof 3.7 Immutable Primitive Values and read more..

  • Page - 63

    var o = {x:1}, p = {x:1}; // Two objects with the same properties o === p // => false: distinct objects are never equal var a = [], b = []; // Two distinct, empty arrays a === b // => false: distinct arrays are never equal var a = []; // The variable a refers to read more..

  • Page - 64

    var n = 1 - "x"; // => NaN: string "x" can't convert to a number n + " objects" // => "NaN objects": NaN converts to string "NaN" Value Converted to: String Number Boolean Object undefined "undefined" NaN false throws TypeError null "null" 0 false throws TypeError true "true" 1 new Boolean(true) false "false" 0 read more..

  • Page - 65

    null undefined 3.8.1 Conversions and Equality == null == undefined // These two values are treated as equal. "0" == 0 // String converts to a number before comparing. 0 == false // Boolean converts to number before comparing. "0" == false // Both operands convert to numbers before comparing. == === undefined false undefined read more..

  • Page - 66

    + + ! x + "" // Same as String(x) +x // Same as Number(x). You may also see x-0 !!x // Same as Boolean(x). Note double ! toString() var n = 17; binary_string = n.toString(2); // Evaluates to "10001" octal_string = "0" + n.toString(8); // Evaluates read more..

  • Page - 67

    parseFloat() parseInt() parseFloat() parseInt() parseInt() parseFloat() parseInt("3 blind mice") // => 3 parseFloat(" 3.14 meters") // => 3.14 parseInt("-12.34") // => -12 parseInt("0xFF") // => 255 parseInt("0xff") // => 255 parseInt("-0XFF") read more..

  • Page - 68

    toString() toString() toString() toString() toString() [1,2,3].toString() // => "1,2,3" (function(x) { f(x); }).toString() // => "function(x) {\n f(x);\n}" /\d+/g.toString() // => "/\\d+/g" new Date(2010,0,1).toString() // => "Fri Jan 01 2010 00:00:00 GMT-0800 (PST)" valueOf() read more..

  • Page - 69

    valueOf() valueOf() toString() valueOf() toString() + == + == valueof() toString() valueOf() toString() < == valueOf() toString() + == != - + - == > var now = new Date(); // Create a Date object typeof (now + 1) // => "string": + converts dates to strings typeof (now - 1) // => "number": - uses object-to-number conversion read more..

  • Page - 70

    now == now.toString() // => true: implicit and explicit string conversions now > (now -1) // => true: > converts a Date to a number 3.9 Variable Declaration var var i; var sum; var var i, sum; var message = "hello"; var i = 0, j = 0, k = 0; var undefined var for for/in for(var i = 0; i < 10; i++) console.log(i); for(var i = 0, j=10; i read more..

  • Page - 71

    3.10 Variable Scope var scope = "global"; // Declare a global variable function checkscope() { var scope = "local"; // Declare a local variable with the same name return scope; // Return the local value, not the global one } checkscope() // => read more..

  • Page - 72

    i j k function test(o) { var i = 0; // i is defined throughout function if (typeof o == "object") { var j = 0; // j is defined everywhere, not just block for(var k=0; k < 10; k++) { // k is defined everywhere, not just read more..

  • Page - 73

    3.10.2 Variables As Properties var delete var truevar = 1; // A properly declared global variable, nondeletable. fakevar = 2; // Creates a deletable property of the global object. this.fakevar2 = 3; // This does the same thing. delete truevar // => false: variable not deleted delete fakevar // => true: variable deleted delete read more..

  • Page - 74

    x x with 56 | Chapter 3: Types, Values, and Variables read more..

  • Page - 75

    CHAPTER 4 Expressions and Operators * x * y x y 4.1 Primary Expressions 57 read more..

  • Page - 76

    1.23 // A number literal "hello" // A string literal /pattern/ // A regular expression literal true // Evalutes to the boolean true value false // Evaluates to the boolean false value null // Evaluates to the null value this // Evaluates to the "current" object true false null this read more..

  • Page - 77

    var matrix = [[1,2,3], [4,5,6], [7,8,9]]; var sparseArray = [1,,,,5]; var p = { x:2.3, y:-1.2 }; // An object with 2 properties var q = {}; // An empty object with no properties q.x = 2.3; q.y = -1.2; // Now q has the same properties as p var rectangle = { upperLeft: { x: 2, y: 2 }, read more..

  • Page - 78

    4.4 Property Access Expressions expression . identifier expression [ expression ] var o = {x:1,y:{z:3}}; // An example object var a = [o,4,[5,6]]; // An example array that contains the object o.x // => 1: property x of expression o o.y.z // => 3: property z of expression read more..

  • Page - 79

    4.5 Invocation Expressions f(0) // f is the function expression; 0 is the argument expression. Math.max(x,y,z) // Math.max is the function; x, y and z are the arguments. a.sort() // a.sort is the function; there are no arguments. return undefined this this undefined this 4.6 Object Creation Expressions new new Object() new Point(2,3) 4.6 read more..

  • Page - 80

    new Object new Date {} this this 4.7 Operator Overview + = delete instanceof Operator Operation A N Types ++ Pre- or post-increment R 1 lval num -- Pre- or post-decrement R 1 lval num - Negate number R 1 num num + Convert to number R 1 num num ~ Invert bits R 1 int int ! Invert boolean value R 1 bool bool 62 | Chapter 4: Expressions and Operators read more..

  • Page - 81

    Operator Operation A N Types delete Remove a property R 1 lval bool typeof Determine type of operand R 1 any str void Return undefined value R 1 any undef *, /, % Multiply, divide, remainder L 2 num,num num +, - Add, subtract L 2 num,num num + Concatenate strings L 2 str,str str << Shift left L 2 int,int int >> Shift right with sign extension L 2 int,int int >>> Shift right read more..

  • Page - 82

    −x x ?: 4.7.2 Operand and Result Type * "3" * "5" + < 4.7.3 Lvalues lval 4.7.4 Operator Side Effects 2 * 3 ++ -- delete undefined 64 | Chapter 4: Expressions and Operators read more..

  • Page - 83

    4.7.5 Operator Precedence w = x + y*z; * + = w = (x + y)*z; typeof my.functions[x](y) typeof typeof 4.7.6 Operator Associativity w = x - y - z; 4.7 Operator Overview | 65 Core JavaScript read more..

  • Page - 84

    w = ((x - y) - z); x = ~-y; w = x = y = z; q = a?b:c?d:e?f:g; x = ~(-y); w = (x = (y = z)); q = a?b:(c?d:(e?f:g)); 4.7.7 Order of Evaluation w=x+y*z w x y z y z x w x z x z 4.8 Arithmetic Expressions * / % + - + NaN NaN NaN 66 | Chapter 4: Expressions and Operators read more..

  • Page - 85

    / 5/2 2.5 2 0/0 NaN % 5 % 2 1 -5 % 2 -1 6.5 % 2.1 0.2 4.8.1 The + Operator + 1 + 2 // => 3 "hello" + " " + "there" // => "hello there" "1" + "2" // => "12" + + + toString() valueOf() valueOf() toString() NaN 1 + read more..

  • Page - 86

    2 + null // => 2: addition after null converts to 0 2 + undefined // => NaN: addition after undefined converts to NaN + 1 + 2 + " blind mice"; // => "3 blind mice" 1 + (2 + " blind mice"); // => "12 blind mice" + 4.8.2 Unary Arithmetic Operators + - ++ -- + - + NaN - - ++ ++ ++ var i = 1, j = ++i; // i read more..

  • Page - 87

    ++x x=x+1 ++ x ++x x+1 for -- -- ++ -- 4.8.3 Bitwise Operators NaN Infinity -Infinity & & 0x1234 & 0x00FF 0x0034 4.8 Arithmetic Expressions | 69 Core JavaScript read more..

  • Page - 88

    | | 0x1234 | 0x00FF 0x12FF ^ ^ true true 0xFF00 ^ 0xF0F0 0x0FF0 ~ ~ ~ ~0x0F 0xFFFFFFF0 << << a << 1 a a 7 << 2 >> >> 7 >> 1 −7 >> 1 >>> >>> >> −1 >> 4 −1 >>> 4 0x0FFFFFFF 70 | Chapter 4: Expressions and Operators read more..

  • Page - 89

    4.9 Relational Expressions true false if while for in instanceof 4.9.1 Equality and Inequality Operators == === true false === == = == === = == === != !== == === != false == true !== false true ! != !== === null undefined true false 4.9 Relational Expressions | 71 Core JavaScript read more..

  • Page - 90

    NaN NaN x NaN x !== x NaN x 0 -0 === == String.localeCompare() == == null undefined true false toString() valueOf() valueOf() toString() toString() "1" == true 72 | Chapter 4: Expressions and Operators read more..

  • Page - 91

    true true "1" true 4.9.2 Comparison Operators < < true false > > true false <= <= true false >= >= true false valueOf() toString() 0 -0 Infinity -Infinity NaN false 4.9 Relational Expressions | 73 Core JavaScript read more..

  • Page - 92

    < String.localeCompare() String.toLowerCase() String.toUpperCase() + + 1 + 2 // Addition. Result is 3. "1" + "2" // Concatenation. Result is "12". "1" + 2 // Concatenation. 2 is converted to "2". Result is "12". 11 < 3 // Numeric comparison. Result is false. "11" < "3" // read more..

  • Page - 93

    instanceof var d = new Date(); // Create a new object with the Date() constructor d instanceof Date; // Evaluates to true; d was created with Date() d instanceof Object; // Evaluates to true; all objects are instances of Object d instanceof Number; // Evaluates to false; d is not a Number object var a = [1, 2, 3]; // Create an array with array literal read more..

  • Page - 94

    null undefined 0 -0 NaN "" && && true false && && && var o = { x : 1 }; var p = null; o && o.x // => 1: o is truthy, so return value of o.x p && p.x // => null: p is falsy, so return it and don't evaluate p.x && p null p.x && p.x p null undefined && if (a == b) stop(); read more..

  • Page - 95

    || && && // If max_width is defined, use that. Otherwise look for a value in // the preferences object. If that is not defined use a hard-coded constant. var max = max_width || preferences.max_width || 500; // Copy the properties of o to p, and return p function copy(o, p) { p = p || {}; // If no object passed for p, use a newly created read more..

  • Page - 96

    = = (a = b) == 0 = == = i = j = k = 0; // Initialize 3 variables to 0 4.11.1 Assignment with Operation = += total += sales_tax total = total + sales_tax += -= *= &= Operator Example Equivalent += a += b a = a + b -= a -= b a = a - b *= a *= b a = a * b /= a /= b a = a / b %= a %= b a = a % b <<= a <<= read more..

  • Page - 97

    Operator Example Equivalent >>= a >>= b a = a >> b >>>= a >>>= b a = a >>> b &= a &= b a = a & b |= a |= b a = a | b ^= a ^= b a = a ^ b a op= b op a = a op b a a data[i++] *= 2; data[i++] = data[i++] * 2; 4.12 Evaluation Expressions eval() eval("3+2") // => 5 eval() eval() Is eval() a read more..

  • Page - 98

    g() eval eval() 4.12.1 eval() eval() undefined eval() eval() x eval("x") eval("x=1") eval("var y = 3;") y eval("function f() { return x+1; }"); eval() eval() eval("return;") return x=0 eval() eval() 4.12.2 Global eval() eval() eval() eval() eval() eval() 80 | Chapter 4: Expressions and Operators read more..

  • Page - 99

    eval() eval() eval() var geval = eval; // Using another name does a global eval var x = "global", y = "global"; // Two global variables function f() { // This function does a local eval var x = "local"; // Define a local variable read more..

  • Page - 100

    4.13 Miscellaneous Operators 4.13.1 The Conditional Operator (?:) ?: ? ? : : x > 0 ? x : -x // The absolute value of x if ?: greeting = "hello " + (username ? username : "there"); if greeting = "hello "; if (username) greeting += username; else greeting += "there"; 4.13.2 The typeof Operator typeof typeof x typeof x undefined read more..

  • Page - 101

    x typeof x any function "function" any nonfunction native object "object" any host object An implementation-defined string, but not “undefined”, “boolean”, “number”, or “string”. typeof (typeof value == "string") ? "'" + value + "'" : value typeof switch typeof typeof typeof(i) typeof null null typeof typeof instanceof constructor typeof typeof typeof typeof 4.13 read more..

  • Page - 102

    4.13.3 The delete Operator delete delete var o = { x: 1, y: 2}; // Start with an object delete o.x; // Delete one of its properties "x" in o // => false: the property does not exist anymore var a = [1,2,3]; // Start with an array delete a[2]; // Delete the last element of read more..

  • Page - 103

    // Exception in strict mode. Use 'delete this.x' instead x; // Runtime error: x is not defined delete 4.13.4 The void Operator void undefined void javascript: void <a> <a href="javascript:void window.open();">Open New Window</a> onclick javascript: void 4.13.5 The Comma Operator (,) i=0, read more..

  • Page - 104

    read more..

  • Page - 105

    CHAPTER 5 Statements if switch while for break return throw 87 read more..

  • Page - 106

    5.1 Expression Statements greeting = "Hello " + name; i *= 3; ++ -- counter++; delete delete o.x; alert(greeting); window.close(); Math.cos(x); cx = Math.cos(x); 5.2 Compound and Empty Statements { x = Math.PI; cx = Math.cos(x); console.log("cos(π) = " + cx); } 88 | Chapter 5: Statements read more..

  • Page - 107

    while ; for for // Initialize an array a for(i = 0; i < a.length; a[i++] = 0) ; a[i++] = 0 for while if if ((a == 0) || (b == 0)); // Oops! This line does nothing... o = null; // and this line is always executed. for(i = 0; i < a.length; a[i++] = 0) /* empty */ ; 5.3 Declaration Statements var function 5.3 Declaration read more..

  • Page - 108

    var function 5.3.1 var var var name_1 [ = value_1] [ ,..., name_n [= value_n]] var var i; // One simple variable var j = 0; // One var, one value var p, q; read more..

  • Page - 109

    5.3.2 function function var f = function(x) { return x+1; } // Expression assigned to a variable function f(x) { return x+1; } // Statement includes variable name function funcname([arg1 [, arg2 [..., argn]]]) { statements } funcname function while function hypotenuse(x, y) { return Math.sqrt(x*x + y*y); // return is documented in the read more..

  • Page - 110

    var var 5.4 Conditionals if/else switch 5.4.1 if if if (expression) statement expression statement expression statement if (username == null) // If username is null or undefined, username = "John Doe"; // define it // If username is null, undefined, false, 0, "", or NaN, give it a new value if (!username) username = "John Doe"; read more..

  • Page - 111

    if (!address) { address = ""; message = "Please specify a mailing address."; } if else expression false if (expression) statement1 else statement2 statement1 expression statement2 expression if (n == 1) console.log("You have 1 new message."); else console.log("You have " + n + " new messages."); if else else if read more..

  • Page - 112

    console.log("i doesn't equal j"); } if else while 5.4.2 else if if/else else if else if if/else if (n == 1) { // Execute code block #1 } else if (n == 2) { // Execute code block #2 } else if (n == 3) { // Execute code block #3 } else { // If all else fails, execute block #4 } if if else else if if (n == 1) { read more..

  • Page - 113

    5.4.3 switch if else if if switch switch switch(expression) { statements } switch case case switch expression case === case case default: default: switch switch switch if/else switch(n) { case 1: // Start here if n == 1 // Execute code block #1. break; // read more..

  • Page - 114

    expression case case break switch return break switch case switch function convert(x) { switch(typeof x) { case 'number': // Convert the number to a hexadecimal integer return x.toString(16); case 'string': // Return the string enclosed in quotes return '"' + x + read more..

  • Page - 115

    5.5 Loops while do/while for for/in 5.5.1 while if while while (expression) statement while expression statement expression statement expression statement expression while(true) statement expression while var count = 0; while (count < 10) { console.log(count); count++; } count false count while count i j k 5.5 Loops | 97 Core JavaScript read more..

  • Page - 116

    5.5.2 do/while do/while while do statement while (expression); do/while while do/while function printArray(a) { var len = a.length, i = 0; if (len == 0) console.log("Empty Array"); else { do { console.log(a[i]); } while (++i < len); } } do/while read more..

  • Page - 117

    for while initialize; while(test) { statement increment; } initialize initialize var test test statement increment ++ -- for while for(var count = 0; count < 10; count++) console.log(count); for var i,j; for(i = 0, j = 10 ; i < 10 ; i++, j--) sum += i * j; for next function tail(o) { read more..

  • Page - 118

    5.5.4 for/in for/in for for for/in for (variable in object) statement variable var object statement for for(var i = 0; i < a.length; i++) // Assign array indexes to variable i console.log(a[i]); // Print the value of each array element for/in for(var p in o) // Assign property names of o to variable p read more..

  • Page - 119

    for/in toString for/in for/in 5.5.4.1 Property enumeration order for/in delete Object.defineProperty() 5.5 Loops | 101 Core JavaScript read more..

  • Page - 120

    5.6 Jumps break continue break continue return throw try/catch/ finally 5.6.1 Labeled Statements identifier: statement break continue break continue while continue mainloop: while(token != null) { // Code omitted... continue mainloop; // Jump to the next iteration of the named loop // More code omitted... } identifier 102 | Chapter 5: Statements read more..

  • Page - 121

    5.6.2 break break switch break; switch break break switch break break for(var i = 0; i < a.length; i++) { if (a[i] == target) break; } break break labelname; break break break switch break break labelname break break var matrix = getData(); // Get a 2D array of numbers from somewhere // Now sum all the numbers in the matrix. var sum = 0, success = false; // Start with read more..

  • Page - 122

    for(var y = 0; y < row.length; y++) { var cell = row[y]; if (isNaN(cell)) break compute_sum; sum += cell; } } success = true; } // The break statements jump here. If we arrive here with success == false // then there was something wrong read more..

  • Page - 123

    continue for(i = 0; i < data.length; i++) { if (!data[i]) continue; // Can't proceed with undefined data total += data[i]; } break continue break continue labelname 5.6.4 return return return return expression; return return expression function square(x) { return x*x; } // A function that has a return statement square(2) read more..

  • Page - 124

    throw try/catch/finally throw throw expression; expression name message function factorial(x) { // If the input argument is invalid, throw an exception! if (x < 0) throw new Error("x must not be negative"); // Otherwise, compute a value and return normally for(var f = 1; x > 1; f *= x, x--) /* empty */ ; return f; } catch read more..

  • Page - 125

    try/catch/finally try { // Normally, this code runs from the top of the block to the bottom // without problems. But it can sometimes throw an exception, // either directly, with a throw statement, or indirectly, by calling // a method that throws an exception. } catch (e) { // The statements in this block are executed if, and only if, the try read more..

  • Page - 126

    try finally try return continue break finally try catch catch finally catch finally catch finally return continue break throw finally finally return try finally catch finally try for while continue try/finally while for continue // Simulate for( initialize ; test ; increment ) body; initialize ; while( test ) { try { body ; } finally { increment ; } } body break while read more..

  • Page - 127

    object statement with with with with document.forms[0].address.value with with(document.forms[0]) { // Access form elements directly here. For example: name.value = ""; address.value = ""; email.value = ""; } document.forms[0] address with var f = document.forms[0]; f.name.value = ""; f.address.value = ""; f.email.value = read more..

  • Page - 128

    f() f() function f(o) { if (o === undefined) debugger; // Temporary line for debugging purposes ... // The rest of the function goes here. } f() debugger debugger debugger 5.7.3 “use strict” "use strict" "use strict" "use strict" use "use strict" "use strict" "use strict" read more..

  • Page - 129

    with catch this undefined this var hasStrictMode = (function() { "use strict"; return this===undefined}()); call() apply() this call() apply() null undefined eval() eval() eval() arguments arguments delete delete false delete false 5.7 Miscellaneous Statements | 111 Core JavaScript read more..

  • Page - 130

    eval arguments catch argu ments.caller arguments.callee caller arguments 5.8 Summary of JavaScript Statements Statement Syntax Purpose break break [label]; Exit from the innermost loop or switch or from named enclosing statement case case expression: Label a statement within a switch continue continue [label]; Begin next iteration of the innermost loop or the named loop debugger debugger; Debugger read more..

  • Page - 131

    Statement Syntax Purpose use strict "use strict"; Apply strict mode restrictions to script or function var var name [ = expr] [ ,... ]; Declare and initialize one or more variables while while (expression) statement A basic loop construct with with (object) statement Extend the scope chain (forbidden in strict mode) 5.8 Summary of JavaScript Statements | 113 Core JavaScript read more..

  • Page - 132

    read more..

  • Page - 133

    CHAPTER 6 Objects true false null undefined x var y = x; y y x 115 read more..

  • Page - 134

    for/in 6.1 Creating Objects new Object.create() 116 | Chapter 6: Objects read more..

  • Page - 135

    6.1.1 Object Literals var empty = {}; // An object with no properties var point = { x:0, y:0 }; // Two properties var point2 = { x:point.x, y:point.y+1 }; // More complex values var book = { "main title": read more..

  • Page - 136

    6.1.3 Prototypes null Object.prototype new prototype new Object() Object.prototype {} new Array() Array.prototype new Date() Date.prototype Object.prototype Object.prototype Date.prototype Object.prototype new Date() Date.prototype Object.prototype prototype 6.1.4 Object.create() Object.create() Object.create() Object.create() var o1 = Object.create({x:1, y:2}); // o1 inherits properties x and y. null toString() read more..

  • Page - 137

    {} new Object() Object.prototype var o3 = Object.create(Object.prototype); // o3 is like {} or new Object(). // inherit() returns a newly created object that inherits properties from the // prototype object p. It uses the ECMAScript 5 function Object.create() if // it is defined, and otherwise falls back to an older technique. function inherit(p) { if (p == null) throw read more..

  • Page - 138

    6.2 Querying and Setting Properties . [] var author = book.author; // Get the "author" property of the book. var name = author.surname // Get the "surname" property of the author. var title = book["main title"] // Get the "main title" property of the book. book.edition = 6; // Create an "edition" read more..

  • Page - 139

    [] var addr = ""; for(i = 0; i < 4; i++) { addr += customer["address" + i] + '\n'; address0 address1 address2 address3 customer portfolio portfolio.ibm 50 function addstock(portfolio, stockname, shares) { portfolio[stockname] = shares; } . portfolio [] for/in function getvalue(portfolio) { var total = 0.0; for(stock in portfolio) { read more..

  • Page - 140

    6.2.2 Inheritance inherit() x o o o x x null var o = {} // o inherits object methods from Object.prototype o.x = 1; // and has an own property x. var p = inherit(o); // p inherits properties from o and Object.prototype p.y = 2; // and has an own property y. var q = inherit(p); read more..

  • Page - 141

    o 6.2.3 Property Access Errors x o o.x undefined book.subtitle; // => undefined: property doesn't exist null undefined // Raises a TypeError exception. undefined doesn't have a length property var len = book.subtitle.length; book book.subtitle book.subtitle.length // A verbose and explicit technique var len = undefined; if (book) { if (book.subtitle) len = book.subtitle.length; } // A read more..

  • Page - 142

    p o o p defineProperty() o p o p o p o extensible false p o p o o 6.3 Deleting Properties delete delete delete book.author; // The book object now has no author property. delete book["main title"]; // Now it doesn't have "main title", either. delete delete true delete true o = {x:1}; // o has own property x and inherits read more..

  • Page - 143

    delete this.x = 1; // Create a configurable global property (no var) delete x; // And delete it delete x delete x; // SyntaxError in strict mode delete this.x; // This works 6.4 Testing Properties in hasOwnProperty() propertyIsEnumerable() in true var o = { x: 1 } "x" in o; // true: o has an own property read more..

  • Page - 144

    o.y !== undefined; // false: o doesn't have a property y o.toString !== undefined; // true: o inherits a toString property in in undefined var o = { x: undefined } // Property is explicitly set to undefined o.x !== undefined // false: property exists but is undefined o.y !== undefined // false: property doesn't read more..

  • Page - 145

    for(p in o) { if (typeof o[p] === "function") continue; // Skip methods } for/in extend() /* * Copy the enumerable properties of p to o, and return o. * If o and p have a property by the same name, o's property is overwritten. * This function does not handle getters and setters or copy attributes. */ function extend(o, p) { for(prop in read more..

  • Page - 146

    for(prop in p) { // For all props in p delete o[prop]; // Delete from o (deleting a // nonexistent prop is harmless) } return read more..

  • Page - 147

    undefined var o = { // An ordinary data property data_prop: value, // An accessor property defined as a pair of functions get accessor_prop() { /* function body here */ }, set accessor_prop(value) { /* function body here */ } }; function get set var p = { // x and y are regular read-write data properties. x: 1.0, read more..

  • Page - 148

    // theta is a read-only accessor property with getter only. get theta() { return Math.atan2(this.y, this.x); } }; this this r x y this.x this.y this p x y r theta var q = inherit(p); // Create a new object that inherits getters and setters q.x = 0, q.y = 0; // Create q's own data properties console.log(q.r); // And use the inherited accessor read more..

  • Page - 149

    6.7 Property Attributes value writable enumerable configurable get set value writable writa ble enumerable configurable get set Object.getOwnPropertyDescriptor() // Returns {value: 1, writable:true, enumerable:true, configurable:true} Object.getOwnPropertyDescriptor({x:1}, "x"); // Now query the octet property of the random object defined above. // Returns { get: /*func*/, set:undefined, enumerable:true, read more..

  • Page - 150

    Object.defineProperty() var o = {}; // Start with no properties at all // Add a nonenumerable data property x with value 1. Object.defineProperty(o, "x", { value : 1, writable: true, enumerable: false, read more..

  • Page - 151

    Object.create() Object.defineProperties() Object.create() Object.defineProperty() Object.defineProperties() Object.defineProperty() Object.defineProperties() false true true false extend() extend() Object.getOwnPropertyDescriptor() Object.defineProperty() Object.prototype 6.7 Property Attributes | 133 Core JavaScript read more..

  • Page - 152

    /* * Add a nonenumerable extend() method to Object.prototype. * This method extends the object on which it is called by copying properties * from the object passed as its argument. All property attributes are * copied, not just the property value. All own properties (even non- * enumerable ones) of the argument object are copied unless a property * with the read more..

  • Page - 153

    6.8 Object Attributes 6.8.1 The prototype Attribute o o prototype Object.prototype new prototype Object.create() null Object.getPrototypeOf() o o.constructor.prototype new constructor prototype Object.create() constructor Object() constructor.prototype Object.create() isPrototypeOf() p o p.isPrototypeOf(o) var p = {x:1}; // Define a prototype object. var o = Object.create(p); read more..

  • Page - 154

    __proto__ 6.8.2 The class Attribute toString() Object.prototype [object class] toString() toString() toString() Function.call() function classof(o) { if (o === null) return "Null"; if (o === undefined) return "Undefined"; return Object.prototype.toString.call(o).slice(8,-1); } classof() toString() null undefined Array Date Object.create classof(null) // => read more..

  • Page - 155

    6.8.3 The extensible Attribute Object.isExtensible() Object.preventExtensions() preventExtensions() Object.seal() Object.preventExtensions() Object.isSealed() Object.freeze() Object.isFrozen() Object.seal() Object.freeze() Object.preventExtensions() Object.seal() Object.freeze() // Create a sealed object with a frozen prototype and a nonenumerable property var o = Object.seal(Object.create(Object.freeze({x:1}), read more..

  • Page - 156

    6.9 Serializing Objects JSON.stringify() JSON.parse() o = {x:1, y:{z:[false,null,""]}}; // Define a test object s = JSON.stringify(o); // s is '{"x":1,"y":{"z":[false,null,""]}}' p = JSON.parse(s); // p is a deep copy of o true false null NaN Infinity -Infinity null Date.toJSON() JSON.parse() undefined read more..

  • Page - 157

    6.10.1 The toString() Method toString() + toString() var s = { x:1, y:1 }.toString(); toString() toString() Array.toString() Date.toString() Function.toString() toString() 6.10.2 The toLocaleString() Method toString() toLocaleString() toLocaleString() toString() toLocaleString() toLocaleString() toString() toLocale String() toString() 6.10.3 The toJSON() Method Object.prototype toJSON() JSON.stringify() toJSON() Date.toJSON() read more..

  • Page - 158

    6.10.4 The valueOf() Method valueOf() toString() valueOf() valueOf() Date.valueOf() valueOf() 140 | Chapter 6: Objects read more..

  • Page - 159

    CHAPTER 7 Arrays length length Array.prototype 7.1 Creating Arrays 141 read more..

  • Page - 160

    var empty = []; // An array with no elements var primes = [2, 3, 5, 7, 11]; // An array with 5 numeric elements var misc = [ 1.1, true, "a", ]; // 3 elements of various types + trailing comma var base = 1024; var table = [base, base+1, base+2, base+3]; var b = [[1,{x:1, y:2}], [2, {x:3, y:4}]]; undefined var count = read more..

  • Page - 161

    var a = ["world"]; // Start with a one-element array var value = a[0]; // Read element 0 a[1] = 3.14; // Write element 1 i = 2; a[i] = 3; // Write element 2 a[i + 1] = "hello"; // Write element 3 a[a[i]] = a[0]; // Read elements 0 read more..

  • Page - 162

    a = [true, false]; // This array has elements at indexes 0 and 1 a[2] // => undefined. No element at this index. a[-1] // => undefined. No property with this name. 7.3 Sparse Arrays length length Array() length a = new Array(5); // No elements, but a.length is 5. a = []; read more..

  • Page - 163

    [].length // => 0: the array has no elements ['a','b','c'].length // => 3: highest index is 2, length is 3 length length length i length length i+1 length n n a = [1,2,3,4,5]; // Start with a 5-element array. a.length = 3; // a is now [1,2,3]. a.length = 0; // Delete all elements. a is []. a.length read more..

  • Page - 164

    a = []; // Start with an empty array a.push("zero") // Add a value at the end. a = ["zero"] a.push("one", "two") // Add two more values. a = ["zero", "one", "two"] a a[a.length] unshift() delete a = [1,2,3]; delete a[1]; // a now has no element at index 1 1 in a read more..

  • Page - 165

    for(var i = 0, len = keys.length; i < len; i++) { // loop body remains the same } null undefined for(var i = 0; i < a.length; i++) { if (!a[i]) continue; // Skip null, undefined, and nonexistent elements // loop body here } for(var i = 0; i < a.length; i++) { if (a[i] === undefined) continue; // Skip undefined + nonexistent elements read more..

  • Page - 166

    for for/in forEach() var data = [1,2,3,4,5]; // This is the array we want to iterate var sumOfSquares = 0; // We want to compute the sum of the squares of data data.forEach(function(x) { // Pass each element of data to this function sumOfSquares += x*x; // add up the squares read more..

  • Page - 167

    7.8.1 join() Array.join() var a = [1, 2, 3]; // Create a new array with these three elements a.join(); // => "1,2,3" a.join(" "); // => "1 2 3" a.join(""); // => "123" var b = new Array(10); // An array of length 10 with no elements b.join('-') read more..

  • Page - 168

    return a-b; // Returns &lt; 0, 0, or &gt; 0, depending on order }); a.sort(function(a,b) {return b-a}); // Reverse numerical order toLowerCase() a = ['ant', 'Bug', 'cat', 'Dog'] a.sort(); // case-sensitive sort: ['Bug','Dog','ant',cat'] a.sort(function(s,t) { // Case-insensitive sort read more..

  • Page - 169

    a.slice(3); // Returns [4,5] a.slice(1,-1); // Returns [2,3,4] a.slice(-3,-2); // Returns [3] 7.8.6 splice() Array.splice() slice() concat() splice() splice() slice() splice() splice() splice() var a = [1,2,3,4,5,6,7,8]; a.splice(4); // Returns [5,6,7,8]; a is [1,2,3,4] a.splice(1,2); // Returns [2,3]; a is [1,4] a.splice(1,1); // Returns [4]; a is [1] splice() var a = read more..

  • Page - 170

    stack.push(3); // stack: [1,3] Returns 2 stack.pop(); // stack: [1] Returns 3 stack.push([4,5]); // stack: [1,[4,5]] Returns 2 stack.pop() // stack: [1] Returns [4,5] stack.pop(); // stack: [] Returns 1 7.8.8 unshift() and shift() read more..

  • Page - 171

    7.9 ECMAScript 5 Array Methods this 7.9.1 forEach() forEach() forEach() forEach() var data = [1,2,3,4,5]; // An array to sum // Compute the sum of the array elements var sum = 0; // Start at 0 data.forEach(function(value) { sum += read more..

  • Page - 172

    catch(e) { if (e === foreach.break) return; else throw e; } } foreach.break = new Error("StopIteration"); 7.9.2 map() map() a = [1, 2, 3]; b = a.map(function(x) { return x*x; }); // b is [1, 4, 9] map() forEach() map() map() 7.9.3 filter() filter() true false forEach() map() true true a = [5, 4, 3, 2, 1]; smallvalues = read more..

  • Page - 173

    a = [1,2,3,4,5]; a.every(function(x) { return x < 10; }) // => true: all values < 10. a.every(function(x) { return x % 2 === 0; }) // => false: not all values even. some() true true false false a = [1,2,3,4,5]; a.some(function(x) { return x%2===0; }) // => true a has some even numbers. a.some(isNaN) // => false: a read more..

  • Page - 174

    reduce() reduce() reduce() reduceRight() reduce() var a = [2, 3, 4] // Compute 2^(3^4). Exponentiation has right-to-left precedence var big = a.reduceRight(function(accumulator,value) { return Math.pow(value,accumulator); }); reduce() reduceRight() this Function.bind() every() some() read more..

  • Page - 175

    7.9.6 indexOf() and lastIndexOf() indexOf() lastIndexOf() indexOf() lastIndexOf() a = [0,1,2,1,0]; a.indexOf(1) // => 1: a[1] is 1 a.lastIndexOf(1) // => 3: a[3] is 1 a.indexOf(3) // => -1: no element has value 3 indexOf() lastIndexOf() indexOf() lastIndexOf() splice() indexOf() // Find all occurrences of a value x in an array a and return an array // read more..

  • Page - 176

    typeof instanceof [] instanceof Array // => true ({}) instanceof Array // => false instanceof instanceof isArray() var isArray = Function.isArray || function(o) { return typeof o === "object" && Object.prototype.toString.call(o) === "[object Array]"; }; Array.isArray() Object.prototype.toString() 7.11 Array-Like Objects length length Array.prototype length read more..

  • Page - 177

    var a = {}; // Start with a regular empty object // Add properties to make it "array-like" var i = 0; while(i < 10) { a[i] = i * i; i++; } a.length = i; // Now iterate through it as if it were a real array var total = 0; for(var j = 0; j < a.length; j++) total += a[j]; document.getElementsByTagName() // Determine if o is an read more..

  • Page - 178

    Array.prototype Function.call var a = {"0":"a", "1":"b", "2":"c", length:3}; // An array-like object Array.prototype.join.call(a, "+") // => "a+b+c" Array.prototype.slice.call(a, 0) // => ["a","b","c"]: true array copy Array.prototype.map.call(a, function(x) { return x.toUpperCase(); }) read more..

  • Page - 179

    s = "JavaScript" Array.prototype.join.call(s, " ") // => "J a v a S c r i p t" Array.prototype.filter.call(s, // Filter the characters of the string function(x) { return x.match(/[^aeiou]/); // Only match nonvowels }).join("") read more..

  • Page - 180

    read more..

  • Page - 181

    CHAPTER 8 Functions this this 163 read more..

  • Page - 182

    8.1 Defining Functions function function // Print the name and value of each property of o. Return undefined. function printprops(o) { for(var p in o) console.log(p + ": " + o[p] + "\n"); } // Compute the distance between Cartesian points (x1,y1) and (x2,y2). function distance(x1, y1, x2, y2) { var dx = x2 - x1; var read more..

  • Page - 183

    var f = function fact(x) { if (x <= 1) return 1; else return x*fact(x-1); }; // Function expressions can also be used as arguments to other functions: data.sort(function(a,b) { return a-b; }); // Function expressions are sometimes defined and immediately invoked: var tensquared = (function(x) {return x*x;}(10)); Function Names like_this() likeThis() $() 8.1 Defining Functions | 165 Core read more..

  • Page - 184

    return return return undefined return undefined return printprops() return printprops() undefined 8.1.1 Nested Functions function hypotenuse(a, b) { function square(x) { return x*x; } return Math.sqrt(square(a) + square(b)); } square() a b hypotenuse() try/catch/finally with 8.2 Invoking Functions if 166 | Chapter 8: Functions read more..

  • Page - 185

    call() apply() 8.2.1 Function Invocation printprops({x:1}); var total = distance(0,0,2,1) + distance(2,1,3,5); var probability = factorial(5)/factorial(13); undefined return return undefined return this undefined this // Define and invoke a function to determine if we're in strict mode. var strict = (function() { return read more..

  • Page - 186

    m() o.m(x, y); o.m x y o m o this var calculator = { // An object literal operand1: 1, operand2: 1, add: function() { // Note the use of the this keyword to refer to this object. this.result = this.operand1 + this.operand2; } }; calculator.add(); // A method invocation to compute 1+1. read more..

  • Page - 187

    Method Chaining // Find all headers, map to their ids, convert to an array and sort them $(":header").map(function() { return this.id }).get().sort(); this shape.setX(100).setY(100).setSize(50).setOutline("red").setFill("blue").draw(); this this this this this this undefined this this self var o = { // An object o. read more..

  • Page - 188

    8.2.3 Constructor Invocation new var o = new Object(); var o = new Object; prototype this new o.m() o return return return 8.2.4 Indirect Invocation call() apply() this call() apply() call() apply() 170 | Chapter 8: Functions read more..

  • Page - 189

    8.3 Function Arguments and Parameters 8.3.1 Optional Parameters undefined // Append the names of the enumerable properties of object o to the // array a, and return a. If a is omitted, create and return a new array. function getPropertyNames(o, /* optional */ a) { if (a === undefined) a = []; // If undefined, use a new array for(var property in read more..

  • Page - 190

    8.3.2 Variable-Length Argument Lists: The Arguments Object arguments f x x arguments[0] arguments[1] arguments length f arguments.length function f(x, y, z) { // First, verify that the right number of arguments was passed if (arguments.length != 3) { throw new Error("function f called with " + arguments.length + read more..

  • Page - 191

    arguments[] arguments length arguments[] arguments[] function f(x) { console.log(x); // Displays the initial value of the argument arguments[0] = null; // Changing the array element also changes x! console.log(x); // Now displays "null" } arguments[0] x arguments arguments arguments 8.3.2.1 The callee and caller properties callee read more..

  • Page - 192

    var factorial = function(x) { if (x <= 1) return 1; return x * arguments.callee(x-1); }; 8.3.3 Using Object Properties As Arguments // Copy length elements of the array from to the array to. // Begin copying with element from_start in the from array // and copy that element to to_start in the to array. // It is hard to remember the order of the read more..

  • Page - 193

    toString() arraycopy() isArrayLike() // Return the sum of the elements of array (or array-like object) a. // The elements of a must all be numbers or null and undefined are ignored. function sum(a) { if (isArrayLike(a)) { var total = 0; for(var i = 0; i < a.length; i++) { // Loop though all elements read more..

  • Page - 194

    if (isArray(element)) // If the argument is an array n = flexisum.apply(this, element); // compute its sum recursively else if (typeof element === "function") // Else if it's a function... n = Number(element()); read more..

  • Page - 195

    // We define some simple functions here function add(x,y) { return x + y; } function subtract(x,y) { return x - y; } function multiply(x,y) { return x * y; } function divide(x,y) { return x / y; } // Here's a function that takes one of the above functions // as an argument and invokes it on two operands function operate(operator, operand1, operand2) { return read more..

  • Page - 196

    8.4.1 Defining Your Own Function Properties // Initialize the counter property of the function object. // Function declarations are hoisted so we really can // do this assignment before the function declaration. uniqueInteger.counter = 0; // This function returns a different integer each time it is called. // It uses a property of itself to remember the next value to be read more..

  • Page - 197

    function mymodule() { // Module code goes here. // Any variables used by the module are local to this function // instead of cluttering up the global namespace. } mymodule(); // But don't forget to invoke the function! (function() { // mymodule function rewritten as an unnamed expression // Module code goes here. }()); // end the read more..

  • Page - 198

    for(var i = 1; i < arguments.length; i++) { var source = arguments[i]; for(var prop in source) o[prop] = source[prop]; } return o; }; } // If we get here, it means that the for/in loop read more..

  • Page - 199

    var scope = "global scope"; // A global variable function checkscope() { var scope = "local scope"; // A local variable function f() { return scope; } // Return the value in scope here return f(); } checkscope() // => "local scope" read more..

  • Page - 200

    Implementing Closures uniqueInteger() uniqueInteger() uniqueInteger() var uniqueInteger = (function() { // Define and invoke var counter = 0; // Private state of function below return function() { return counter++; }; read more..

  • Page - 201

    counter function counter() { var n = 0; return { count: function() { return n++; }, reset: function() { n = 0; } }; } var c = counter(), d = counter(); // Create two counters c.count() // => 0 d.count() read more..

  • Page - 202

    counter() n counter() addPrivateProperty() // This function adds property accessor methods for a property with // the specified name to the object o. The methods are named get<name> // and set<name>. If a predicate function is supplied, the setter // method uses it to test its argument for validity before storing it. // If the predicate returns false, the setter read more..

  • Page - 203

    // This function returns a function that always returns v function constfunc(v) { return function() { return v; }; } // Create an array of constant functions: var funcs = []; for(var i = 0; i < 10; i++) funcs[i] = constfunc(i); // The function at array element 5 returns the value 5. funcs[5]() // => 5 // Return an array of functions that return the values 0-9 read more..

  • Page - 204

    8.7 Function Properties, Methods, and Constructor typeof Function() Function() 8.7.1 The length Property arguments.length length check() arguments arguments.length arguments.callee.length check() f() check() // This function uses arguments.callee, so it won't work in strict mode. function check(args) { var actual = args.length; // The actual number of arguments read more..

  • Page - 205

    8.7.3 The call() and apply() Methods call() apply() call() Object.prototype.toString call() apply() this f() o call() apply() f.call(o); f.apply(o); o m o.m = f; // Make f a temporary method of o. o.m(); // Invoke it, passing no arguments. delete o.m; // Remove the temporary method. call() apply() this null undefined null undefined call() f() o f.call(o, 1, 2); apply() read more..

  • Page - 206

    var result = original.apply(this, arguments); // Invoke original. console.log(new Date(), "Exiting:", m); // Log message. return result; // Return result. }; } trace() 8.7.4 The bind() Method bind() bind() bind() f o f o function f(y) read more..

  • Page - 207

    Function.prototype.bind if (!Function.prototype.bind) { Function.prototype.bind = function(o /*, args */) { // Save the this and arguments values into variables so we can // use them in the nested function below. var self = this, boundArgs = arguments; // The return value of the bind() method is a read more..

  • Page - 208

    8.7.6 The Function() Constructor function Function() var f = new Function("x", "y", "return x*y;"); var f = function(x, y) { return x*y; } Function() Function() Function() Function() Function() Function() Function() var scope = "global"; function constructFunction() { var scope = "local"; return new Function("return scope"); // Does not read more..

  • Page - 209

    8.7.7 Callable Objects Window.alert() Document.getElementsById() exec() typeof function isFunction(x) { return Object.prototype.toString.call(x) === "[object Function]"; } isFunction() isArray() 8.8 Functional Programming map() reduce() 8.8 Functional Programming | 191 Core JavaScript read more..

  • Page - 210

    8.8.1 Processing Arrays with Functions var data = [1,1,3,5,5]; // This is our array of numbers // The mean is the sum of the elements divided by the number of elements var total = 0; for(var i = 0; i < data.length; i++) total += data[i]; var mean = total/data.length; // The mean of our data is 3 // To compute the standard read more..

  • Page - 211

    else return a.reduce(f); // Otherwise, no initial value. } : function(a, f, initial) { // This algorithm from the ES5 specification var i = 0, len = a.length, accumulator; // Start with the specified initial value, or the first value in a read more..

  • Page - 212

    var odd = not(even); // A new function that does the opposite [1,1,3,5,5].every(odd); // => true: every element of the array is odd not() mapper() map() // Return a function that expects an array argument and applies f to // each element, returning the array of return values. // Contrast this with the map() function from earlier. function mapper(f) { return read more..

  • Page - 213

    // A utility function to convert an array-like object (or suffix of it) // to a true array. Used below to convert arguments objects to real arrays. function array(a, n) { return Array.prototype.slice.call(a, n || 0); } // The arguments to this function are passed on the left function partialLeft(f /*, ...*/) { var args = arguments; // Save the outer arguments read more..

  • Page - 214

    not() var not = partialLeft(compose, function(x) { return !x; }); var even = function(x) { return x % 2 === 0; }; var odd = not(even); var isNumber = not(isNaN) var data = [1,1,3,5,5]; // Our data var sum = function(x,y) { return x+y; }; // Two elementary functions var product = function(x,y) { return x*y; read more..

  • Page - 215

    memoize() // Return the Greatest Common Divisor of two integers, using the Euclidian // algorithm: http://en.wikipedia.org/wiki/Euclidean_algorithm function gcd(a,b) { // Type checking for a and b has been omitted var t; // Temporary variable for swapping values if (a < b) t=b, b=a, a=t; read more..

  • Page - 216

    read more..

  • Page - 217

    CHAPTER 9 Classes and Modules 199 read more..

  • Page - 218

    9.1 Classes and Prototypes inherit() inherit() // range.js: A class representing a range of values. // This is a factory function that returns a new range object. function range(from, to) { // Use the inherit() function to create an object that inherits from the // prototype object defined below. The prototype object is stored as // a property read more..

  • Page - 219

    // This method works for textual and Date ranges as well as numeric. includes: function(x) { return this.from <= x && x <= this.to; }, // Invoke f once for each integer in the range. // This method works only for numeric ranges. foreach: function(f) { for(var x = Math.ceil(this.from); x <= this.to; x++) read more..

  • Page - 220

    function Range(from, to) { // Store the start and end points (state) of this new range object. // These are noninherited properties that are unique to this object. this.from = from; this.to = to; } // All Range objects inherit from this object. // Note that the property name must be "prototype" for this to work. Range.prototype = { read more..

  • Page - 221

    range.methods Range.prototype Range() Range.prototype 9.2.1 Constructors and Class Identity prototype Range() instanceof r r instanceof Range // returns true if r inherits from Range.prototype instanceof r Range Range.prototype instanceof instanceof 9.2.2 The constructor Property Range.prototype prototype Function.bind() prototype constructor constructor var F = function() {}; // This is a function object. read more..

  • Page - 222

    constructor constructor var o = new F(); // Create an object o of class F o.constructor === F // => true: the constructor property specifies the class Range() Range.prototype constructor con structor Range.prototype = { constructor: Range, // Explicitly set the constructor back-reference includes: function(x) { return this.from <= x && x <= this.to; }, read more..

  • Page - 223

    9.3 Java-Style Classes in JavaScript prototype defineClass() extend() // A simple function for defining simple classes function defineClass(constructor, // A function that sets instance properties 9.3 Java-Style Classes in JavaScript | 205 Core JavaScript read more..

  • Page - 224

    methods, // Instance methods: copied to prototype statics) // Class properties: copied to constructor { if (methods) extend(constructor.prototype, methods); if (statics) extend(constructor, statics); return constructor; } // This is a simple variant read more..

  • Page - 225

    return new Complex(this.r * that.r - this.i * that.i, this.r * that.i + this.i * that.r); }; // Return the real magnitude of a complex number. This is defined // as its distance from the origin (0,0) of the complex plane. Complex.prototype.mag = function() { return Math.sqrt(this.r*this.r + this.i*this.i); }; // read more..

  • Page - 226

    var c = new Complex(2,3); // Create a new object with the constructor var d = new Complex(c.i,c.r); // Use instance properties of c c.add(d).toString(); // => "{5,5}": use instance methods // A more complex expression that uses a class method and field Complex.parse(c.toString()). // Convert c to a string and back again, add(c.neg()). read more..

  • Page - 227

    // Code for the bind method goes here... }; } // Invoke the function f this many times, passing the iteration number // For example, to print "hello" 3 times: // var n = 3; // n.times(function(n) { console.log(n + " hello"); }); Number.prototype.times = function(f, context) { var n = Number(this); for(var i read more..

  • Page - 228

    classof() classof() instanceof constructor 9.5.1 The instanceof operator instanceof o instanceof c true o c.prototype o c.prototype true instanceof isPrototypeOf() r range.methods.isPrototypeOf(r); // range.methods is the prototype object. instanceof isPrototypeOf() instanceof Array() 210 | Chapter 9: Classes and Modules read more..

  • Page - 229

    9.5.2 The constructor property constructor function typeAndValue(x) { if (x == null) return ""; // Null and undefined don't have constructors switch(x.constructor) { case Number: return "Number: " + x; // Works for primitive types case String: return "String: '" + x + "'"; case Date: read more..

  • Page - 230

    type() classof() Function.getName() /** * Return the type of o as a string: * -If o is null, return "null", if o is NaN, return "nan". * -If typeof returns a value other than "object" return that value. * (Note that some implementations identify regexps as functions.) * -If the class of o is anything other than "Object", read more..

  • Page - 231

    getName() // This constructor has no name var Complex = function(x,y) { this.r = x; this.i = y; } // This constructor does have a name var Range = function Range(f,t) { this.from = f; this.to = t; } 9.5.4 Duck-Typing Range() > includes() <= includes() var lowercase = new Range("a", "z"); var thisYear = new Range(new Date(2009, 0, 1), new Date(2010, 0, read more..

  • Page - 232

    < length triathlon() walk() swim() bike() < ++ compareTo() succ() quacks() implements quacks() // Return true if o implements the methods specified by the remaining args. function quacks(o /*, ... */) { for(var i = 1; i < arguments.length; i++) { // for each argument after o var arg = arguments[i]; switch(typeof arg) { // If arg is read more..

  • Page - 233

    quacks() quacks() quacks(o, Array) for/in quacks() Object.getOwnProperty Names() 9.6 Object-Oriented Techniques in JavaScript instanceof 9.6.1 Example: A Set Class function Set() { // This is the constructor this.values = {}; // The properties of this object hold the set this.n = 0; // How many values are in the read more..

  • Page - 234

    for(var i = 0; i < arguments.length; i++) { // For each argument var val = arguments[i]; // The value to add to the set var str = Set._v2s(val); // Transform it to a string if (!this.values.hasOwnProperty(str)) { // If not already read more..

  • Page - 235

    function objectId(o) { var prop = "|**objectid**|"; // Private property name for storing ids if (!o.hasOwnProperty(prop)) // If the object has no id o[prop] = Set._v2s.next++; // Assign it the next available return o[prop]; // Return the id read more..

  • Page - 236

    toJSON: function() { return this.name; } // For serialization }; enumeration.values = []; // An array of the enumerated value objects // Now create the instances of this new type. for(name in namesToValues) { // For each value var e = inherit(proto); // read more..

  • Page - 237

    Card.orderByRank = function(a,b) { return a.compareTo(b); }; // A function for ordering cards as you would in bridge Card.orderBySuit = function(a,b) { if (a.suit < b.suit) return -1; if (a.suit > b.suit) return 1; if (a.rank < b.rank) return -1; if (a.rank > b.rank) return 1; return 0; }; // Define a class to represent a standard deck read more..

  • Page - 238

    + Object.prototype toString() toString() toString() toString() toLocaleString() toString() toLocaleString() toString() toLocale String() toString() toLocaleString() toLocaleString() valueOf() valueOf() + valueOf() toJSON() JSON.stringify() JSON.stringify() {"from":1, "to":3} {"r":1, "i":-1} JSON.parse() toJSON() toJSON() JSON.stringify() toJSON() toJSON() toJSON() toString() toJSON() valueOf() toString() read more..

  • Page - 239

    extend() Set.prototype // Add these methods to the Set prototype object. extend(Set.prototype, { // Convert a set to a string toString: function() { var s = "{", i = 0; this.foreach(function(v) { s += ((i++ > 0)?", ":"") + v; }); read more..

  • Page - 240

    // The Range class overwrote its constructor property. So add it now. Range.prototype.constructor = Range; // A Range is not equal to any nonrange. // Two ranges are equal if and only if their endpoints are equal. Range.prototype.equals = function(that) { if (that == null) return false; // Reject null and undefined if read more..

  • Page - 241

    compareTo() compareTo() this compareTo() this Replace this With this a < b a.compareTo(b) < 0 a <= b a.compareTo(b) <= 0 a > b a.compareTo(b) > 0 a >= b a.compareTo(b) >= 0 a == b a.compareTo(b) == 0 a != b a.compareTo(b) != 0 compareTo() Range.prototype.compareTo = function(that) { return this.from - that.from; }; Card.Rank valueOf() compareTo() equals() false compareTo() read more..

  • Page - 242

    // Order ranges by lower bound, or upper bound if the lower bounds are equal. // Throws an error if passed a non-Range value. // Returns 0 if and only if this.equals(that). Range.prototype.compareTo = function(that) { if (!(that instanceof Range)) throw new Error("Can't compare a Range with " + that); var diff = this.from - that.from; read more..

  • Page - 243

    equals() equals() Range.prototype.equals = generic.equals; generic.equals() equals() var generic = { // Returns a string that includes the name of the constructor function // if available and the names and values of all noninherited, nonfunction // properties. toString: function() { var s = '['; // If the object has read more..

  • Page - 244

    9.6.6 Private State from to from to from() to() from() to() function Range(from, to) { // Don't store the endpoints as properties of this object. Instead // define accessor functions that return the endpoint values. // These values are stored in the closure. this.from = function() { return from; }; this.to = function() { return to; }; read more..

  • Page - 245

    9.6.7 Constructor Overloading and Factory Methods function Set() { this.values = {}; // The properties of this object hold the set this.n = 0; // How many values are in the set // If passed a single array-like object, add its elements to the set // Otherwise, add all arguments to read more..

  • Page - 246

    return s; // Return the new set }; // An auxiliary constructor for the Set class. function SetFromArray(a) { // Initialize new object by invoking Set() as a function, // passing the elements of a as individual arguments. Set.apply(this, a); } // Set the prototype so that SetFromArray creates instances of Set read more..

  • Page - 247

    9.7.1 Defining a Subclass inherit() B.prototype = inherit(A.prototype); // Subclass inherits from superclass B.prototype.constructor = B; // Override the inherited constructor prop. Object.prototype defineClass() defineSubclass() Function.proto type.extend() // A simple function for creating simple subclasses function defineSubclass(superclass, // Constructor of the superclass read more..

  • Page - 248

    // The constructor function function SingletonSet(member) { this.member = member; // Remember the single member of the set } // Create a prototype object that inherits from the prototype of Set. SingletonSet.prototype = inherit(Set.prototype); // Now add properties to the prototype. // These properties override the properties of the same name from Set.prototype. read more..

  • Page - 249

    null undefined add() add() NonNullSet() /* * NonNullSet is a subclass of Set that does not allow null and undefined * as members of the set. */ function NonNullSet() { // Just chain to our superclass. // Invoke the superclass constructor as an ordinary function to initialize // the object that has been created by this constructor invocation. read more..

  • Page - 250

    var MySet = filteredSetSubclass(NonNullSet, function(x) {return typeof x !== "function";}); /* * This function returns a subclass of specified Set class and overrides * the add() method of that class to apply the specified filter. */ function filteredSetSubclass(superclass, filter) { var read more..

  • Page - 251

    }); }()); 9.7.3 Composition Versus Subclassing /* * A FilteredSet wraps a specified set object and applies a specified filter * to values passed to its add() method. All of the other core set methods * simply forward to the wrapped set instance. */ var FilteredSet = Set.extend( function FilteredSet(set, filter) { // The constructor read more..

  • Page - 252

    this.set.remove.apply(this.set, arguments); return this; }, contains: function(v) { return this.set.contains(v); }, size: function() { return this.set.size(); }, foreach: function(f,c) { this.set.foreach(f,c); } }); var s = new FilteredSet(new Set(), function(x) { read more..

  • Page - 253

    union() intersection() AbstractWritableSet Function.prototype.extend() // A convenient function that can be used for any abstract method function abstractmethod() { throw new Error("abstract method"); } /* * The AbstractSet class defines a single abstract method, contains(). */ function AbstractSet() { throw new Error("Can't instantiate abstract classes");} AbstractSet.prototype.contains = read more..

  • Page - 254

    this.foreach(function(v) { if (i++ > 0) s += ", "; s += v; }); return s + "}"; }, read more..

  • Page - 255

    { add: abstractmethod, remove: abstractmethod, union: function(that) { var self = this; that.foreach(function(v) { self.add(v); }); return this; }, intersection: function(that) { var read more..

  • Page - 256

    9.8 Classes in ECMAScript 5 9.8.1 Making Properties Nonenumerable for/in Object.defineProperty() // Wrap our code in a function so we can define variables in the function scope (function() { // Define objectId as a nonenumerable property inherited by all objects. // When this property is read, the getter function is invoked. // It has no read more..

  • Page - 257

    9.8.2 Defining Immutable Classes Object.defineProperties() Object.create() Object.defineProperties() new // This function works with or without 'new': a constructor and factory function function Range(from,to) { // These are descriptors for the read-only from and to properties. var props = { from: {value:from, enumerable:true, writable:false, configurable:false}, read more..

  • Page - 258

    // Make the named (or all) properties of o nonwritable and nonconfigurable. function freezeProps(o) { var props = (arguments.length == 1) // If 1 arg ? Object.getOwnPropertyNames(o) // use all props : Array.prototype.splice.call(arguments, 1); // else named props read more..

  • Page - 259

    9.8.3 Encapsulating Object State // This version of the Range class is mutable but encapsulates its endpoint // variables to maintain the invariant that from <= to. function Range(from, to) { // Verify that the invariant holds when we're created if (from > to) throw new Error("Range: from must be <= to"); // Define the accessor methods that read more..

  • Page - 260

    Object.prototype Object.seal(Object.prototype); var original_sort_method = Array.prototype.sort; Array.prototype.sort = function() { var start = new Date(); original_sort_method.apply(this, arguments); var end = new Date(); console.log("Array sort took " + (end - start) + " milliseconds."); }; freezeProps() Object.freeze() Object.seal() o p o.p o Object.defineProperty() read more..

  • Page - 261

    null Object.create() in hasOwnProperty() function StringSet() { this.set = Object.create(null); // Create object with no proto this.n = 0; this.add.apply(this, arguments); } // Note that with Object.create we can inherit from the superclass prototype // and define methods in a single call. Since we don't specify any of the // writable, enumerable, and read more..

  • Page - 262

    properties() Object.prototype hideProps() freezeProps() /* * Define a properties() method in Object.prototype that returns an * object representing the named properties of the object on which it * is invoked (or representing all own properties of the object, if * invoked with no arguments). The returned object defines four useful * methods: toString(), descriptors(), hide(), read more..

  • Page - 263

    Object.defineProperty(o, n, hidden); }); return this; }; // Make these properties read-only and nonconfigurable Properties.prototype.freeze = function() { var o = this.o, read more..

  • Page - 264

    9.9 Modules imports exports provide() require() require() 9.9.1 Objects As Namespaces Set Set.prototype _v2s() Set 246 | Chapter 9: Classes and Modules read more..

  • Page - 265

    var sets = {}; sets sets.SingletonSet = sets.AbstractEnumerableSet.extend(...); var s = new sets.SingletonSet(1); sets var Set = sets.Set; // Import Set to the global namespace var s = new Set(1,2,3); // Now we can use it without the sets prefix. collections.sets var collections; // Declare (or re-declare) the single global variable if (!collections) // If read more..

  • Page - 266

    9.9.2 Function Scope As a Private Namespace Set._v2s() // Declare a global variable Set and assign it the return value of this function // The open parenthesis and the function name below hint that the function // will be invoked immediately after being defined, and that it is the function // return value, not the function itself, that is being assigned. // Note that read more..

  • Page - 267

    // The public API for this module is the Set() constructor function. // We need to export that function from this private namespace so that // it can be used on the outside. In this case, we export the constructor // by returning it. It becomes the value of the assignment expression // on the first line above. read more..

  • Page - 268

    // ... Lots of code omitted... // Now export our API to the this object this.AbstractSet = AbstractSet; this.NotSet = NotSet; // And so on.... // Note no return value. }()); var collections; if (!collections) collections = {}; collections.sets = {}; (function namespace() { // ... Lots of code omitted... read more..

  • Page - 269

    CHAPTER 10 Pattern Matching with Regular Expressions 10.1 Defining Regular Expressions RegExp() / var pattern = /s$/; pattern RegExp() var pattern = new RegExp("s$"); s x \a \e \l \u \L \U \E \Q \A \Z \z \G (?<= (?<! (?# (? 251 read more..

  • Page - 270

    RegExp Literals and Object Creation {} [] var a = [] /java/ /s$/ 10.1.1 Literal Characters \ \n Character Matches Alphanumeric character Itself \0 The NUL character (\u0000) \t Tab (\u0009) \n Newline (\u000A) \v Vertical tab (\u000B) \f Form feed (\u000C) 252 | Chapter 10: Pattern Matching with Regular Expressions read more..

  • Page - 271

    Character Matches \r Carriage return (\u000D) \x nn The Latin character specified by the hexadecimal number nn; for example, \x0A is the same as \n \u xxxx The Unicode character specified by the hexadecimal number xxxx; for example, \u0009 is the same as \t \c X The control character ^ X; for example, \cJ is equivalent to the newline character \n ^ $ . * + ? = read more..

  • Page - 272

    /[\u0400-\u04FF]/ Character Matches [...] Any one character between the brackets. [^...] Any one character not between the brackets. . Any character except newline or another Unicode line terminator. \w Any ASCII word character. Equivalent to [a-zA-Z0-9_]. \W Any character that is not an ASCII word character. Equivalent to [^a-zA-Z0-9_]. \s Any Unicode whitespace character. \S Any character that read more..

  • Page - 273

    Character Meaning { n , m } Match the previous item at least n times but no more than m times. { n ,} Match the previous item n or more times. { n } Match exactly n occurrences of the previous item. ? Match zero or one occurrences of the previous item. That is, the previous item is optional. Equivalent to {0,1}. + Match one or more occurrences of read more..

  • Page - 274

    10.1.4 Alternation, Grouping, and References | /ab|cd|ef/ /\d{3}|[a-z]{4}/ /a|ab/ | * + ? /java(script)?/ /(ab|cd)+|ef/ /[a-z]+\d +/ (/[a-z]+(\d+)/) \ \1 \3 ([Ss]cript) \2 /([Jj]ava([Ss]cript)?)\sis\s(fun\w*)/ /['"][^'"]*['"]/ 256 | Chapter 10: Pattern Matching with Regular Expressions read more..

  • Page - 275

    /(['"])[^'"]*\1/ \1 /(['"])[^\1]*\1/ ( ) (?: ) /([Jj]ava(?:[Ss]cript)?)\sis\s(fun\w*)/ (?:[Ss]cript) ? \2 (fun\w*) Character Meaning | Alternation. Match either the subexpression to the left or the subexpression to the right. (...) Grouping. Group items into a single unit that can be used with *, +, ?, |, and so on. Also remember the characters that match this group for use with read more..

  • Page - 276

    ^ $ /^JavaScript$/ /\sJava\s/ \s \b /\bJava\b/ \B /\B[Ss]cript/ (?= ) /[Jj]ava([Ss]cript)?(?=\:)/ (?! /Java(?! Script)([A-Z]\w*)/ Character Meaning ^ Match the beginning of the string and, in multiline searches, the beginning of a line. $ Match the end of the string and, in multiline searches, the end of a line. \b Match a word boundary. That is, match the position between a \w character read more..

  • Page - 277

    10.1.6 Flags / i g m ^ $ /java$/im /\bjava\b/i g /\bjava\b/gi g Character Meaning i Perform case-insensitive matching. g Perform a global match—that is, find all matches rather than stopping after the first match. m Multiline mode. ^ matches beginning of line or beginning of string, and $ matches end of line or end of string. 10.2 String Methods for Pattern Matching search() read more..

  • Page - 278

    search() RegExp search() g replace() g replace() replace() RegExp() search() replace() // No matter how it is capitalized, replace it with the correct capitalization text.replace(/javascript/gi, "JavaScript"); replace() $ replace() // A quote is a quotation mark, followed by any number of // nonquotation-mark characters (which we remember), followed // by another quotation mark. var quote = read more..

  • Page - 279

    match() a a[0] a[1] replace() a[ n ] $ n var url = /(\w+):\/\/([\w.]+)\/(\S*)/; var text = "Visit my blog at http://www.example.com/~david"; var result = text.match(url); if (result != null) { var fullurl = result[0]; // Contains "http://www.example.com/~david" var protocol = result[1]; // Contains "http" var host = result[2]; read more..

  • Page - 280

    // Find all five-digit numbers in a string. Note the double \\ in this case. var zipcode = new RegExp("\\d{5}", "g"); RegExp() RegExp() 10.3.1 RegExp Properties source global g ignoreCase i multiline m lastIndex g exec() test() 10.3.2 RegExp Methods exec() match() exec() null match() index input match() exec() g match() exec() exec() g lastIndex exec() lastIndex exec() lastIndex lastIndex read more..

  • Page - 281

    exec() var pattern = /Java/g; var text = "JavaScript is more fun than Java!"; var result; while((result = pattern.exec(text)) != null) { alert("Matched '" + result[0] + "'" + " at position " + result.index + "; next search begins at " + pattern.lastIndex); } test() test() exec() true var pattern = read more..

  • Page - 282

    read more..

  • Page - 283

    CHAPTER 11 JavaScript Subsets and Extensions 265 read more..

  • Page - 284

    11.1 JavaScript Subsets 11.1.1 The Good Parts with continue eval() ++ -- == != === !== var var 11.1.2 Subsets for Security 266 | Chapter 11: JavaScript Subsets and Extensions read more..

  • Page - 285

    eval() Function() this this with window document document document caller callee arguments arguments call() apply() constructor prototype __proto__ . [] [] 11.1 JavaScript Subsets | 267 Core JavaScript read more..

  • Page - 286

    eval() with this ADSAFE eval() 268 | Chapter 11: JavaScript Subsets and Extensions read more..

  • Page - 287

    this eval() 11.2 Constants and Scoped Variables const const pi = 3.14; // Define a constant and give it a value. pi = 4; // Any future assignments to it are silently ignored. const pi = 4; // It is an error to redeclare a constant. var pi = 4; // This is also an error. const var let const let JavaScript Versions let read more..

  • Page - 288

    version() let <script type="application/javascript; version=1.8"> let var for for/in var let var var let let function oddsums(n) { let total = 0, result=[]; // Defined throughout the function for(let x = 1; x <= n; x++) { // x is only defined in the loop let odd = 2*x-1; // odd only read more..

  • Page - 289

    { // Begin a block to create a new variable scope let x = x + 1; // x is undefined, so x+1 is NaN console.log(x); // Prints NaN } var var ReferenceError undefined var let let let undefined let let let let let x=1, y=2; let (x=x+1,y=x+2) { // Note that we're shadowing variables console.log(x+y); // Prints read more..

  • Page - 290

    var let let [x,y] = [1,2]; // Same as let x=1, y=2 [x,y] = [x+1,y+1]; // Same as x = x + 1, y = y+1 [x,y] = [y,x]; // Swap the value of the two variables console.log([x,y]); // Prints [3,2] // Convert [x,y] coordinates to [r,theta] polar coordinates function polar(x,y) { return [Math.sqrt(x*x+y*y), Math.atan2(y,x)]; } // Convert polar read more..

  • Page - 291

    undefined r g b red green blue let transparent = {r:0.0, g:0.0, b:0.0, a:1.0}; // A RGBA color let {r:red, g:green, b:blue} = transparent; // red=0.0,green=0.0,blue=0.0 Math // Same as let sin=Math.sin, cos=Math.cos, tan=Math.tan let {sin:sin, cos:cos, tan:tan} = Math; // A nested data structure: an object that contains an array of objects let data = { name: read more..

  • Page - 292

    11.4 Iteration for each 11.4.1 The for/each Loop for/each for/each for each for/in let o = {one: 1, two: 2, three: 3} for(let p in o) console.log(p); // for/in: prints 'one', 'two', 'three' for each (let v in o) console.log(v); // for/each: prints 1, 2, 3 for/each a = ['one', 'two', 'three']; for(let p in a) console.log(p); // Prints array indexes read more..

  • Page - 293

    next() next() counter() next() // A function that returns an iterator; function counter(start) { let nextValue = Math.round(start); // Private state of the iterator return { next: function() { return nextValue++; }}; // Return iterator obj } let serialNumberGenerator = counter(1000); let sn1 = serialNumberGenerator.next(); // 1000 let sn2 = serialNumberGenerator.next(); read more..

  • Page - 294

    for/in in for/in __iterator__() next() for/in StopIteration range() for/in while // Return an iterable object that represents an inclusive range of numbers function range(min,max) { return { // Return an object representing a range. get min() { return min; }, // The range's bounds are immutable. read more..

  • Page - 295

    for/in next() Iterator() for(let [k,v] in Iterator({a:1,b:2})) // Iterate keys and values console.log(k + "=" + v); // Prints "a=1" and "b=2" Iterator() true Iterator() o = {x:1, y:2} // An object with two properties Object.prototype.z = 3; read more..

  • Page - 296

    next() StopIteration for/in // Define a generator function for iterating over a range of integers function range(min, max) { for(let i = Math.ceil(min); i <= max; i++) yield i; } // Invoke the generator function to obtain a generator, then iterate it. for(let n in range(3,8)) console.log(n); // Prints numbers 3 through 8. // A generator function that yields the Fibonacci read more..

  • Page - 297

    // A generator to yield the lines of the string s one at a time. // Note that we don't use s.split(), because that would process the entire // string at once, allocating an array, and we want to be lazy instead. function eachline(s) { let p; while((p = s.indexOf('\n')) != -1) { yield s.substring(0,p); s = read more..

  • Page - 298

    send() yield yield yield next() send() throw() yield throw() // A generator function that counts from an initial value. // Use send() on the generator to specify an increment. // Use throw("reset") on the generator to reset to the initial value. // This is for example only; this use of throw() is bad style. function counter(initial) { let nextValue = initial; read more..

  • Page - 299

    evensquares.push(x*x); } [ expression for ( variable in object ) if ( condition ) ] for/in for/each variable in object in var let let if conditional for false if if (true) expression for conditional data = [2,3,4, -5]; // An array of numbers squares = [x*x for each (x in data)]; // Square each one: [4,9,16,25] // Now read more..

  • Page - 300

    map() function map(i, f) { // A generator that yields f(x) for each element of i for(let x in i) yield f(x); } map() h g let h = (f(x) for (x in g)); eachline() let lines = eachline(text); let trimmed = (l.trim() for (l in lines)); let nonblank = (l for (l in trimmed) if (l.length > 0 && l[0]!='#')); 11.5 Shorthand Functions return let succ = read more..

  • Page - 301

    11.6 Multiple Catch Clauses try/catch if try { // multiple exception types can be thrown here throw 1; } catch(e if e instanceof ReferenceError) { // Handle reference errors here } catch(e if e === "quit") { // Handle the thrown string "quit" } catch(e if typeof e === "string") { // Handle any other thrown read more..

  • Page - 302

    typeof typeof // Create an XML object var pt = <periodictable> <element id="1"><name>Hydrogen</name></element> <element id="2"><name>Helium</name></element> <element id="3"><name>Lithium</name></element> </periodictable>; // Add a new element to the table pt.element += read more..

  • Page - 303

    pt.element += new XML('<element id="5"><name>Boron</name></element>'); XMLList() XML() pt.element += new XMLList('<element id="6"><name>Carbon</name></element>' + '<element id="7"><name>Nitrogen</name></element>'); var elements = pt.element; // Evaluates to a list of all read more..

  • Page - 304

    for/each for/each for/in // Print the names of each element in the periodic table for each (var e in pt.element) { console.log(e.name); } // Print the atomic numbers of the elements for each (var n in pt.element.@*) console.log(n); // Modify the <element> tag for Hydrogen to add a new attribute // and a new child element so that it looks like this: // // read more..

  • Page - 305

    var bodyns = tagname.uri; var localname = tagname.localName; // Selecting the <svg> element is trickier because it is not in the // default namespace. So create a Namespace object for svg, and use the // :: operator to add a namespace to a tagname var svg = new Namespace('http://www.w3.org/2000/svg'); var color = d..svg::rect.@fill // "red" 11.7 E4X: ECMAScript for XML | read more..

  • Page - 306

    read more..

  • Page - 307

    CHAPTER 12 Server-Side JavaScript 12.1 Scripting Java with Rhino 289 read more..

  • Page - 308

    Obtaining Rhino java -jar rhino1_7R2/js.jar program.js program.js // Embedding-specific globals: Type help() at the rhino prompt for more print(x); // Global print function prints to the console version(170); // Tell Rhino we want JS 1.7 language features load(filename,...); // Load and execute one or more files of JavaScript code readFile(file); read more..

  • Page - 309

    importPackage(java.util); importPackage(java.net); // Another technique: pass any number of classes and packages to JavaImporter() // and use the object it returns in a with statement var guipkgs = JavaImporter(java.awt, java.awt.event, Packages.javax.swing); with (guipkgs) { /* Classes like Font, ActionListener and JFrame defined here */ } new // Objects: instantiate Java classes with new read more..

  • Page - 310

    // Suppose the Java object o has a method named f that expects an int or // a float. In JavaScript, you must specify the signature explicitly: o['f(int)'](3); // Call the int method o['f(float)'](Math.PI); // Call the float method for/in importClass(java.lang.System); for(var m in System) print(m); // Print static members of the java.lang.System for(m in read more..

  • Page - 311

    var o = new JavaAdapter(java.awt.event.ActionListener, java.lang.Runnable, { run: function() {}, // Implements Runnable actionPerformed: function(e) {} // Implements ActionListener }); javaException try { java.lang.System.getProperty(null); // null is not a legal argument } catch(e) { // e read more..

  • Page - 312

    /* * A download manager application with a simple Java GUI */ // Import the Swing GUI components and a few other classes importPackage(javax.swing); importClass(javax.swing.border.EmptyBorder); importClass(java.awt.event.ActionListener); importClass(java.net.URL); importClass(java.io.FileOutputStream); importClass(java.lang.Thread); // Create some GUI widgets var frame = new JFrame("Rhino URL Fetcher"); read more..

  • Page - 313

    catch(e) { // Display a dialog box if anything goes wrong JOptionPane.showMessageDialog(frame, e.message, "Exception", JOptionPane.ERROR_MESSAGE); } }); // Use java.net.URL, etc. to download the content of the URL and use // java.io.File, etc. to read more..

  • Page - 314

    } } } 12.2 Asynchronous I/O with Node Obtaining Node node program.js print() load() // Node defines console.log() for debugging output like browsers do. console.log("Hello Node"); // Debugging output to console // Use require() instead of load(). It loads and executes (only once) the // named module, returning an object that contains its exported read more..

  • Page - 315

    setTimeout() setInterval() clearTimeout() clearInterval() // Say hello one second from now. setTimeout(function() { console.log("Hello World"); }, 1000); process process.version // Node version string process.argv // Command-line args as an array argv[0] is "node" process.env // Enviroment variables as an object. e.g.: process.env.PATH process.pid read more..

  • Page - 316

    // POSIX signals like SIGINT, SIGHUP and SIGTERM generate events process.on("SIGINT", function() { console.log("Ignored Ctrl-C"); }); s // Input stream s: s.on("data", f); // When data is available, pass it as an argument to f() s.on("end", f); // "end" event fired on EOF when no more data will arrive s.on("error", f); // If something read more..

  • Page - 317

    end.copy(more, 0, 8, 16); // Copy elements 8-15 of end[] into more[] more[0] // => 248 // Buffers also do binary <=> text conversion // Valid encodings: "utf8", "ascii" and "base64". "utf8" is the default. var buf = new Buffer("2πr", read more..

  • Page - 318

    #! /usr/local/bin/node var fs = require("fs"), path = require("path"); // Load the modules we need var dir = process.cwd(); // Current directory if (process.argv.length > 2) dir = process.argv[2]; // Or from the command line var files = fs.readdirSync(dir); // read more..

  • Page - 319

    var http = require('http'); // HTTP server API var fs = require('fs'); // For working with local files var server = new http.Server(); // Create a new HTTP server server.listen(8000); // Run it on port 8000. // Node uses the "on()" method to register event handlers. // When the server gets a new request, run read more..

  • Page - 320

    case "css": type = "text/css; charset=UTF-8"; break; case "txt" : type = "text/plain; charset=UTF-8"; break; case "manifest": type = "text/cache-manifest; charset=UTF-8"; break; default: type = "application/octet-stream"; break; } read more..

  • Page - 321

    // Parse the URL and get the pieces we need from it url = require('url').parse(url); var hostname = url.hostname, port = url.port || 80; var path = url.pathname, query = url.query; if (query) path += "?" + query; // Make a simple GET request var client = require("http").createClient(port, hostname); read more..

  • Page - 322

    response.setEncoding("utf8"); // Assume it is text var body = "" // To save the response body response.on("data", function(chunk) { body += chunk; }); response.on("end", function() { // When read more..

  • Page - 323

    PART II Client-Side JavaScript read more..

  • Page - 324

    read more..

  • Page - 325

    CHAPTER 13 JavaScript in Web Browsers 13.1 Client-Side JavaScript window location 307 read more..

  • Page - 326

    // Set the location property to navigate to a new web page window.location = "http://www.oreilly.com/"; alert() setTimeout() // Wait 2 seconds and then say hello setTimeout(function() { alert("hello world"); }, 2000); window window window document getElementById() id // Find the element with id="timestamp" var timestamp = document.getElementById("timestamp"); getElementById() // read more..

  • Page - 327

    // Update the content of the timestamp element when the user clicks on it timestamp.onclick = function() { this.innerHTML = new Date().toString(); } onload onload onload <script> <!DOCTYPE html> <html> <head> <style> /* CSS styles for this page */ .reveal * { display: none; } /* Children of class="reveal" are not shown */ .reveal *.handle { display: read more..

  • Page - 328

    </body> </html> 13.1.1 JavaScript in Web Documents 13.1.2 JavaScript in Web Applications 310 | Chapter 13: JavaScript in Web Browsers read more..

  • Page - 329

    13.2 Embedding JavaScript in HTML <script> </script> src <script> onclick onmouseover javascript: javascript: src <script> src 13.2 Embedding JavaScript in HTML | 311 Client-Side JavaScript read more..

  • Page - 330

    13.2.1 The <script> Element <script> </script> <script> // Your JavaScript code goes here </script> <script> < & <script><![CDATA[ // Your JavaScript code goes here ]]></script> onload <!DOCTYPE html> <!-- This is an HTML5 file --> <html> read more..

  • Page - 331

    13.2.2 Scripts in External Files <script> src <script src="../../scripts/util.js"></script> <script> <script> src <script> </script> </script> src <script> </script> <script/> src <script> <script> <script src=""> </script> src src src 13.2 Embedding JavaScript in HTML | 313 Client-Side JavaScript read more..

  • Page - 332

    src 13.2.3 Script Type <script> type <script type="text/vbscript"> ' VBScript code goes here </script> type language <script> type <script language="javascript"> // JavaScript code here... </script> language <script> type <script> type text HTMLElement src type 13.2.4 Event Handlers in HTML onclick onmouseover 314 | Chapter 13: JavaScript in Web Browsers read more..

  • Page - 333

    onclick <input type="checkbox" name="options" value="giftwrap" onchange="order.options.giftwrap = this.checked;"> onchange 13.2.5 JavaScript in URLs javascript: /* */ // javascript: undefined javascript: href <a> action <form> window.open() <a href="javascript:new Date().toLocaleTimeString();"> What time is it? </a> http: 13.2 Embedding JavaScript in read more..

  • Page - 334

    <a href="javascript:alert(new Date().toLocaleTimeString());"> Check the time without overwriting the document </a> alert() undefined javascript: onclick onclick <button> <a> javascript: void undefined <a href="javascript:void window.open('about:blank');">Open Window</a> void Window.open() [object Window] javascript: javascript: javascript: 13.2.5.1 Bookmarklets javascript: javascript: <a> read more..

  • Page - 335

    e = prompt("Expression: " + e + "\n" + r + "\n", e); try { r = "Result: " + eval(e); } /* Try to evaluate the expression */ catch(ex) { r = ex; } /* Or remember the error instead */ } while(e); /* Continue until no expression entered or Cancel clicked */ void 0; read more..

  • Page - 336

    javascript: onload 13.3.1 Synchronous, Asynchronous, and Deferred Scripts document.write() <h1>Table of Factorials</h1> <script> function factorial(n) { // A function to compute factorials 318 | Chapter 13: JavaScript in Web Browsers read more..

  • Page - 337

    if (n <= 1) return n; else return n*factorial(n-1); } document.write("<table>"); // Begin an HTML table document.write("<tr><th>n</th><th>n!</th></tr>"); // Output table header for(var i = 1; i <= 10; i++) { // Output 10 read more..

  • Page - 338

    async <script> loadasync() // Asynchronously load and execute a script from a specified URL function loadasync(url) { var head = document.getElementsByTagName("head")[0]; // Find document <head> var s = document.createElement("script"); // Create a <script> element s.src = url; read more..

  • Page - 339

    window.onload = function() { ... }; document.getElementById("button1").onclick = function() { ... }; function handleResponse() { ... } request.onreadystatechange = handleResponse; event <button> addEventListener() window.addEventListener("load", function() {...}, false); request.addEventListener("readystatechange", function() {...}, false); addEventListener() attachEvent() window.attachEvent("onload", function() read more..

  • Page - 340

    setTimeout() setInterval() setTimeout() setTimeout() setInterval() setTimeout() addEventListener() attachEvent() onLoad() onLoad() // Register the function f to run when the document finishes loading. // If the document has already loaded, run it asynchronously ASAP. function onLoad(f) { if (onLoad.loaded) // If document is already loaded read more..

  • Page - 341

    setTimeout() setInterval() 13.3.4 Client-Side JavaScript Timeline document.readyState <script> async defer document.write() <script> <script> async 13.3 Execution of JavaScript Programs | 323 Client-Side JavaScript read more..

  • Page - 342

    document.write() <script> document.readyState defer document.write() async async document.readyState document.readyState defer async loadasync() 324 | Chapter 13: JavaScript in Web Browsers read more..

  • Page - 343

    13.4 Compatibility and Interoperability <canvas> addEventListener() <canvas> addEventListener() 13.4 Compatibility and Interoperability | 325 Client-Side JavaScript read more..

  • Page - 344

    326 | Chapter 13: JavaScript in Web Browsers read more..

  • Page - 345

    A Word about “Current Browsers” 13.4 Compatibility and Interoperability | 327 Client-Side JavaScript read more..

  • Page - 346

    13.4.1 Compatibility Libraries <canvas> <canvas> forEach() map() reduce() addEventListener() attachEvent() attachEvent() addEventListener() addEvent() addEventListener() attachEvent() addEvent() addEventListener() attachEvent() bind() addEventListener() attachEvent() 13.4.2 Graded Browser Support 328 | Chapter 13: JavaScript in Web Browsers read more..

  • Page - 347

    13.4.3 Feature Testing if (element.addEventListener) { // Test for this W3C method before using it element.addEventListener("keydown", handler, false); element.addEventListener("keypress", handler, false); } else if (element.attachEvent) { // Test for this IE method before using it element.attachEvent("onkeydown", handler); read more..

  • Page - 348

    <!DOCTYPE html> document.compatMode undefined compatMode compatMode 13.4.5 Browser Testing User-Agent 13.4.6 Conditional Comments in Internet Explorer 330 | Chapter 13: JavaScript in Web Browsers read more..

  • Page - 349

    <!--[if IE 6]> This content is actually inside an HTML comment. It will only be displayed in IE 6. <![endif]--> <!--[if lte IE 7]> This content will only be displayed by IE 5, 6 and 7 and earlier. lte stands for "less than or equal". You can also use "lt", "gt" and "gte". <![endif]--> <!--[if !IE]> <--> This is normal HTML read more..

  • Page - 350

    // This code is inside a conditional comment, which is also a // regular JavaScript comment. IE runs it but other browsers ignore it. alert('You are using Internet Explorer); @else*/ // This code is no longer inside a JavaScript comment, but is still // inside the IE conditional comment. This means that all browsers read more..

  • Page - 351

    13.6.1 What JavaScript Can’t Do 13.6 Security | 333 Client-Side JavaScript read more..

  • Page - 352

    value 13.6.2 The Same-Origin Policy <iframe> http: https: src <script> 334 | Chapter 13: JavaScript in Web Browsers read more..

  • Page - 353

    13.6.2.1 Relaxing the same-origin policy domain domain domain domain domain document.domain Origin: Access-Control- Allow-Origin 13.6 Security | 335 Client-Side JavaScript read more..

  • Page - 354

    postMessage() onmessage 13.6.3 Scripting Plug-ins and ActiveX Controls 13.6.4 Cross-Site Scripting <script> var name = decodeURIComponent(window.location.search.substring(1)) || ""; document.write("Hello " + name); </script> 336 | Chapter 13: JavaScript in Web Browsers read more..

  • Page - 355

    window.location.search document.write() http://www.example.com/greet.html?David http://www.example.com/greet.html?%3Cscript%3Ealert('David')%3C/script%3E %3C %3E http://siteA/greet.html?name=%3Cscript src=siteB/evil.js%3E%3C/script%3E <script> name = name.replace(/</g, "&lt;").replace(/>/g, "&gt;"); toStaticHTML() <script> toSta ticHTML() sandbox <iframe> 13.6 Security | 337 Client-Side JavaScript read more..

  • Page - 356

    13.6.5 Denial-of-Service Attacks alert() setInterval() 13.7 Client-Side Frameworks 338 | Chapter 13: JavaScript in Web Browsers read more..

  • Page - 357

    13.7 Client-Side Frameworks | 339 Client-Side JavaScript read more..

  • Page - 358

    read more..

  • Page - 359

    CHAPTER 14 The Window Object setTimeout() setInterval() location history navigator screen alert() confirm() prompt() showModalDialog() onerror 14.1 Timers setTimeout() setInterval() 341 read more..

  • Page - 360

    setTimeout() setTimeout() clearTimeout() setInterval() setTimeout() setInterval(updateClock, 60000); // Call updateClock() every 60 seconds setTimeout() setInterval() clearInterval() setTimeout() setInterval() clearInterval() /* * Schedule an invocation or invocations of f() in the future. * Wait start milliseconds, then call f() every interval milliseconds, * stopping after a total of start+end read more..

  • Page - 361

    setTimeout() 14.2 Browser Location and Navigation location location window.location === document.location // always true URL document.URL 14.2.1 Parsing URLs location href toString() href toString() location location.href protocol host hostname port pathname search hash <a> <area> Location Link hash search hash search urlArgs() search decodeURIComponent() Global 14.2 Browser Location and Navigation read more..

  • Page - 362

    /* * This function parses ampersand-separated name=value argument pairs from * the query string of the URL. It stores the name=value pairs in * properties of an object and returns that object. Use it like this: * * var args = urlArgs(); // Parse args from URL * var q = args.q || ""; // Use argument, if defined, or a default value * var n read more..

  • Page - 363

    location location = "page2.html"; // Load the next page #top location = "#top"; // Jump to the top of the document hash location.search = "?page=" + (pagenum+1); // load the next page 14.3 Browsing History history length back() forward() go() history.go(-2); // Go back 2, like clicking read more..

  • Page - 364

    <iframe> open() write() setInterval() 14.4 Browser and Screen Information navi gator screen 14.4.1 The Navigator Object navigator clientInformation navigator 346 | Chapter 14: The Window Object read more..

  • Page - 365

    appName appVersion appVersion userAgent USER-AGENT appVersion appVersion platform navigator.appName appName appVersion navigator.userAgent navigator.userAgent // Define browser.name and browser.version for client sniffing, using code // derived from jQuery 1.4.1. Both the name and number are strings, and both // may differ from the public browser name and version. Detected names are: // // read more..

  • Page - 366

    return { name: match[1] || "", version: match[2] || "0" }; }()); onLine navigator.onLine geolocation javaEnabled() true cookiesEnabled() true 14.4.2 The Screen Object screen width height avail Width availHeight colorDepth window.screen 14.5 Dialog Boxes alert() confirm() prompt() do { var name = prompt("What is your name?"); read more..

  • Page - 367

    "Click Okay to proceed or Cancel to re-enter."); } while(!correct) alert("Hello, " + name); // Display a plain message alert() confirm() prompt() alert() alert() confirm() prompt() confirm() prompt() alert() Window.alert Window.con firm Window.prompt alert() confirm() prompt() showModalDialog() showModalDialog() window.dialogArguments read more..

  • Page - 368

    <!-- This is not a stand-alone HTML file. It must be invoked by showModalDialog(). It expects window.dialogArguments to be an array of strings. The first element of the array is displayed at the top of the dialog. Each remaining element is a label for a single-line text input field. Returns an array of input field values when the user clicks Okay. read more..

  • Page - 369

    14.6 Error Handling onerror onerror onerror window.onerror onerror onerror false true onerror try/catch // Display error messages in a dialog box, but never more than 3 window.onerror = function(msg, url, line) { if (onerror.num++ < onerror.max) { alert("ERROR: " + msg + "\n" + url + ":" + line); return true; } } read more..

  • Page - 370

    <button id="okay"/> okay id x id document.getElementById() var ui = ["input","prompt","heading"]; // An array of element ids ui.forEach(function(id) { // For each id look up the element ui[id] = document.getElementById(id); // and store it in a property }); ui.input ui.prompt ui.heading input heading read more..

  • Page - 371

    name name id <iframe> name id <iframe> 14.8 Multiple Windows and Frames <iframe> <iframe> <frameset> <frame> <frame> 14.8 Multiple Windows and Frames | 353 Client-Side JavaScript read more..

  • Page - 372

    14.8.1 Opening and Closing Windows open() Window.open() open() about:blank open() Window Names open() target <a> <form> target name Window.open() name <iframe> name name name open() 354 | Chapter 14: The Window Object read more..

  • Page - 373

    var w = window.open("smallwin.html", "smallwin", "width=400,height=350,status=yes,resizable=yes"); Window.open() open() true false false open() window var w = window.open(); // Open a new, blank window. w.alert("About to visit http://example.com"); // Call its alert() method read more..

  • Page - 374

    14.8.1.1 Closing windows open() close() w w.close(); window.close(); window close() close() close() close() <iframe> closed true document 14.8.2 Relationships Between Frames open() opener window self parent parent.history.back(); parent parent == self; // For any top-level window parent.parent top top top top parent 356 | Chapter 14: The Window Object read more..

  • Page - 375

    parent top <iframe> <iframe> <iframe id="f1"> var iframeElement = document.getElementById("f1"); <iframe> contentWindow var childFrame = document.getElementById("f1").contentWindow; <iframe> frameElement null frameElement var elt = document.getElementById("f1"); var win = elt.contentWindow; win.frameElement === elt // Always true for frames window.frameElement read more..

  • Page - 376

    name id <iframe> name name target window.open() 14.8.3 JavaScript in Interacting Windows <iframe> i var i = 3; i window.i parent.A.i = 4; // Change the value of a variable in frame A function var f f f() f parent.B.f(); // Invoke a function defined in frame B var f = parent.B.f; f() f 358 | Chapter 14: The Window Object read more..

  • Page - 377

    var s = new Set(); Set() var s = new parent.Set(); var Set = top.Set(); var s = new Set(); String() String.prototype String.prototype instanceof instanceof false String() The WindowProxy Object 14.8 Multiple Windows and Frames | 359 Client-Side JavaScript read more..

  • Page - 378

    window self top parent frames window.open() this 360 | Chapter 14: The Window Object read more..

  • Page - 379

    CHAPTER 15 Scripting Documents document referrer write() 15.1 Overview of the DOM 361 read more..

  • Page - 380

    <body> <p> <html> <head> <title>Sample Document</title> </head> <body> <h1>An HTML Document</h1> <p>This is a <i>simple</i> document. </html> 362 | Chapter 15: Scripting Documents read more..

  • Page - 381

    Node 15.1 Overview of the DOM | 363 Client-Side JavaScript read more..

  • Page - 382

    15.2 Selecting Document Elements document id name 15.2.1 Selecting Elements By ID id getElementById() var section1 = document.getElementById("section1"); id getElements() 364 | Chapter 15: Scripting Documents read more..

  • Page - 383

    /** * This function expects any number of string arguments. It treats each * argument as an element id and calls document.getElementById() for each. * Returns an object that maps ids to the corresponding Element object. * Throws an Error object if any of the ids is undefined. */ function getElements(/*ids...*/) { var elements = {}; read more..

  • Page - 384

    <iframe> // Get the Element object for the <form name="shipping_address"> element var form = document.shipping_address; getElementsBy Name() 15.2.3 Selecting Elements by Type getElementsByTagName() <span> var spans = document.getElementsByTagName("span"); getElementsByName() getElementsByTagName() <p> var firstpara = document.getElementsByTagName("p")[0]; getElementsByTagName() spans read more..

  • Page - 385

    images forms links <img> <form> <a> <a> href <form> document.shipping_address document.forms document.forms.shipping_address; embeds plugins <embed> anchors <a> name href <scripts> <script> document.body <body> document.head <head> <head> <body> documentElement <html> NodeLists and HTMLCollections getElementsByName() getElementsByTagName() document.images document.forms read more..

  • Page - 386

    item() namedItem() getElementsByTagName('div') <div> length <div> length var snapshot = Array.prototype.slice.call(nodelist, 0); 15.2.4 Selecting Elements by CSS Class class class class className class class getElementsByClassName() class getElementsByTagName() getElementsByClassName() getElementsByClassName() class class getElementsByClassName() getElementsByClassName() // Find all elements that have "warning" in read more..

  • Page - 387

    // Find all descendants of the element named "log" that have the class // "error" and the class "fatal" var log = document.getElementById("log"); var fatal = log.getElementsByClassName("fatal error"); <!DOCTYPE> class getElementsByClassName() getElementsByClassName() querySelectorAll() getElementsByClassName() 15.2.5 Selecting Elements with CSS Selectors #nav read more..

  • Page - 388

    querySelectorAll() querySelectorAll() querySelectorAll() querySelectorAll() querySelectorAll() querySelector() querySelectorAll() null :first-line :first-letter querySelectorAll() querySelector() :link :visited querySelector() querySelectorAll() querySelectorAll() querySelectorAll() querySelectorAll() $() 370 | Chapter 15: Scripting Documents read more..

  • Page - 389

    15.2.6 document.all[] document.all[] document.all[] getElementById() getElementsByTag Name() document.all[0] // The first element in the document document.all["navbar"] // Element (or elements) with id or name "navbar" document.all.navbar // Ditto document.all.tags("div") // All <div> elements in the document read more..

  • Page - 390

    nodeType nodeValue nodeName document.childNodes[0].childNodes[1] document.firstChild.firstChild.nextSibling <html><head><title>Test</title></head><body>Hello World!</body></html> <body> nodeType nodeName <html> <head> <head> <body> 15.3.2 Documents As Trees of Elements children childNodes childNodes children children Node.parentNode parentNode 372 | Chapter 15: Scripting read more..

  • Page - 391

    firstElementChild lastElementChild firstChild lastChild nextElementSibling previousElementSibling nextSibling previousSibling childElementCount children.length /** * Return the nth ancestor of e, or null if there is no such ancestor * or if that ancestor is not an Element (a Document or DocumentFragment e.g.). * If n is 0 return e itself. If n is 1 (or * omitted) return the read more..

  • Page - 392

    } } return e; } /** * Return the nth element child of e, or null if it doesn't have one. * Negative values of n count from the end. 0 means the first child, but * -1 means the last child, -2 means the second to last, and so on. */ function child(e, n) { if (e.children) { read more..

  • Page - 393

    children // Simulate the Element.children property in non-IE browsers that don't have it // Note that this returns a static array rather than a live NodeList if (!document.documentElement.children) { Element.prototype.__defineGetter__("children", function() { var kids = []; for(var c = this.firstChild; c != null; c = c.nextSibling) read more..

  • Page - 394

    defaultChecked tabIndex for <label> htmlFor class className className defaultChecked maxLength <input> null form <input> style delete 15.4.2 Getting and Setting Non-HTML Attributes getAttribute() setAttribute() var image = document.images[0]; var width = parseInt(image.getAttribute("WIDTH")); image.setAttribute("class", "thumbnail"); getAttribute() hasAttribute() removeAttribute() 376 | read more..

  • Page - 395

    disabled getAttributeNS() setAttributeNS() hasAttributeNS() removeAttributeNS() setAttributeNS() 15.4.3 Dataset Attributes class getAttribute() setAttribute() dataset data- dataset.x data-x data-jquery-test dataset.jqueryTest <span class="sparkline" data-ymin="0" data-ymax="10"> 1 1 1 2 2 3 4 5 5 4 3 5 6 7 7 4 2 1 </span> // Assumes the ES5 Array.map() method (or a work-alike) read more..

  • Page - 396

    drawSparkline(sparklines[i], ymin, ymax, data); // Not yet implemented } dataset var sparklines = document.getElementsByClassName("sparkline"); for(var i = 0; i < sparklines.length; i++) { var elt = sparklines[i]; var ymin = parseFloat(elt.getAttribute("data-ymin")); var ymin = parseFloat(elt.getAttribute("data-ymax")); var points = read more..

  • Page - 397

    15.5.1 Element Content As HTML innerHTML innerHTML innerHTML innerHTML += innerHTML innerHTML outerHTML outerHTML outerHTML outerHTML outerHTML outerHTML innerHTML insertAdjacentHTML() insertAdjacentHTML() insertAdjacentHTML() 15.5 Element Content | 379 Client-Side JavaScript read more..

  • Page - 398

    innerHTML 15.5.2 Element Content As Plain Text textContent var para = document.getElementsByTagName("p")[0]; // First <p> in the document var text = para.textContent; // Text is "This is a simple document." para.textContent = "Hello World!"; // Alter paragraph content textContent innerText innerText textContent innerText /** * With one argument, return read more..

  • Page - 399

    text 15.5.3 Element Content As Text Nodes textContent() nodeValue // Return the plain-text content of element e, recursing into child elements. // This method works like the textContent property function textContent(e) { var child, type, s = ""; // s holds the text of all children for(child = e.firstChild; child != null; child = child.nextSibling) { read more..

  • Page - 400

    15.6 Creating, Inserting, and Deleting Nodes // Asynchronously load and execute a script from a specified URL function loadasync(url) { var head = document.getElementsByTagName("head")[0]; // Find document <head> var s = document.createElement("script"); // Create a <script> element s.src = url; read more..

  • Page - 401

    15.6.2 Inserting Nodes appendChild() insertBefore() appendChild() last Child insertBefore() appendChild() null insertBefore() appendChild() appendChild() insertBefore() // Insert the child node into parent so that it becomes child node n function insertAt(parent, child, n) { if (n < 0 || n > parent.childNodes.length) throw new Error("invalid index"); else if (n == read more..

  • Page - 402

    // Now append the rows into the tbody in their sorted order. // This automatically moves them from their current location, so there // is no need to remove them first. If the <tbody> contains any // nodes other than <tr> elements, those nodes will float to the top. for(var i = 0; i < rows.length; i++) read more..

  • Page - 403

    // Implement the outerHTML property for browsers that don't support it. // Assumes that the browser does support innerHTML, has an extensible // Element.prototype, and allows getters and setters to be defined. (function() { // If we already have outerHTML return without doing anything if (document.createElement("div").outerHTML) return; // Return read more..

  • Page - 404

    appendChild() insertBefore() replaceChild() // Reverse the order of the children of Node n function reverse(n) { // Create an empty DocumentFragment as a temporary container var f = document.createDocumentFragment(); // Now loop backward through the children, moving each one to the fragment. // The last child of n becomes the first child of f, and read more..

  • Page - 405

    while(elt.firstChild) // Move all nodes frag.appendChild(elt.firstChild); // from elt to frag return frag; // And return the frag } var Insert = { read more..

  • Page - 406

    * * The entries in the generated TOC can be styled with CSS. All entries have * a class "TOCEntry". Entries also have a class that corresponds to the level * of the section heading. <h1> tags generate entries of class "TOCLevel1", * <h2> tags generate entries of class "TOCLevel2", and so on. Section numbers * inserted into headings have class read more..

  • Page - 407

    for(var h = 0; h < headings.length; h++) { var heading = headings[h]; // Skip the section heading if it is inside the TOC container. if (heading.parentNode == toc) continue; // Figure out what level heading it is. var level = parseInt(heading.tagName.charAt(1)); if read more..

  • Page - 408

    15.8.1 Document Coordinates and Viewport Coordinates <iframe> 390 | Chapter 15: Scripting Documents read more..

  • Page - 409

    pageXOffset pageYOffset scrollLeft scrollTop document.documentElement <body> document.body // Return the current scrollbar offsets as the x and y properties of an object function getScrollOffsets(w) { // Use the specified window or the current window if no argument w = w || window; // This works for all browsers except IE versions 8 and before if read more..

  • Page - 410

    return { w: d.documentElement.clientWidth, h: d.documentElement.clientHeight }; // For browsers in Quirks mode return { w: d.body.clientWidth, h: d.body.clientWidth }; } scrollLeft scrollTop clientWidth clientHeight 15.8.2 Querying the Geometry of an Element getBoundingClientRect() left right top bottom left top right bottom read more..

  • Page - 411

    getBoundingClientRect() <i> getClientRects() getBoundingClientRect() getElementsByTagName() getBoundingClientRect() getClientRects() 15.8.3 Determining the Element at a Point getBoundingClientRect() elementFromPoint() z-index elementFromPoint() null elementFromPoint() target elementFromPoint() 15.8.4 Scrolling scrollLeft scrollTop scrollTo() scroll() 15.8 Document and Element Geometry and Scrolling | 393 Client-Side JavaScript read more..

  • Page - 412

    // Get the height of the document and viewport. offsetHeight is explained below. var documentHeight = document.documentElement.offsetHeight; var viewportHeight = window.innerHeight; // Or use getViewportSize() above // And scroll so the last "page" shows in the viewport window.scrollTo(0, documentHeight - viewportHeight); scrollBy() scroll() scrollTo() // Scroll 10 pixels down every 200 ms. Note read more..

  • Page - 413

    y += e.offsetTop; e = e.offsetParent; } return {x:x, y:y}; } offsetParent getBounding ClientRect() getElementPosition() offset client scroll offsetWidth clientWidth scrollWidth offsetHeight clientHeight scrollHeight offsetLeft clientLeft read more..

  • Page - 414

    clientWidth clientHeight scrollLeft scrollTop getScrollOffsets() scrollLeft scroll Top scrollTo() getEle mentPosition() function getElementPos(elt) { var x = 0, y = 0; // Loop to add up offsets for(var e = elt; e != null; e = e.offsetParent) { x += e.offsetLeft; y += e.offsetTop; } // Loop again, through all read more..

  • Page - 415

    <input> <textarea> <select> Form Input Option Select TextArea HTML element Type property Event handler Description and events <input type="button"> or <button type="button"> “button” onclick A push button <input type="checkbox"> “checkbox” onchange A toggle button without radio button behavior <input type="file"> “file” onchange An input field read more..

  • Page - 416

    HTML element Type property Event handler Description and events <input type="radio"> “radio” onchange A toggle button with radio button behavior—only one selected at a time <input type="reset"> or <button type="reset"> “reset” onclick A push button that resets a form <select> “select-one” onchange A list or drop-down menu from which one item may be read more..

  • Page - 417

    elements document.forms.address.elements[0] document.forms.address.elements.street id name name <form name="shipping"> <fieldset><legend>Shipping Method</legend> <label><input type="radio" name="method" value="1st">First-class</label> <label><input type="radio" name="method" value="2day">2-day Air</label> read more..

  • Page - 418

    submit() reset() submit() reset() type <input> type <textarea> <select> type <input> form null <form> name name value <input> <button> value value value 15.9.3 Form and Element Event Handlers onsubmit onreset onsubmit false onsubmit submit() onsubmit onreset onsubmit 400 | Chapter 15: Scripting Documents read more..

  • Page - 419

    false <form... onreset="return confirm('Really erase ALL input and start over?')"> ... <button type="reset">Clear and Start Over</button> </form> onsubmit onreset reset() onreset onclick onchange change focus blur this <form> form this.form x this.form.x 15.9.4 Push Buttons onclick <input> value <button> onclick onclick 15.9 HTML Forms | 401 read more..

  • Page - 420

    onclick false onclick onsubmit Input <button> 15.9.5 Toggle Buttons name name checked defaultChecked checked <label> value value onclick onchange onchange 15.9.6 Text Fields value placeholder Arrival Date: <input type="text" name="arrival" placeholder="yyyy-mm-dd"> 402 | Chapter 15: Scripting Documents read more..

  • Page - 421

    onchange <textarea> <input> TextArea value onchange <input type="password"> <input type="file"> onchange value onkeypress onkeydown onkeyup false onkeypress onkeydown 15.9.7 Select and Option Elements size type <select> multiple type multiple type <option> 15.9 HTML Forms | 403 Client-Side JavaScript read more..

  • Page - 422

    options onchange selectedIndex selectedIndex options[] selected selected text value value value onchange text options options.length options.length options[] null options[] Option() options[] // Create a new Option object var zaire = new Option("Zaire", // The text property "zaire", // The value property read more..

  • Page - 423

    15.10 Other Document Features 15.10.1 Document Properties body documentElement forms cookie domain lastModified location location referrer Referer title <title> <title> URL location.href location.href document.URL referrer if (document.referrer.indexOf("http://www.google.com/search?") == 0) { var args = document.referrer.substring(ref.indexOf("?")+1).split("&"); for(var i = read more..

  • Page - 424

    document.write("<p>Welcome Google User. "); document.write("You searched for: " + unescape(args[i].substring(2)).replace('+', ' '); break; } } } document.write() 15.10.2 The document.write() Method document.write() read more..

  • Page - 425

    writeln() write() <pre> document.write() innerHTML write() write() close() innerHTML // Define a simple "streaming" API for setting the innerHTML of an element. function ElementStream(elt) { if (typeof elt === "string") elt = document.getElementById(elt); this.elt = elt; this.buffer = ""; } // Concatenate all arguments and append to the buffer read more..

  • Page - 426

    window.getSelection() toString() document.selection createRange() text <a href="javascript: var q; if (window.getSelection) q = window.getSelection().toString(); else if (document.selection) q = document.selection.createRange().text; void window.open('http://en.wikipedia.org/wiki/' + q);"> Look Up Selected Text In Wikipedia </a> getSelection() <input> read more..

  • Page - 427

    <div id="editor" contenteditable> Click to edit </div> contenteditable spellcheck spellcheck=false <textarea> designMode designMode <iframe> onLoad() <iframe id="editor" src="about:blank"></iframe> // Empty iframe <script> onLoad(function() { // When document loads, var read more..

  • Page - 428

    false execCommand(): function bold() { document.execCommand("bold", false, null); } function link() { var url = prompt("Enter link destination"); if (url) document.execCommand("createlink", false, url); } execCommand() document.queryCommandSupported() document.queryCommandEnabled() document.queryCommandState() document.queryCommand Value() document.queryCommandIndeterm() bold read more..

  • Page - 429

    contenteditable innerHTML 15.10 Other Document Features | 411 Client-Side JavaScript read more..

  • Page - 430

    read more..

  • Page - 431

    CHAPTER 16 Scripting CSS style style style 413 read more..

  • Page - 432

    16.1 Overview of CSS font-weight: bold margin-left: 10%; /* left margin is 10% of page width */ text-indent: .5in; /* indent by 1/2 inch */ font-size: 12pt; /* 12 point font size */ /* */ // style <p style="margin: 20px; border: solid red 2px;"> This paragraph has increased margins and is surrounded by a rectangular red border. read more..

  • Page - 433

    <style> </style> <head> <script> <style> <html> <head><title>Test Document</title> <style> body { margin-left: 30px; margin-right: 15px; background-color: #ffffff } p { font-size: 24px; } </style> </head> <body><p>Testing, testing</p> </html> <script> <style> src <link> <head> <head> <title>Test read more..

  • Page - 434

    16.1.2 CSS History 16.1.3 Shortcut Properties font-family font-size font-style font- weight font font: bold italic 24pt helvetica; border margin padding border border-left border-right border-top border-bot tom border-top border-top- color border-top-style border-top-width 16.1.4 Nonstandard Properties moz- -webkit- -ms- border-radius border-radius 416 | Chapter 16: Scripting CSS read more..

  • Page - 435

    .radius10 { border-radius: 10px; /* for current browsers */ -moz-border-radius: 10px; /* for Firefox 3.x */ -webkit-border-radius: 10px; /* For Safari 3.2 and 4 */ } class 16.1.5 CSS Example style <head> <style type="text/css"> /* Specify that headings display in blue italic text. */ h1, h2 read more..

  • Page - 436

    * Any element of class="WARNING" displays in big bold text with large margins * and a yellow background with a fat red border. */ .WARNING { font-weight: bold; font-size: 150%; margin: 0 1in 0 1in; /* top right bottom left */ background-color: yellow; border: read more..

  • Page - 437

    16.2 Important CSS Properties Property Description position Specifies the type of positioning applied to an element top, left Specify the position of the top and left edges of an element bottom, right Specify the position of the bottom and right edges of an element width, height Specify the size of an element z-index Specifies the “stacking order” of an element relative to any read more..

  • Page - 438

    16.2.1 Positioning Elements with CSS position static top left position absolute fixed fixed relative position relative position static left top right bottom left top style <div style="position: absolute; left: 100px; top: 100px;"> top left position static top left 420 | Chapter 16: Scripting CSS read more..

  • Page - 439

    position:rela tive top left 0px left top right bottom position: absolute; right: 0px; bottom: 0px; position: fixed; right: 10px; top: 10px; width height width height background-color <div style="position: absolute; top: 10px; left: 10px; width: 10px; height: 10px; background-color: blue"> </div> left right top bottom left right width width right height bottom 16.2 read more..

  • Page - 440

    <div style="position: absolute; left: 25%; top: 25%; width: 50%; height: 50%; border: 2px solid black"> </div> 16.2.1.1 The third dimension: z-index left top right bottom z-index z-index z-index z-index z-index z-index z-index z-index position:static z-index z-index z-index z-index 16.2.1.2 CSS positioning example: Shadowed text text-shadow <!-- The text-shadow read more..

  • Page - 441

    <span style="position:absolute; top:3px; left:3px; z-index:-1; color: #888"> Shadowed <!-- This is the shadow --> </span> </span> <span> <span> <span> z-index 16.2.2 Borders, Margins and Padding border: solid black 1px; /* border is drawn with a solid, black 1-pixel line */ border: 3px dotted red; /* border is drawn in 3-pixel red read more..

  • Page - 442

    padding: 1px 2px 3px 4px; /* The previous line is equivalent to the following lines. */ padding-top: 1px; padding-right: 2px; padding-bottom: 3px; padding-left: 4px; margin 16.2.3 The CSS Box Model and Positioning Details margin border padding top left width height width height 424 | Chapter 16: Scripting CSS read more..

  • Page - 443

    left top right bottom left left top 16.2.3.1 The border-box model and the box-sizing property width height <!DOCTYPE> width height box-sizing content-box box- sizing:border-box width height border-box <div style="box-sizing:border-box; width: 50%; padding: 10px; border: solid black 2px;"> 16.2 Important CSS Properties | 425 Client-Side JavaScript read more..

  • Page - 444

    box-sizing -webkit-box-sizing -moz-box-sizing box-sizing <div style="width: calc(50%-12px); padding: 10px; border: solid black 2px;"> calc() -moz-calc() 16.2.4 Element Display and Visibility visibility display visibility hid den visible display display none visibility display visibility hidden display none display visibility display visibility visibility display 16.2.5 Color, Transparency, and Translucency color read more..

  • Page - 445

    #000000 /* black */ #fff /* white */ #f00 /* bright red */ #404080 /* dark unsaturated blue */ #ccc /* light gray */ <canvas> background-color background-image background-attachment background-position background-repeat background <div> <div> <div> <button> background-color opacity 16.2 read more..

  • Page - 446

    opacity filter opacity: .75; /* standard CSS3 style for transparency */ filter: alpha(opacity=75); /* transparency for IE; note no decimal point */ 16.2.6 Partial Visibility: overflow and clip visibility overflow clip over flow width height visible hidden scroll auto overflow clip clip clip clip rect(top right bottom left) top right bottom left style 428 | Chapter read more..

  • Page - 447

    style="clip: rect(0px 100px 100px 0px);" px auto style style="clip: rect(auto 100px auto auto);" clip auto 16.2.7 Example: Overlapping Translucent Windows 16.2 Important CSS Properties | 429 Client-Side JavaScript read more..

  • Page - 448

    <!DOCTYPE html> <head> <style type="text/css"> /** * This is a CSS stylesheet that defines three style rules that we use * in the body of the document to create a "window" visual effect. * The rules use positioning properties to set the overall size of the window * and the position of its components. Changing the size of the window * read more..

  • Page - 449

    <!-- Here's another window with different position, color, and font weight --> <div class="window" style="left: 75px; top: 110px; z-index: 20;"> <div class="titlebar">Another Window</div> <div class="content translucent" style="background-color:#ccc; font-weight:bold;"> This is another window. Its <tt>z-index</tt> puts it on top of the other one. CSS read more..

  • Page - 450

    float float cssFloat style position: absolute; font-family: sans-serif; background-color: #ffffff; e e.style.position = "absolute"; e.style.fontFamily = "sans-serif"; e.style.backgroundColor = "#ffffff"; left e.style.left = 300; // Incorrect: this is a number, not a string e.style.left = "300"; // Incorrect: the units are missing left e e.style.left = read more..

  • Page - 451

    e.style.marginBottom = bottomMargin + "px"; e.style.marginLeft = leftMargin + "px"; style style marginLeft style getAttribute() setAttribute() cssText // Set the style attribute of e to the string s with either of these lines: e.setAttribute("style", s); e.style.cssText = s; // Query the inline style string of the element e with either of these: s = read more..

  • Page - 452

    function shake(e, oncomplete, distance, time) { // Handle arguments if (typeof e === "string") e = document.getElementById(e); if (!time) time = 500; if (!distance) distance = 5; var originalStyle = e.style.cssText; // Save the original style of e e.style.position = "relative"; // Make read more..

  • Page - 453

    var elapsed = (new Date()).getTime()-start; // elapsed time var fraction = elapsed/time; // As a fraction of total if (fraction < 1) { // If the animation is not yet complete var opacity = 1 - ease(fraction); // Compute element opacity read more..

  • Page - 454

    getComputedStyle() null var title = document.getElementById("section1title"); var titlestyles = window.getComputedStyle(element, null); getComputedStyle() margin marginLeft marginTop cssText scale() scaleColor() getComputedStyle() // Scale the text size of element e by the specified factor function scale(e, factor) { // Use the computed style to query the current size of the text read more..

  • Page - 455

    // Alter the background color of element e by the specified amount. // Factors > 1 lighten the color and factors < 1 darken it. function scaleColor(e, factor) { var color = window.getComputedStyle(e, "").backgroundColor; // Query var components = color.match(/[\d\.]+/g); // Parse r,g,b, and a components for(var i = 0; i < 3; i++) { read more..

  • Page - 456

    .attention { /* Styles to grab the user's attention */ background-color: yellow; /* Yellow highlight background */ font-weight: bold; /* Bold text */ border: solid black 2px; /* Black box */ } class class className className function grabAttention(e) { e.className = "attention"; } function releaseAttention(e) { read more..

  • Page - 457

    * DOMTokenList is not array-like, but has a toArray() method that returns * a true-array snapshot of the element's class names. */ function classList(e) { if (e.classList) return e.classList; // Return e.classList if it exists else return new CSSClassList(e); // Otherwise try to fake it } // CSSClassList is a JavaScript class that simulates read more..

  • Page - 458

    }; // Return e.className itself CSSClassList.prototype.toString = function() { return this.e.className; }; // Return of the names in e.className CSSClassList.prototype.toArray = function() { return this.e.className.match(/\b\w+\b/g) || []; }; 16.6 Scripting Stylesheets <style> <link> id document.getElementById() document.styleSheets title <style> <link> title 16.6.1 Enabling and read more..

  • Page - 459

    sheets[i].disabled = true; } } 16.6.2 Querying, Inserting and Deleting Stylesheet Rules className document.styleSheets[] cssRules[] var firstRule = document.styleSheets[0].cssRules[0]; rules cssRules cssRules[] rules[] @import @page rules[] selectorText style CSSStyleDeclaration cssText insertRule() deleteRule() document.styleSheets[0].insertRule("H1 { text-weight: bold; }", 0); insertRule() read more..

  • Page - 460

    var ss = document.styleSheets[0]; // Get the first stylesheet var rules = ss.cssRules?ss.cssRules:ss.rules; // Get the stylesheet rules for(var i = 0; i < rules.length; i++) { // Loop through those rules var rule = rules[i]; if (!rule.selectorText) continue; // Skip @import and other nonstyle rules var read more..

  • Page - 461

    // Now the new stylesheet should be the last one styleSheet = document.styleSheets[document.styleSheets.length-1] } // Now insert the styles into it if (typeof styles === "string") { // The argument is stylesheet text if (styleElt) styleElt.innerHTML = styles; else read more..

  • Page - 462

    read more..

  • Page - 463

    CHAPTER 17 Handling Events <button> 445 read more..

  • Page - 464

    event type target srcElement target type target Event <a> <p> <div> 446 | Chapter 17: Handling Events read more..

  • Page - 465

    17.1 Types of Events 17.1 Types of Events | 447 Client-Side JavaScript read more..

  • Page - 466

    Event Categories 448 | Chapter 17: Handling Events read more..

  • Page - 467

    <video> <audio> 17.1.1 Legacy Event Types 17.1.1.1 Form events <form> 17.1 Types of Events | 449 Client-Side JavaScript read more..

  • Page - 468

    <textarea> 17.1.1.2 Window events onerror <img> 450 | Chapter 17: Handling Events read more..

  • Page - 469

    overflow 17.1.1.3 Mouse events clientX clientY button which Event altKey ctrlKey metaKey shiftKey true detail 17.1 Types of Events | 451 Client-Side JavaScript read more..

  • Page - 470

    relatedTarget Event relatedTarget 17.1.1.4 Key events keyCode keyCode altKey ctrlKey metaKey shiftKey keyCode 452 | Chapter 17: Handling Events read more..

  • Page - 471

    17.1.2 DOM Events deltaX deltaY deltaZ deltaZ keyCode data inputMethod textInput data inputMethod 17.1 Types of Events | 453 Client-Side JavaScript read more..

  • Page - 472

    key char key char key char null key char key 17.1.3 HTML5 Events <audio> <video> canplay loadeddata playing stalled canplaythrough loadedmetadata progress suspend durationchange loadstart ratechange timeupdate emptied pause seeked read more..

  • Page - 473

    cached checking downloading error noupdate obsolete progress updateready data source origin 17.1 Types of Events | 455 Client-Side JavaScript read more..

  • Page - 474

    17.1.4 Touchscreen and Mobile Events scale rotation scale scale scale rotation changedTouches orientation 17.2 Registering Event Handlers 456 | Chapter 17: Handling Events read more..

  • Page - 475

    addEventListener() attachEvent() 17.2.1 Setting Event Handler Properties onclick onchange onload onmouseover // Set the onload property of the Window object to a function. // The function is the event handler: it is invoked when the document loads. window.onload = function() { // Look up a <form> element var elt = document.getElementById("shipping_address"); read more..

  • Page - 476

    <body> onafterprint onfocus ononline onresize onbeforeprint onhashchange onpagehide onstorage onbeforeunload onload onpageshow onundo onblur onmessage onpopstate onunload onerror onoffline read more..

  • Page - 477

    <button> <button id="mybutton">Click me</button> <script> var b = document.getElementById("mybutton"); b.onclick = function() { alert("Thanks for clicking me!"); }; b.addEventListener("click", function() { alert("Thanks again!"); }, false); </script> addEventListener() onclick alert() addEventListener() addEventListener() addEventListener() removeEventListener() read more..

  • Page - 478

    addEventListener() attachEvent() var b = document.getElementById("mybutton"); var handler = function() { alert("Thanks!"); }; if (b.addEventListener) b.addEventListener("click", handler, false); else if (b.attachEvent) b.attachEvent("onclick", handler); 17.3 Event Handler Invocation this 17.3.1 Event Handler Argument type window.event window.event function handler(event) { read more..

  • Page - 479

    17.3.2 Event Handler Context e.onclick = function() { /* handler code */ }; this this addEventListener() attachEvent() attachEvent() this /* * Register the specified handler function to handle events of the specified * type on the specified target. Ensure that the handler will always be * invoked as a method of the target. */ function addEvent(target, type, handler) { read more..

  • Page - 480

    tagName this.tag Name getElementById document.getElementById <form> zipcode this.form.zipcode open() open() window.open open window.location location 17.3.4 Handler Return Value false onclick false onkeypress false onbeforeunload addEventListener() attachEvent() preventDefault() returnValue 17.3.5 Invocation Order 462 | Chapter 17: Handling Events read more..

  • Page - 481

    addEventListener() attachEvent() 17.3.6 Event Propagation <form> addEventListener() true addEventListener() true 17.3 Event Handler Invocation | 463 Client-Side JavaScript read more..

  • Page - 482

    17.3.7 Event Cancellation addEventListener() preventDefault() returnValue false function cancelHandler(event) { var event = event || window.event; // For IE /* Do something to handle the event here */ // Now cancel the default action associated with the event if (event.preventDefault) event.preventDefault(); // Standard technique if read more..

  • Page - 483

    stopImmediatePropagation() stopPropagation() stopImmediatePropagation() stopImmediatePropagation() 17.4 Document Load Events onLoad() async document.readyState whenReady() onLoad() whenReady() onLoad() whenReady() 17.4 Document Load Events | 465 Client-Side JavaScript read more..

  • Page - 484

    whenReady() /* * Pass a function to whenReady() and it will be invoked (as a method of the * document) when the document is parsed and ready for manipulation. Registered * functions are triggered by the first DOMContentLoaded, readystatechange, or * load event that occurs. Once the document is ready and all functions have * been invoked, any functions passed to read more..

  • Page - 485

    17.5 Mouse Events Type Description click A higher-level event fired when the user presses and releases a mouse button or otherwise “activates” an element. contextmenu A cancelable event fired when a contextmenu is about to be popped up. Current browsers display context menus on right mouse clicks, so this event can also be used like the click event. dblclick Fired when the user read more..

  • Page - 486

    drag() mouse down drag() drag() position drag() <img> <img src="draggable.gif" style="position:absolute; left:100px; top:100px;" onmousedown="if (event.shiftKey) drag(this, event);"> drag() getScrollOffsets() drag() setCapture() moveHandler() upHandler() drag() drag() /** * Drag.js: drag absolutely positioned HTML elements. * * This module defines a single drag() read more..

  • Page - 487

    * It requires the getScrollOffsets() function from elsewhere in this book. * * Arguments: * * elementToDrag: the element that received the mousedown event or * some containing element. It must be absolutely positioned. Its * style.left and style.top values will be changed based on the user's * drag. * * event: the Event read more..

  • Page - 488

    **/ function moveHandler(e) { if (!e) e = window.event; // IE event Model // Move the element to the current mouse position, adjusted by the // position of the scrollbars and the offset of the initial click. var scroll = getScrollOffsets(); elementToDrag.style.left = read more..

  • Page - 489

    <p>This is a test. Testing, testing, testing.</p><p>Test</p><p>Test</p> </div> onmousedown <div> this.parentNode 17.6 Mousewheel Events wheelDelta wheelDeltaX wheelDeltaY wheelDelta wheelDelta wheelDeltaY detail wheelDelta detail wheelDelta detail wheelDelta deltaX deltaY deltaZ 17.6 Mousewheel Events | 471 Client-Side JavaScript read more..

  • Page - 490

    enclose() enclose() <script src="whenReady.js"></script> <script src="Enclose.js"></script> <script> whenReady(function() { enclose(document.getElementById("content"),400,200,-200,-300); }); </script> <style>div.enclosure { border: solid black 10px; margin: 10px; }</style> <img id="content" src="testimage.jpg"/> // Enclose the content element read more..

  • Page - 491

    // Put the frame in the document and move the content elt into the frame. content.parentNode.insertBefore(frame, content); frame.appendChild(content); // Position the element relative to the frame content.style.position = "relative"; content.style.left = contentX + "px"; content.style.top = contentY + "px"; read more..

  • Page - 492

    var contentwidth = contentbox.right - contentbox.left; var contentheight = contentbox.bottom - contentbox.top; if (e.altKey) { // If Alt key is held down, resize the frame if (deltaX) { framewidth -= deltaX; // New width, but not bigger than the read more..

  • Page - 493

    dataTransfer draggable dragstart dataTransfer.setData() dataTransfer.items.add() dataTransfer.effectAllowed dataTransfer.setDragImage() 17.7 Drag and Drop Events | 475 Client-Side JavaScript read more..

  • Page - 494

    dataTransfer.addElement() dataTransfer.dropEffect <span> draggable true ondragstart dataTransfer.setData() dataTransfer.setDragIcon() <script src="whenReady.js"></script> <script> whenReady(function() { var clock = document.getElementById("clock"); // The clock element var icon = new Image(); // An image to drag read more..

  • Page - 495

    // Tell the browser what is being dragged. // The Date() constructor used as a function returns a timestamp string dt.setData("Text", Date() + "\n"); // Tell the browser to drag our icon to represent the timestamp, in // browsers that support that. Without this line, the read more..

  • Page - 496

    dataTransfer.getData() dataTransfer.files dataTransfer.items[] <ul> <li> <ul> class /* * The DnD API is quite complicated, and browsers are not fully interoperable. * This example gets the basics right, but each browser is a little different * and each one seems to have its own unique bugs. This code does not attempt * browser-specific workarounds. */ read more..

  • Page - 497

    // know when to highlight or unhighlight the element in a case like // this where the <ul> element has <li> children. In browsers that // define relatedTarget we can track that. // Otherwise, we count enter/leave pairs // If we entered read more..

  • Page - 498

    }; // This handler is invoked when a drop actually happens. // We take the dropped text and make it into a new <li> element list.ondrop = function(e) { e = e || window.event; // Get the event // Get the data that was dropped read more..

  • Page - 499

    // If the drop was a move, then delete the list item. // In IE8, this will be "none" unless you explicitly set it to // move in the ondrop handler above. But forcing it to "move" for // IE prevents other browsers from giving the user a choice of a read more..

  • Page - 500

    <input type=text> data-allowed-chars /** * InputFilter.js: unobtrusive filtering of keystrokes for <input> elements * * This module finds all <input type="text"> elements in the document that * have an "data-allowed-chars" attribute. It registers keypress, textInput, and * textinput event handlers for any such element to restrict the user's input * so that only read more..

  • Page - 501

    } // This is the keypress and textInput handler that filters the user's input function filter(event) { // Get the event object and the target element target var e = event || window.event; // Standard or IE model var target = e.target || e.srcElement; // Standard or IE model read more..

  • Page - 502

    SURNAME: <input type="text" oninput="this.value = this.value.toUpperCase();"> value function forceToUpperCase(element) { if (typeof element === "string") element = document.getElementById(element); element.oninput = upcase; element.onpropertychange = upcaseOnPropertyChange; // Easy case: the handler for the input event function upcase(event) { read more..

  • Page - 503

    keyCode altKey ctrlKey metaKey shift Key true keyCode keyCode key key key key keyIdentifier key keyIdentifier A Keymap() bind() unbind() install() keydown key keyIdentifier keyCode /* * Keymap.js: bind key events to handler functions. * * This module defines a Keymap class. An instance of this class represents a * mapping of key identifiers (defined below) to handler functions. A Keymap read more..

  • Page - 504

    * identifer and handler function to the bind() method. You can remove a * binding by passing a key identifier to the unbind() method. * * To make use of a Keymap, call its install() method, passing an HTML element, * such as the document object. install() adds an onkeydown event handler to * the specified object. When this handler is invoked, it determines read more..

  • Page - 505

    for(name in bindings) this.bind(name, bindings[name]); } } // Bind the specified key identifier to the specified handler function Keymap.prototype.bind = function(key, func) { this.map[Keymap.normalize(key)] = func; }; // Delete the binding for the specified key identifier Keymap.prototype.unbind = function(key) { delete this.map[Keymap.normalize(key)]; }; // read more..

  • Page - 506

    if (handler) { // If there is a handler for this key, handle it // Invoke the handler function var retval = handler.call(element, event, keyid); // If the handler returns false, cancel default and prevent bubbling if (retval === false) { if (event.stopPropagation) read more..

  • Page - 507

    // Keypad numbers and punctuation keys. (Opera does not support these.) 96:"0",97:"1",98:"2",99:"3",100:"4",101:"5",102:"6",103:"7",104:"8",105:"9", 106:"Multiply", 107:"Add", 109:"Subtract", 110:"Decimal", 111:"Divide", // Function keys 112:"F1", read more..

  • Page - 508

    read more..

  • Page - 509

    CHAPTER 18 Scripted HTTP location submit() 491 read more..

  • Page - 510

    <img> src src <img> <img> <iframe> <iframe> src <iframe> <iframe> <iframe> <iframe> <script> src <script> <script> <iframe> <script> <script> 492 | Chapter 18: Scripted HTTP read more..

  • Page - 511

    <script> The XML Is Optional responseXML <iframe> <script> <iframe> Scripted HTTP | 493 Client-Side JavaScript read more..

  • Page - 512

    18.1 Using XMLHttpRequest var request = new XMLHttpRequest(); XMLHttpRequest in IE6 XMLHttpRequest() // Emulate the XMLHttpRequest() constructor in IE5 and IE6 if (window.XMLHttpRequest === undefined) { window.XMLHttpRequest = function() { try { // Use the latest version of the ActiveX object if available read more..

  • Page - 513

    XMLHttpRequest and Local Files file:// http:// http:// 18.1.1 Specifying the Request open() 18.1 Using XMLHttpRequest | 495 Client-Side JavaScript read more..

  • Page - 514

    request.open("GET", // Begin a HTTP GET request "data.csv"); // For the contents of this URL open() open() open() open() request.setRequestHeader("Content-Type", "text/plain"); setRequestHeader() setRequestHeader() Accept-Charset Content-Transfer-Encoding TE Accept-Encoding Date read more..

  • Page - 515

    open() open() send() request.send(null); null setRequestHeader() Order Matters send() setRequestHeader() open() send() function postMessage(msg) { var request = new XMLHttpRequest(); // New request request.open("POST", "/log.php"); // POST to a server-side script // Send the message, in plain-text, as the request body read more..

  • Page - 516

    18.1.2 Retrieving the Response status statusText getResponseHeader() getAllResponseHeaders() getAllResponseHeaders() null getResponseHeader() responseText responseXML responseXML send() readyState readyState XMLHttpRequest.DONE Constant Value Meaning UNSENT 0 open() has not been called yet OPENED 1 open() has been called HEADERS_RECEIVED 2 Headers have been received LOADING 3 The response body is being received DONE 4 read more..

  • Page - 517

    LOADING ready State readyState onreadystatechange addEventListener() attachEvent() onreadystatechange getText() // Issue an HTTP GET request for the contents of the specified URL. // When the response arrives successfully, verify that it is plain text // and if so, pass it to the specified callback function function getText(url, callback) { var request = new XMLHttpRequest(); read more..

  • Page - 518

    request.send(null); // Send the request now // Throw an error if the request was not 200 OK if (request.status !== 200) throw new Error(request.statusText); // Throw an error if the type was wrong var type = request.getResponseHeader("Content-Type"); if (!type.match(/^text/)) read more..

  • Page - 519

    // If the request is compete and was successful if (request.readyState === 4 && request.status === 200) { // Get the type of the response var type = request.getResponseHeader("Content-Type"); // Check type so we don't get HTML documents in the future read more..

  • Page - 520

    18.1.3 Encoding the Request Body 18.1.3.1 Form-encoded requests find=pizza&zipcode=02134&radius=1km application/x-www-form-urlencoded { find: "pizza", zipcode: 02134, radius: "1km" } /** * Encode the properties of an object as if they were name/value pairs from * an HTML form, using application/x-www-form-urlencoded format */ function read more..

  • Page - 521

    var pairs = []; // To hold name=value pairs for(var name in data) { // For each name if (!data.hasOwnProperty(name)) continue; // Skip inherited if (typeof data[name] === "function") continue; read more..

  • Page - 522

    http://restaurantfinder.example.com/02134/1km/pizza 18.1.3.2 JSON-encoded requests JSON.stringify() function postJSON(url, data, callback) { var request = new XMLHttpRequest(); request.open("POST", url); // POST to the specified url request.onreadystatechange = function() { // Simple event read more..

  • Page - 523

    if (request.readyState === 4 && callback) callback(request); }; // Create an XML document with root element <query> var doc = document.implementation.createDocument("", "query", null); var query = doc.documentElement; // The <query> element var find = doc.createElement("find"); read more..

  • Page - 524

    // response is ignored. whenReady(function() { // Run when the document is ready var elts = document.getElementsByTagName("input"); // All input elements for(var i = 0; i < elts.length; i++) { // Loop through them var input = elts[i]; if read more..

  • Page - 525

    request.onreadystatechange = function() { // A simple event handler. if (request.readyState === 4 && callback) // When response is complete callback(request); // ...call the callback. }; var formdata = new FormData(); for(var name in data) { read more..

  • Page - 526

    addEventListener() onprogress onload if ("onprogress" in (new XMLHttpRequest())) { // Progress events are supported } type timestamp loaded total lengthComputable true false total loaded request.onprogress = function(e) { if (e.lengthComputable) progress.innerHTML = Math.round(100*e.loaded/e.total) + "% Complete"; } 18.1.4.1 Upload progress events upload upload read more..

  • Page - 527

    for(var i = 0; i < elts.length; i++) { var target = elts[i]; var url = target.getAttribute("data-uploadto"); if (!url) continue; createFileUploadDropTarget(target, url); } function createFileUploadDropTarget(target, url) { // Keep track of whether we're currently uploading read more..

  • Page - 528

    uploading = false; target.classList.remove("uploading"); target.innerHTML = "Drop files to upload"; }; xhr.send(body); return false; read more..

  • Page - 529

    timeout); // How long before we do this request.open("GET", url); // Specify URL to fetch request.onreadystatechange = function() { // Define event listener. if (request.readyState !== 4) return; // Ignore read more..

  • Page - 530

    <a> /** * linkdetails.js * * This unobtrusive JavaScript module finds all <a> elements that have an href * attribute but no title attribute and adds an onmouseover event handler to * them. The event handler makes an XMLHttpRequest HEAD request to fetch * details about the linked resource, and then sets those details in the title * attribute of the link so read more..

  • Page - 531

    var size = req.getResponseHeader("Content-Length"); // link var date = req.getResponseHeader("Last-Modified"); // details // Display the details in a tooltip. link.title = "Type: " + type + " \n" + read more..

  • Page - 532

    <script> JSON.parse() <script> <script> [1, 2, {"buckle": "my shoe"}] handleResponse( [1, 2, {"buckle": "my shoe"}] ) <script> handleResponse() <script> ?json &json getJSONP() <script> 514 | Chapter 18: Scripted HTTP read more..

  • Page - 533

    getJSONP() // Make a JSONP request to the specified URL and pass the parsed response // data to the specified callback. Add a query parameter named "jsonp" to // the URL to specify the name of the callback function for the request. function getJSONP(url, callback) { // Create a unique callback name just for this request var cbnum = "cb" + read more..

  • Page - 534

    // Now process the event type and event data strings. } data type onmessage type EventSource event: bid data: GOOG data: 999 <script> window.onload = function() { // Take care of some UI details var nick = prompt("Enter your nickname"); // Get user's nickname var input = read more..

  • Page - 535

    var xhr = new XMLHttpRequest(); // Create a new XHR xhr.open("POST", "/chat"); // to POST to /chat. xhr.setRequestHeader("Content-Type", // Specify plain UTF-8 text read more..

  • Page - 536

    // And establish a long-lived connection through it connect(); // If the connection closes normally, wait a second and try to restart function reconnect() { if (aborted) return; // Don't reconnect after an abort if (xhr.status read more..

  • Page - 537

    if (line === "") { // A blank line means send the event if (evtsrc.onmessage && data !== "") { // Chop trailing newline if there is one if (data.charAt(data.length-1) read more..

  • Page - 538

    }, 20000); // Create a new server var server = new http.Server(); // When the server gets a new request, run this function server.on("request", function (request, response) { // Parse the requested URL var url = require('url').parse(request.url); // If the request was for "/", send the client-side chat UI. if (url.pathname === "/") { read more..

  • Page - 539

    response.end(); }); // Remember the response object so we can send future messages to it clients.push(response); } }); // Run the server on port 8000. Connect to http://localhost:8000/ to use it. server.listen(8000); 18.3 Comet with Server-Sent Events | 521 Client-Side JavaScript read more..

  • Page - 540

    read more..

  • Page - 541

    CHAPTER 19 The jQuery Library jQuery jQuery 523 read more..

  • Page - 542

    19.1 jQuery Basics jQuery() $ <div> var divs = $("div"); jQuery() new <p> $ $ jQuery.noConflict() $ 524 | Chapter 19: The jQuery Library read more..

  • Page - 543

    $("p.details").css("background-color", "yellow").show("fast"); css() $() show() $(".clicktohide").click(function() { $(this).slideUp("slow"); }); Obtaining jQuery <script> <script src="jquery-1.4.2.min.js"></script> http://code.jquery.com/jquery-1.4.2.min.js http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js jQuery 19.1.1 read more..

  • Page - 544

    $() $() $(document) $(this) $() $() $() $() $() <iframe> css() html() text() var img = $("<img/>", // Create a new <img> element { src:url, // with this HTML attribute, css: {borderWidth:5}, // this CSS style, read more..

  • Page - 545

    jQuery(function() { // Invoked when the document has loaded // All jQuery code goes here }); $(f) $(document).ready(f) jQuery() this jQuery $ jQuery.noConflict(); // Restore $ to its original state jQuery(function($) { // Use $ as a local alias for the jQuery object // Put all your jQuery code here }); $() $() $() jQuery() jQuery.noConflict() jQuery.each() read more..

  • Page - 546

    attr() attr() attr() jQuery.noConflict() // Call the jQuery function each() to // invoke the function f once for each element of the array a $.each(a,f); // Call the jQuery() function to obtain a jQuery object that represents all // <a> elements in the document. Then call the each() method of that jQuery // object to invoke the function f once for each selected element. read more..

  • Page - 547

    toArray() length selector context $() jquery jquery // Find all <script> elements in the document body var bodyscripts = $("script", document.body); bodyscripts.selector // => "script" bodyscripts.context // => document.body bodyscripts.jquery // => "1.4.2" $() versus querySelectorAll() $() querySelectorAll() querySelectorAll() $() querySelectorAll() querySelectorAll() $() read more..

  • Page - 548

    // Number the divs of the document, up to and including div#last $("div").each(function(idx) { // find all <div>s, and iterate through them $(this).prepend(idx + ": "); // Insert index at start of each if (this.id === "last") return false; // Stop at element #last }); each() each() each() map() Array.map() map() each() this null read more..

  • Page - 549

    19.2 jQuery Getters and Setters map() this 19.2.1 Getting and Setting HTML Attributes attr() attr() removeAttr() $("form").attr("action"); // Query the action attr of 1st form $("#icon").attr("src", "icon.gif"); // Set the src attribute $("#banner").attr({src:"banner.gif", // Set 4 read more..

  • Page - 550

    $("a").attr({target: function() {...}}); // We can also pass functions like this $("a").removeAttr("target"); // Make all links load in this window 19.2.2 Getting and Setting CSS Attributes css() attr() css() style css() style css() css() $("h1").css("font-weight"); // Get font weight of first <h1> read more..

  • Page - 551

    }); // Removing CSS classes $("p").removeClass("hilite"); // Remove a class from all <p> elements $("p").removeClass("hilite first"); // Multiple classes are allowed $("section").removeClass(function(n) { // Remove custom classes from elements return "section" + n; }); read more..

  • Page - 552

    19.2.5 Getting and Setting Element Content text() html() text() textContent innerText html() innerHTML x.html() x[0].innerHTML text() html() var title = $("head title").text() // Get document title var headline = $("h1").html() // Get html of first <h1> element $("h1").text(function(n,current) { // Give each heading a section number return read more..

  • Page - 553

    offsetParent() <body> offset() position() offsetParent() width() height() innerWidth() innerHeight() outerWidth() outerHeight() true var body = $("body"); var contentWidth = body.width(); var paddingWidth = body.innerWidth(); var borderWidth = body.outerWidth(); var marginWidth = body.outerWidth(true); var padding = paddingWidth-contentWidth; // sum of left and right padding var borders = read more..

  • Page - 554

    scrollTop() scrollLeft() scrollTop() scrollLeft() scrollTop() height() // Scroll the window by n pages. n can be fractional or negative function page(n) { var w = $(window); // Wrap the window in a jQuery object var pagesize = w.height(); // Get the size of a page var current = read more..

  • Page - 555

    data() removeData() e data() $(e).data(...) // The method form $.data(e, ...) // The function form <applet> <object> <embed> 19.3 Altering Document Structure html() text() 19.3.1 Inserting and Replacing Elements replaceWith() $("#log").append("<br/>"+message); // Add content at end of the #log element $("h1").prepend("§"); read more..

  • Page - 556

    this append() prepend() replaceWith() before() after() Operation $(target).method(content) $(content).method(target) insert content at end of target append() appendTo() insert content at start of target prepend() prependTo() insert content after target after() insertAfter() insert content before target before() insertBefore() replace target with content replaceWith() replaceAll() $() read more..

  • Page - 557

    $("<hr/>").insertBefore("h1"); // Insert rule before <h1>s $("<hr/>").insertAfter("h1"); // Insert rule after <h1>s $("<br/>").replaceAll("hr"); // Replace <hr/> with <br/> 19.3.2 Copying read more..

  • Page - 558

    19.3.4 Deleting Elements empty() remove() remove() filter() remove() detach() remove() detach() unwrap() wrap() wrapAll() remove() detach() unwrap() 19.4 Handling Events with jQuery 19.4.1 Simple Event Handler Registration click() // Clicking on any <p> gives it a gray background $("p").click(function() { $(this).css("background-color", "gray"); }); addEventListener() attachEvent() 540 | read more..

  • Page - 559

    blur() focusin() mousedown() mouseup() change() focusout() mouseenter() resize() click() keydown() mouseleave() scroll() dblclick() keypress() mousemove() select() error() keyup() mouseout() submit() read more..

  • Page - 560

    $() attr() $("<img/>", { src: image_url, alt: image_description, className: "translucent_image", click: function() { $(this).css("opacity", "50%"); } }); 19.4.2 jQuery Event Handlers trigger() false false preventDefault() stopPropagation() undefined result 19.4.3 The jQuery Event Object undefined 542 | Chapter 19: The jQuery Library read more..

  • Page - 561

    altKey ctrlKey newValue screenX attrChange currentTarget offsetX screenY attrName detail offsetY shiftKey bubbles eventPhase originalTarget srcElement button fromElement pageX read more..

  • Page - 562

    which which charCode keyCode which which button which button data handler result originalEvent 19.4.4 Advanced Event Handler Registration bind() bind() bind() bind() $('p').click(f) $('p').bind('click', f); bind() data bind() Function.bind() jQuery.proxy() 544 | Chapter 19: The jQuery Library read more..

  • Page - 563

    bind() $('a').hover(f) $('a').bind('mouseenter mouseleave', f); bind() // Bind f as a mouseover handler in namespace "myMod" to all <a> elements $('a').bind('mouseover.myMod', f); // Bind f as a mouseout handler in namespaces "myMod" and "yourMod" $('a').bind('mouseout.myMod.yourMod', f); bind() hover() $('a').hover(f,g) $('a').bind({mouseenter:f, mouseleave:g}); bind() one() bind() one() bind() read more..

  • Page - 564

    onclick onmouseover unbind() $('*').unbind(); // Remove all jQuery event handlers from all elements! // Unbind all mouseover and mouseout handlers on all <a> elements $('a').unbind("mouseover mouseout"); unbind() // Unbind all mouseover and mouseout handlers in the "myMod" namespace $('a').unbind("mouseover.myMod mouseout.myMod"); // Unbind handlers for any kind of event in read more..

  • Page - 565

    19.4.6 Triggering Events click() mouseover() $("#my_form").submit(); // Act as if the user clicked the Submit button submit() false preventDefault() onsubmit addEventListener() attachEvent() submit() bind() trigger() trigger() submit() $("#my_form").trigger("submit"); bind() unbind() bind() unbind() onclick $("button").trigger("click.ns1"); // Trigger click handlers in a read more..

  • Page - 566

    trigger() type type // The onclick handler of button1 triggers the same event on button2 $('#button1').click(function(e) { $('#button2').trigger(e); }); // Add an extra property to the event object when triggering an event $('#button1').trigger({type:'click', synthetic:true}); // This handler tests that extra property to distinguish real from synthetic $('#button1').click(function(e) { if (e.synthetic) read more..

  • Page - 567

    19.4.7 Custom Events bind() trigger() jQuery.event.trigger() trigger() // When the user clicks the "logoff" button, broadcast a custom event // to any interested observers that need to save their state and then // navigate to the logoff page. $("#logoff").click(function() { $.event.trigger("logoff"); // Broadcast an event window.location = read more..

  • Page - 568

    // Live event handlers for parts of the document that are dynamically updated $(".dynamic").delegate("a", "mouseover", linkHandler); bind() data delegate() cancelBubble() live() live() delegate() bind() delegate() live() $("a").live("mouseover", linkHandler); $("a", $(".dynamic")).live("mouseover", linkHandler); live() $() context selector $() x x.live(type,handler); read more..

  • Page - 569

    19.5 Animated Effects visibility opacity fadeIn() fadeOut() animate() animate() jQuery.fx.speeds jQuery.fx.speeds["medium-fast"] = 300; jQuery.fx.speeds["medium-slow"] = 500; $("#message").fadeIn(); // Fade an element in over 400ms $("#message").fadeOut("fast"); // Fade it out over 200ms Disabling Animations jQuery.fx.off true $(".stopmoving").click(function() { jQuery.fx.off read more..

  • Page - 570

    fadeIn() this // Quickly fade in an element, and when it is visible, display some text in it. $("#message").fadeIn("fast", function() { $(this).text("Hello World"); }); $("#blinker").fadeIn(100).fadeOut(100).fadeIn(100).fadeOut(100).fadeIn(); // Pass duration and callback as object properties instead of arguments $("#message").fadeIn({ duration: "fast", read more..

  • Page - 571

    show() hide() toggle() fadeOut() hide() display none hide() show() hide() width height opacity show() toggle() show() hide() show() hide() toggle() true toggle() show() false hide() toggle() slideDown() slideUp() slideToggle() slideUp() display slideDown() slideToggle() // Fade all images out, then show them, then slide up, then slide down $("img").fadeOut().show(300).slideUp().slideToggle(); 19.5.2 Custom read more..

  • Page - 572

    animate() $("#sprite").animate({ opacity: .25, // Animate opacity to .25 font-size: 10 // Animate font size to 10 pixels }, { duration: 500, // Animation lasts 1/2 second complete: function() { // Call this function when done read more..

  • Page - 573

    slideUp() $("img").animate({ width: "hide", borderLeft: "hide", borderRight: "hide", paddingLeft: "hide", paddingRight: "hide" }); slideDown() slideToggle() 19.5.2.2 The animation options object animate() duration jQuery.fx.speeds complete step this queue queue false $("img").fadeIn(500) read more..

  • Page - 574

    jQuery.easing jQuery.easing["squareroot"] = Math.sqrt; easing $("img").animate({"width":"+=100"}, {duration: 500, easing:"linear"}); duration easing complete animate() $("img").animate({"width":"+=100"}, 500, "linear"); // Hide images, as with the hide() method, but animate the image size linearly // while the opacity is being animated with the default read more..

  • Page - 575

    19.5.3 Canceling, Delaying, and Queuing Effects stop() stop() true false true // Images become opaque when the mouse moves over them. // Be careful that we don't keep queueing up animations on mouse events! $("img").bind({ mouseover: function() { $(this).stop().fadeTo(300, 1.0); }, mouseout: function() { $(this).stop().fadeTo(300, 0.5); } }); delay() delay() // Quickly read more..

  • Page - 576

    // Fade an element in, wait, set some text in it, and animate its border $("#message").fadeIn().delay(200).queue(function(next) { $(this).text("Hello World"); // Display some text next(); // Run the next item on the queue }).animate({borderWidth: "+=10px;"}); // Grow its read more..

  • Page - 577

    jQuery.ajax() jQuery.ajax() jQuery.ajax() 19.6.1 The load() Method load() // Load and display the latest status report every 60 seconds setInterval(function() { $("#stats").load("status_report.html"); }, 60000); load() // Load and display the temperature section of the weather report $('#temp').load("weather_report.html #temperature"); hash load() ? & load() // Load the weather report read more..

  • Page - 578

    jQuery’s Ajax Status Codes load() ifModified timeout 19.6.2 Ajax Utility Functions jQuery $ jQuery.getScript() jQuery.getJSON() jQuery.get() jQuery.post() jQuery.get() load() 560 | Chapter 19: The jQuery Library read more..

  • Page - 579

    19.6.2.1 jQuery.getScript() jQuery.getScript() // Dynamically load a script from some other server jQuery.getScript("http://example.com/js/widget.js"); // Load a library and use it once it loads jQuery.getScript("js/jquery.my_plugin.js", function() { $('div').my_plugin(); // Use the library we loaded }); jQuery.getScript() <script> jQuery.getScript() undefined jQuery.getScript() undefined read more..

  • Page - 580

    ? & Passing Data to jQuery’s Ajax Utilities name=value serialize() load() $("#submit_button").click(function(event) { $(this.form).load( // Replace the form by loading... this.form.action, // the form url $(this.form).serialize()); // with the form data appended to it read more..

  • Page - 581

    jQuery.getJSON() jQuery.getJSON() 19.6.2.3 jQuery.get() and jQuery.post() jQuery.get() jQuery.post() jQuery.get() jQuery.post() jQuery.getJSON() // Request text from the server and display it in an alert dialog jQuery.get("debug.txt", alert); load() jQuery.getScript() jQuery.getJSON() jQuery.get() jQuery.post() jQuery’s Ajax Data Types jQuery.get() jQuery.post() jQuery.ajax() dataType "text" "html" read more..

  • Page - 582

    "script" jQuery.getScript() <script> "json" jQuery.parseJSON() jQuery.getJSON() "=?" "jsonp" <script> "&jsonp=?" "&callback=?" jsonp jsonpCallback jQuery.get() jQuery.post() jQuery.ajax() 19.6.3 The jQuery.ajax() Function jQuery.ajax() jQuery.ajax() jQuery.getScript(url,callback) jQuery.ajax() jQuery.ajax({ type: "GET", // The read more..

  • Page - 583

    jQuery.get() jQuery.post() jQuery.ajax() jQuery.ajaxSetup() jQuery.ajaxSetup({ timeout: 2000, // Abort all Ajax requests after 2 seconds cache: false // Defeat browser cache by adding a timestamp to the URL }); timeout cache jQuery.get() load() Ajax in jQuery 1.5 jQuery.ajax() $.getScript() success() error() jQuery.get() success() jQuery.get("data.txt") read more..

  • Page - 584

    url data cache false data process Data dataType Content-Type contentType Content-Type type timeout error cache false _= ifModified true Last-Modified If-None-Match success ifModified 566 | Chapter 19: The jQuery Library read more..

  • Page - 585

    global true false 19.6.3.2 Callbacks success jQuery.getJSON() global false context this context beforeSend beforeSend XMLHttpRequest false beforeSend success dataType Content-Type 19.6 Ajax with jQuery | 567 Client-Side JavaScript read more..

  • Page - 586

    ifModified <script> error error dataType success error complete success error complete success error complete 19.6.3.3 Uncommon options and hooks async false jQuery.ajax() complete dataFilter 568 | Chapter 19: The jQuery Library read more..

  • Page - 587

    dataType dataFilter dataFilter jsonp dataType url data jsonpCallback dataType success complete processData data jQuery.get() false scriptCharset <script> charset traditional true username password xhr 19.6 Ajax with jQuery | 569 Client-Side JavaScript read more..

  • Page - 588

    19.6.4 Ajax Events jQuery.ajax() beforeSend success error complete Callback Event Type Handler Registration Method beforeSend “ajaxSend” ajaxSend() success “ajaxSuccess” ajaxSuccess() error “ajaxError” ajaxError() complete “ajaxComplete” ajaxComplete() “ajaxStart” ajaxStart() “ajaxStop” ajaxStop() bind() ajaxSuccess() click() mouseover() beforeSend 570 | Chapter 19: The jQuery Library read more..

  • Page - 589

    $("#loading_animation").bind({ ajaxStart: function() { $(this).show(); }, ajaxStop: function() { $(this).hide(); } }); context jQuery.ajax() global false global false context 19.7 Utility Functions jQuery.browser browser msie true mozilla webkit opera version if ($.browser.mozilla && parseInt($.browser.version) < 4) { // Work around a hypothetical Firefox bug here... } read more..

  • Page - 590

    this false jQuery.each() jQuery.each() jQuery.each() for/in jQuery.each() jQuery.extend() undefined null jQuery true var clone = jQuery.extend({}, original); var options = jQuery.extend({}, default_options, user_options); jQuery.globalEval() <script> <script> jQuery.grep() filter() jQuery.grep() true true jQuery.grep() false jQuery.inArray() indexOf() 572 | Chapter 19: The jQuery Library read more..

  • Page - 591

    jQuery.isArray() true jQuery.isEmptyObject true jQuery.isFunction() true Window.alert() Element.attachEvent() jQuery.isPlainObject() true jQuery.makeArray() jQuery.map() map() jQuery.map() map() null jQuery.merge() var clone = jQuery.merge([], original); jQuery.parseJSON() JSON.parse() jQuery.proxy() bind() bind() 19.7 Utility Functions | 573 Client-Side JavaScript read more..

  • Page - 592

    jQuery.proxy() jQuery.proxy(o,n) jQuery.proxy(o[n],o) jQuery.proxy() jQuery.support jQuery.browser jQuery.support jQuery.support jQuery.support.boxModel true false jQuery.trim() trim() 19.8 jQuery Selectors and Selection Methods $() 19.8.1 jQuery Selectors id <blockquote> <div> class 574 | Chapter 19: The jQuery Library read more..

  • Page - 593

    $() 19.8.1.1 Simple selectors <p> Filter Meaning #id Matches the element with an id attribute of id. Valid HTML documents never have more than one element with the same ID, so this filter is usually used as a stand-alone selector. .class Matches any elements whose class attribute (when interpreted as a list of words separated by spaces) includes the word class. [attr] read more..

  • Page - 594

    Filter Meaning determined with their textContent or innerText properties—this is the raw document text, with tags and comments stripped out. :disabled Matches disabled elements. :empty Matches elements that have no children, including no text content. :enabled Matches elements that are not disabled. :eq(n) Matches only the nth element of the document-order zero-indexed list of matches read more..

  • Page - 595

    Filter Meaning :only-child Matches elements that are the only child of their parent. :parent Matches elements that are parents. This is the opposite of :empty (jQuery extension). :password Matches <input type="password"> elements (jQuery extension). :radio Matches <input type="radio"> elements (jQuery extension). :reset Matches <input type="reset"> and <button read more..

  • Page - 596

    "blockquote i" // Matches an <i> element within a <blockquote> "ol > li" // An <li> element as a direct child of an <ol> "#output + *" // The sibling after the element with id="output" "div.note > h1 + p" // A <p> following a <h1> inside a <div read more..

  • Page - 597

    var paras = $("p"); paras.first() // Select only the first <p> element paras.last() // Select only the last <p> paras.eq(1) // Select the second <p> paras.eq(-2) // Select the second to last <p> paras[1] // The second <p> element, itself read more..

  • Page - 598

    $("p").has("a[href]") // Paragraphs that include links add() add() $() add() $() add() // Equivalent ways to select all <div> and all <p> elements $("div, p") // Use a selector group $("div").add("p") // Pass a selector to add() $("div").add($("p")) // Pass a jQuery object to read more..

  • Page - 599

    contents() <iframe> contents() next() prev() $("h1").next("p") // Same as $("h1+p") $("h1").prev() // Sibling elements before <h1> elements nextAll() prevAll() siblings() $("#footer").nextAll("p") // All <p> siblings following the #footer element $("#footer").prevAll() read more..

  • Page - 600

    end() end() // Find all <div> elements, then find the <p> elements inside them. // Highlight the <p> elements and then give the <div> elements a border. // First, without method chaining var divs = $("div"); var paras = divs.find("p"); paras.addClass("highlight"); divs.css("border", "solid black 1px"); // read more..

  • Page - 601

    jQuery.fn jQuery.fn.println = function() { // Join all the arguments into a space-separated string var msg = Array.prototype.join.call(arguments, " "); // Loop through each element in the jQuery object this.each(function() { // For each one, append the string as plain text, then append a <br/>. read more..

  • Page - 602

    jQuery.fn data() // This method prints its arguments (using the println() plugin method) // to the element with id "debug". If no such element exists, it is created // and added to the document. jQuery.debug = function() { var elt = jQuery("#debug"); // Find the #debug element if (elt.length == 0) { read more..

  • Page - 603

    RegExp.exec() :data(x) true data-x jQuery.expr[':'].data = function(element, index, match, array) { // Note: IE7 and before do not implement hasAttribute() return element.hasAttribute("data-" + match[3]); }; 19.10 The jQuery UI Library 19.10 The jQuery UI Library | 585 Client-Side JavaScript read more..

  • Page - 604

    datepicker() // Make <input> elements with class="date" into date picker widgets $("input.date").datepicker(); animate() datepicker() disableDatepicker() datepicker("disable") bind() bind() datepicker() 586 | Chapter 19: The jQuery Library read more..

  • Page - 605

    CHAPTER 20 Client-Side Storage localStorage sessionStorage localStorage sessionStorage 587 read more..

  • Page - 606

    Filesystem API Storage, Security, and Privacy 588 | Chapter 20: Client-Side Storage read more..

  • Page - 607

    20.1 localStorage and sessionStorage localStorage sessionStorage localStorage sessionStorage localStorage sessionStorage var name = localStorage.username; // Query a stored value. name = localStorage["username"]; // Array notation equivalent if (!name) { name = prompt("What is your name?"); // Ask the user a question. read more..

  • Page - 608

    // Convert a Date to a string when setting, and parse it when getting localStorage.lastRead = (new Date()).toUTCString(); var lastRead = new Date(Date.parse(localStorage.lastRead)); // JSON makes a convenient encoding for any primitive or data structure localStorage.data = JSON.stringify(data); // Encode and store var data = JSON.parse(localStorage.data); // Retrieve and decode. 20.1.1 read more..

  • Page - 609

    sessionStorage <iframe> sessionStorage 20.1.2 Storage API localStorage sessionStorage setItem() getItem() removeItem() delete clear() length length key() local Storage sessionStorage localStorage.setItem("x", 1); // Store an number with the name "x" localStorage.getItem("x"); // Retrieve a value // Enumerate all stored name/value pairs for(var i read more..

  • Page - 610

    getItem() localStorage.getItem("o").x = 2; // We don't expect this to store the value 2 localStorage // Figure out what memory I'm using var memory = window.localStorage || (window.UserDataStorage && new UserDataStorage()) || new CookieStorage(); // Then search my memory var username = memory.getItem("username"); 20.1.3 read more..

  • Page - 611

    storageArea localStorage sessionStorage url localStorage localStorage localStorage 20.2 Cookies cookie Why “Cookie?” https: cookie cookie 20.2 Cookies | 593 Client-Side JavaScript read more..

  • Page - 612

    Determining Whether Cookies Are Enabled navigator.cookieEnabled true false 20.2.1 Cookie Attributes: Lifetime and Scope sessionStorage localStorage sessionStorage 594 | Chapter 20: Client-Side Storage read more..

  • Page - 613

    localStorage <iframe> 20.2.2 Storing Cookies cookie name=value document.cookie = "version=" + encodeURIComponent(document.lastModified); cookie encodeURIComponent() decodeURIComponent() 20.2 Cookies | 595 Client-Side JavaScript read more..

  • Page - 614

    max-age cookie name=value; max-age=seconds max-age // Store the name/value pair as a cookie, encoding the value with // encodeURIComponent() in order to escape semicolons, commas, and spaces. // If daysToLive is a number, set the max-age attribute so that the cookie // expires after the specified number of days. Pass 0 to delete a cookie. function setCookie(name, value, daysToLive) { read more..

  • Page - 615

    // Return the document's cookies as an object of name/value pairs. // Assume that cookie values are encoded with encodeURIComponent(). function getCookies() { var cookies = {}; // The object we will return var all = document.cookie; // Get all cookies in one big string if (all === "") // read more..

  • Page - 616

    if (all === "") // If the property is the empty string return cookies; // return an empty object var list = all.split("; "); // Split into individual name=value pairs for(var i = 0; i < list.length; i++) { // For each cookie read more..

  • Page - 617

    if (!(key in cookies)) return; // If it doesn't exist, do nothing // Delete the cookie from our internal set of cookies delete cookies[key]; // And remove the key from the array of names, too. // This would be easier with the ES5 array indexOf() method. for(var i read more..

  • Page - 618

    name = prompt("What is your name?); // Get user input memory.setAtttribute("username", name); // Set it as an attribute memory.save("myStoredData"); // And save it for next time } expires var now = (new Date()).getTime(); // Now, in milliseconds var expires = now + 100 * 24 * read more..

  • Page - 619

    this.removeItem = function(key) { memory.removeAttribute(key); // Remove stored value attribute memory.save("UserDataStorage"); // Save new state }; } <!--[if IE]> <script src="UserDataStorage.js"></script> <![endif]--> 20.4 Application Storage and Offline Webapps localStorage sessionStorage 20.4.1 The Application Cache read more..

  • Page - 620

    CACHE MANIFEST # The line above identifies the file type. This line is a comment # The lines below specify the resources the application needs to run myapp.html myapp.js myapp.css images/background.png Cache Manifest MIME Type <html manifest=> 20.4.1.1 Complex manifests 602 | Chapter 20: Client-Side Storage read more..

  • Page - 621

    CACHE MANIFEST CACHE: myapp.html myapp.css myapp.js FALLBACK: videos/ offline_help.html NETWORK: cgi/ 20.4.2 Cache Updates 20.4 Application Storage and Offline Webapps | 603 Client-Side JavaScript read more..

  • Page - 622

    CACHE MANIFEST # MyApp version 1 (change this number to make browsers redownload the files) MyApp.html MyApp.js applicationCache.onupdateready = function() { var reload = confirm("A new version of this application is available\n" + "and will be used the next time you reload.\n" + read more..

  • Page - 623

    status("This version is up-to-date.") return false; }; // If the application is not already cached, or if the manifest has changed, // the browser downloads and caches everything listed in the manifest. // The downloading event signals the start of this download process. window.applicationCache.ondownloading = function() { status("Downloading new version"); read more..

  • Page - 624

    status("This application is no longer cached. " + "Reload to get the latest version from the network."); return false; }; manifest false applicationCache.status ApplicationCache.UNCACHED (0) manifest ApplicationCache.IDLE (1) ApplicationCache.CHECKING (2) 606 | Chapter 20: Client-Side Storage read more..

  • Page - 625

    ApplicationCache.DOWNLOADING (3) ApplicationCache.UPDATEREADY (4) ApplicationCache.OBSOLETE (5) update() swapCache() swapCache() swapCache() swapCache() status ApplicationCache.UPDATEREADY ApplicationCache.OBSOLETE swapCache() status OBSOLETE swapCache() status 20.4.3 Offline Web Applications 20.4 Application Storage and Offline Webapps | 607 Client-Side JavaScript read more..

  • Page - 626

    localStorage navigator.onLine localStorage CACHE MANIFEST # PermaNote v8 permanote.html permanote.js NETWORK: note <textarea> <html> manifest <!DOCTYPE HTML> <html manifest="permanote.appcache"> <head> <title>PermaNote Editor</title> <script src="permanote.js"></script> <style> #editor { width: 100%; height: 250px; } read more..

  • Page - 627

    </head> <body> <div id="toolbar"> <button id="savebutton" onclick="save()">Save</button> <button onclick="sync()">Sync Note</button> <button onclick="applicationCache.update()">Update Application</button> </div> <textarea id="editor"></textarea> read more..

  • Page - 628

    // Some variables we need throughout var editor, statusline, savebutton, idletimer; // The first time the application loads window.onload = function() { // Initialize local storage if this is the first time if (localStorage.note == null) localStorage.note = ""; if (localStorage.lastModified == null) localStorage.lastModified = 0; if read more..

  • Page - 629

    }; // Also let the user know if there is not a new version available. window.applicationCache.onnoupdate = function() { status("You are running the latest version of the application."); }; // A function to display a status message in the status line function status(msg) { statusline.innerHTML = msg; } // Upload the note text to the server (if we're online). // Will be read more..

  • Page - 630

    status("Ignoring newer version of the note."); localStorage.lastModified = now; } else status("You are editing the current version of the note."); if (localStorage.lastModified > read more..

  • Page - 631

    CHAPTER 21 Scripted Media and Graphics <audio> <video> <canvas> <canvas> 21.1 Scripting Images <img> <img> src 613 read more..

  • Page - 632

    :hover <img src="images/help.gif" onmouseover="this.src='images/help_rollover.gif'" onmouseout="this.src='images/help.gif'"> <img> src <img> <a> onclick Image() src <script>(new Image()).src = "images/help_rollover.gif";</script> <img src="images/help.gif" onmouseover="this.src='images/help_rollover.gif'" read more..

  • Page - 633

    document.images[] <img> /** * rollover.js: unobtrusive image rollovers. * * To create image rollovers, include this module in your HTML file and * use the data-rollover attribute on any <img> element to specify the URL of * the rollover image. For example: * * <img src="normal_image.png" data-rollover="rollover_image.png"> * * Note that this read more..

  • Page - 634

    <audio id="music"> <source src="music.mp3" type="audio/mpeg"> <source src="music.ogg" type='audio/ogg; codec="vorbis"'> </audio> <source> </source> /> <audio> <video> <object> <video id="news" width=640 height=480 controls preload> <!-- WebM format for Firefox and Chrome --> <source src="news.webm" type='video/webm; read more..

  • Page - 635

    Audio() <audio> document.createElement("audio") Video() 21.2.1 Type Selection and Loading codec canPlayType() var a = new Audio(); if (a.canPlayType("audio/wav")) { a.src = "soundeffect.wav"; a.play(); } src preload src <source> src <source> load() 21.2.2 Controlling Media Playback <audio> <video> play() pause() // When the document has loaded, read more..

  • Page - 636

    initialTime duration currentTime volume muted true false volume playbackRate <audio> <video> defaultPlaybackRate play() playbackRate defaultPlaybackRate currentTime volume muted playbackRate <audio> <video> controls muted currentTime controls loop preload autoplay controls true false loop true false preload preload preload autoplay autoplay true 21.2.3 Querying Media Status <audio> <video> paused true read more..

  • Page - 637

    initialTime currentTime initialTime played buffered seekable currentTime duration played buffered seekable TimeRanges length start() end() start(0) end(0) var percent_loaded = Math.floor(song.buffered.end(0) / song.duration * 100); readyState networkState error <audio> <video> if (song.readyState === song.HAVE_ENOUGH_DATA) song.play(); readyState Constant Value Description HAVE_NOTHING 0 No media data or metadata has read more..

  • Page - 638

    Constant Value Description HAVE_ENOUGH_DATA 4 Enough media data has been loaded that the browser is likely to be able to play to the end without pausing. networkState Constant Value Description NETWORK_EMPTY 0 The element has not started using the network. This would be the state before the src attribute was set, for example. NETWORK_IDLE 1 The element is not currently loading data from read more..

  • Page - 639

    addEventListener() <audio> <video> Event Type Description loadstart Triggered when the element begins requesting media data. networkState is NETWORK_LOADING. progress Network activity is continuing to load media data. networkState is NETWORK_LOADING. Typ- ically fired between 2 and 8 times per second. loadedmetadata The media metadata has been loaded, and the duration and dimensions of read more..

  • Page - 640

    Event Type Description error A network or other error prevented media data from being loaded. error.code is a value other than MEDIA_ERR_ABORTED. emptied An error or abort has caused the networkState to return to NETWORK_EMPTY. 21.3 SVG: Scalable Vector Graphics <!-- Begin an SVG figure and declare our namespace --> <svg xmlns="http://www.w3.org/2000/svg" read more..

  • Page - 641

    <img> <object> <?xml version="1.0"?> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:svg="http://www.w3.org/2000/svg"> <!-- declare HTML as default namespace and SVG with "svg:" prefix --> <body> This is a red square: <svg:svg width="10" height="10"> <svg:rect x="0" y="0" width="10" read more..

  • Page - 642

    <!DOCTYPE html> <html> <body> This is a red square: <svg width="10" height="10"> <rect x="0" y="0" width="10" height="10" fill="red"/> </svg> This is a blue circle: <svg width="10" height="10"> <circle cx="5" cy="5" r="5" fill="blue"/> </svg> </body> read more..

  • Page - 643

    /** * Create an <svg> element and draw a pie chart into it. * Arguments: * data: an array of numbers to chart, one for each wedge of the pie. * width,height: the size of the SVG graphic, in pixels * cx, cy, r: the center and radius of the pie * colors: an array of HTML color strings, one for each wedge * labels: an read more..

  • Page - 644

    // Create the <svg> element, and specify pixel size and user coordinates var chart = document.createElementNS(svgns, "svg:svg"); chart.setAttribute("width", width); chart.setAttribute("height", height); chart.setAttribute("viewBox", "0 0 " + width + " " + height); // Add up the data values so we know how big read more..

  • Page - 645

    var icon = document.createElementNS(svgns, "rect"); icon.setAttribute("x", lx); // Position the square icon.setAttribute("y", ly + 30*i); icon.setAttribute("width", 20); // Size the square icon.setAttribute("height", 20); read more..

  • Page - 646

    pieChart([12, 23, 34, 45], 640, 400, 200, 200, 150, ['red','blue','yellow','green'], ['North','South', 'East', 'West'], 400, 100)); "> </body> </html> <line> transform <line> read more..

  • Page - 647

    // Get SVG elements for the hands of the clock var minhand = document.getElementById("minutehand"); var hourhand = document.getElementById("hourhand"); // Set an SVG attribute on them to move them around the clock face minhand.setAttribute("transform", "rotate(" + minangle + ",50,50)"); read more..

  • Page - 648

    <g id="numbers"> <!-- Number the cardinal directions--> <text x="50" y="18">12</text><text x="85" y="53">3</text> <text x="50" y="88">6</text><text x="15" y="53">9</text> </g> <!-- Draw hands pointing read more..

  • Page - 649

    3D Graphics in a Canvas <canvas> getContext() <canvas> <body> This is a red square: <canvas id="square" width=10 height=10></canvas>. This is a blue circle: <canvas id="circle" width=10 height=10></canvas>. <script> var canvas = document.getElementById("square"); // Get first canvas element var context = canvas.getContext("2d"); read more..

  • Page - 650

    <canvas> <canvas> <canvas> c width height c var canvas = document.getElementById("my_canvas_id"); var c = canvas.getContext('2d'); <canvas> 21.4.1 Drawing Lines and Filling Polygons beginPath() moveTo() moveTo() lineTo() c.beginPath(); // Start a new path c.moveTo(100, 100); // Begin a subpath at (100,100) c.lineTo(200, 200); // Add a line from read more..

  • Page - 651

    stroke() fill() c.fill(); // Fill a triangular area c.stroke(); // Stroke two sides of the triangle fill() close Path() lineTo(100,100) closePath() stroke() fill() c.moveTo(300,100); // Begin a new subpath at (300,100); c.lineTo(300,200); // Draw a vertical line down to (300,200); stroke() stroke() fill() fill() stroke() beginPath() read more..

  • Page - 652

    // Define a regular polygon with n sides, centered at (x,y) with radius r. // The vertices are equally spaced along the circumference of a circle. // Put the first vertex straight up or at the specified angle. // Rotate clockwise, unless the last argument is true. function polygon(c,n,x,y,r,angle,counterclockwise) { angle = angle || 0; counterclockwise = read more..

  • Page - 653

    fill() The Nonzero Winding Rule 21.4.2 Graphics Attributes fillStyle strokeStyle lineWidth fill() stroke() stroke() fill() stroke() strokeStyle fillStyle 21.4 Graphics in a <canvas> | 635 Client-Side JavaScript read more..

  • Page - 654

    Property Meaning fillStyle the color, gradient, or pattern for fills font the CSS font for text-drawing commands globalAlpha transparency to be added to all pixels drawn globalCompositeOperation how to combine new pixels with the ones underneath lineCap how the ends of lines are rendered lineJoin how vertexes are rendered lineWidth the width of stroked lines miterLimit maximum length of acute read more..

  • Page - 655

    // Revert to the last saved graphics state, but don't pop the stack. CanvasRenderingContext2D.prototype.revert = function() { this.restore(); // Restore the old graphics state. this.save(); // Save it again so we can go back to it. return this; // Allow method chaining. }; // Set the graphics attributes specified by the properties of read more..

  • Page - 656

    <canvas> width height <canvas> width height 21.4.4 Coordinate System Transforms setTransform() translate() rotate() Math.PI scale() 638 | Chapter 21: Scripted Media and Graphics read more..

  • Page - 657

    scale() translate() scale() 21.4.4.1 Understanding transformations mathematically translate() rotate() scale() 21.4 Graphics in a <canvas> | 639 Client-Side JavaScript read more..

  • Page - 658

    (x,y) (x',y') c.translate(dx,dy) x' = x + dx; // An X coordinate of 0 in the new system is dx in the old y' = y + dy; c.scale(sx,sy) x' = sx * x; y' = sy * y; c.rotate(a) x' = x * cos(a) - y * sin(a); y' = y * cos(a) + x * sin(a); (x,y) (x'',y'') (x', y') (x'',y'') x'' = sx*x + dx; y'' = sy*y + dy; scale() translate() x'' = sx*(x + dx); y'' = read more..

  • Page - 659

    transform() // Shear transform: // x' = x + kx*y; // y' = y + ky*x; function shear(c,kx,ky) { c.transform(1, ky, kx, 1, 0, 0); } // Rotate theta radians clockwise around the point (x,y) // This can also be accomplished with a translate,rotate,translate sequence function rotateAbout(c,theta,x,y) { var ct = Math.cos(theta), st = Math.sin(theta); c.transform(ct, read more..

  • Page - 660

    len var deg = Math.PI/180; // For converting degrees to radians // Draw a level-n Koch Snowflake fractal on the canvas context c, // with lower-left corner at (x,y) and side length len. function snowflake(c, n, x, y, len) { c.save(); // Save current transformation c.translate(x,y); // Translate origin to starting point read more..

  • Page - 661

    21.4.5 Drawing and Filling Curves arc() arcTo() arc() arcTo() bezierCurveTo() quadraticCurveTo() bezierCurveTo() 21.4 Graphics in a <canvas> | 643 Client-Side JavaScript read more..

  • Page - 662

    // A utility function to convert angles from degrees to radians function rads(x) { return Math.PI*x/180; } // Draw a circle. Scale and rotate if you want an ellipse instead. // There is no current point, so draw just the circle with no straight // line from the current point to the start of the circle. c.beginPath(); c.arc(75,100,50, // Center at read more..

  • Page - 663

    c.arcTo(500,150,400,150,20); // Add right edge and lower right corner. c.arcTo(400,150,400,50,10); // Add bottom edge and lower left corner. c.arcTo(400,50,500,50,0); // Add left edge and upper left corner. c.closePath(); // Close path to add the rest of the top edge. // Quadratic Bezier curve: one control point c.moveTo(75, 250); read more..

  • Page - 664

    context.strokeStyle = "blue"; // Stroke lines in blue context.fillStyle = "#aaa"; // Fill areas with light gray strokeStyle fillStyle var colors = [ "#f44", // Hexadecimal RGB value: red "#44ff44", // Hexadecimal RRGGBB value: green read more..

  • Page - 665

    fillStyle strokeStyle createPattern() var image = document.getElementById("myimage"); c.fillStyle = c.createPattern(image, "repeat"); createPattern() <img> <canvas> <video> Image() <canvas> <canvas> var offscreen = document.createElement("canvas"); // Create an offscreen canvas offscreen.width = offscreen.height = 10; // Set its size read more..

  • Page - 666

    // A linear gradient, diagonally across the canvas (assuming no transforms) var bgfade = c.createLinearGradient(0,0,canvas.width,canvas.height); bgfade.addColorStop(0.0, "#88f"); // Start with light blue in upper left bgfade.addColorStop(1.0, "#fff"); // Fade to white in lower right // A gradient between two concentric circles. Transparent in the middle // fading to translucent read more..

  • Page - 667

    lineWidth stroke() lineTo() 21.4 Graphics in a <canvas> | 649 Client-Side JavaScript read more..

  • Page - 668

    lineCap lineJoin miterLimit lineJoin miterLimit miterLimit 21.4.9 Text fillText() fillStyle strokeText() font font "48pt sans-serif" "bold 18px Times Roman" "italic 12pt monospaced" "bolder smaller serif" // bolder and smaller than the font of the <canvas> 650 | Chapter 21: Scripted Media and Graphics read more..

  • Page - 669

    textAlign fillText() strokeText() textBaseline (x,y) fillText() textAlign dir <canvas> textBaseline fillText() strokeText() font measureText() font TextMetrics var width = c.measureText(text).width; 21.4 Graphics in a <canvas> | 651 Client-Side JavaScript read more..

  • Page - 670

    21.4.10 Clipping stroke() fill() clip() polygon() // Define some drawing attributes c.font = "bold 60pt sans-serif"; // Big font c.lineWidth = 2; // Narrow lines c.strokeStyle = "#000"; // Black lines // Outline a rectangle and some text c.strokeRect(175, 25, 50, 325); // A vertical read more..

  • Page - 671

    // Make that path the clipping region. c.clip(); // Stroke the path with a 5 pixel line, entirely inside the clipping region. c.lineWidth = 10; // Half of this 10 pixel line will be clipped away c.stroke(); // Fill the parts of the rectangle and text that are inside the clipping region c.fillStyle = "#aaa" // Light read more..

  • Page - 672

    // Define a subtle shadow c.shadowColor = "rgba(100,100,100,.4)"; // Translucent gray c.shadowOffsetX = c.shadowOffsetY = 3; // Shadow offset to lower right c.shadowBlur = 5; // Soften shadow edges // Draw some text in a blue box using that shadow c.lineWidth = 10; c.strokeStyle = "blue"; c.strokeRect(100, 100, 300, 200); read more..

  • Page - 673

    21.4.12 Images drawImage() drawImage() <img> Image() <canvas> <video> <img> <video> drawImage() drawImage() drawImage() width height x y (x,y) (x+width, y+height) drawImage() drawImage() 21.4 Graphics in a <canvas> | 655 Client-Side JavaScript read more..

  • Page - 674

    // Draw a line in the upper left c.moveTo(5,5); c.lineTo(45,45); c.lineWidth = 8; c.lineCap = "round"; c.stroke(); // Define a transformation c.translate(50,100); c.rotate(-45*Math.PI/180); // Straighten out the line c.scale(10,10); // Enlarge it so we can see the individual pixels // Use draw image to copy the line c.drawImage(c.canvas, read more..

  • Page - 675

    <canvas> drawImage() 21.4.13 Compositing drawImage() globalCompositeOperation globalCompositeOperation globalCompositeOperation globalCompositeOperation 21.4 Graphics in a <canvas> | 657 Client-Side JavaScript read more..

  • Page - 676

    CanvasRenderingContext2D 658 | Chapter 21: Scripted Media and Graphics read more..

  • Page - 677

    fill() stroke() lineWidth 21.4 Graphics in a <canvas> | 659 Client-Side JavaScript read more..

  • Page - 678

    drawImage() 660 | Chapter 21: Scripted Media and Graphics read more..

  • Page - 679

    21.4.14 Pixel Manipulation getImageData() ImageData createImageData() putImageData() getImageData() putImageData() putImageData() globalAlpha getImageData() putImageData() getImageData() putImageData() // Smear the pixels of the rectangle to the right, producing a // sort of motion blur as if objects are moving from right to left. // n must be 2 or larger. Larger values produce bigger smears. // The read more..

  • Page - 680

    for(var row = 0; row < height; row++) { // For each row var i = row*width*4 + 4; // The offset of the second pixel of the row for(var col = 1; col < width; col++, i += 4) { // For each column data[i] = (data[i] + data[i-4]*m)/n; // Red pixel component read more..

  • Page - 681

    hitpath() canvas.onclick = function(event) { if (hitpath(this.getContext("2d"), event) { alert("Hit!"); // Click over current path } }; getImageData() // Returns true if the specified mouse event is over a nontransparent pixel. function hitpaint(context, event) { // Translate and scale mouse event coordinates to canvas coordinates read more..

  • Page - 682

    * Define sparklines with markup like this: * <span class="sparkline">3 5 7 6 6 9 11 15</span> * * Style sparklines with CSS like this: * .sparkline { background-color: #ddd; color: red; } * * - Sparkline color is from the computed style of the CSS color property. * - Sparklines are transparent, so the normal background color shows through. read more..

  • Page - 683

    elt.appendChild(canvas); // Insert the canvas into the element // Now plot the points (i,data[i]), transforming to canvas coordinates. var context = canvas.getContext('2d'); for(var i = 0; i < data.length; i++) { // For each data point var x = width*i/data.length; read more..

  • Page - 684

    read more..

  • Page - 685

    CHAPTER 22 HTML5 APIs getElementsByClassName() querySelectorAll() dataset classList <audio> <video> <canvas> 667 read more..

  • Page - 686

    22.1 Geolocation navigator.geolocation navigator.geolocation.getCurrentPosition() navigator.geolocation.watchPosition() navigator.geolocation.clearWatch() watchPosition() 668 | Chapter 22: HTML5 APIs read more..

  • Page - 687

    getCurrentPosition() watchPosition() navigator.geolocation.getCurrentPosition(function(pos) { var latitude = pos.coords.latitude; var longitude = pos.coords.longitude; alert("Your position: " + latitude + ", " + longitude); }); getCurrentPosition() // Return a newly created <img> element that will (once geolocation succeeds) // be set to display a Google map of the current read more..

  • Page - 688

    "?center=" + latitude + "," + longitude + "&size=640x640&sensor=true"; // Set the map zoom level using a rough heuristic var zoomlevel=20; // Start zoomed in almost all the way if (accuracy > 80) // Zoom out for read more..

  • Page - 689

    function error(e) { // The error object has a numeric code and a text message. Code values: // 1: the user did not give permission to share his or her location // 2: the browser was unable to determine the position // 3: a timeout occurred elt.innerHTML = "Geolocation read more..

  • Page - 690

    hash location.hash location.hash window.onhashchange location.hash history.pushState() history.pushState() JSON.stringify() <Back> #state Structured Clones pushState() JSON.stringify() JSON.parse() <canvas> 672 | Chapter 22: HTML5 APIs read more..

  • Page - 691

    pushState() replaceState() state pushState() state <!DOCTYPE html> <html><head><title>I'm thinking of a number...</title> <script> 22.2 History Management | 673 Client-Side JavaScript read more..

  • Page - 692

    window.onload = newgame; // Start a new game when we load window.onpopstate = popState; // Handle history events var state, ui; // Globals initialized in newgame() function newgame(playagain) { // Begin a new game of guess-the-number // Set up an object to hold document elements we care about ui = read more..

  • Page - 693

    var url = "#guess" + state.guessnum; // Now save the state object and the URL history.pushState(state, // State object to save "", // State title: current browsers ignore this url); // State URL: not useful to bookmark } // read more..

  • Page - 694

    ui.high.style.width = (100-state.high) + "%"; // Make sure the input field is visible, empty, and focused ui.input.style.visibility = "visible"; ui.input.value = ""; ui.input.focus(); // Set the prompt based on the user's most recent guess if (state.guess === undefined) ui.prompt.innerHTML read more..

  • Page - 695

    postMessage() postMessage() JSON.stringify() postMessage() "*" "/" postMessage() data postMessage() source origin onmessage() origin postMessage() <iframe> <script> 22.3 Cross-Origin Messaging | 677 Client-Side JavaScript read more..

  • Page - 696

    postMessage() <iframe> <!DOCTYPE html> <!-- This is a Twitter search gadget. Include it in any webpage, inside an iframe, and ask it to search for things by sending it a query string with postMessage(). Since it is in an <iframe> and not a <script>, it can't mess around with the containing document. --> <html> <head> <style>body { read more..

  • Page - 697

    } else { html += "<dl>"; // <dl> list of results for(var i = 0; i < tweets.length; i++) { read more..

  • Page - 698

    iframe.src = origin + gadget; // Set its URL iframe.width = "250"; // 250 pixels wide iframe.height = "100%"; // Full document height iframe.style.cssFloat = "right"; read more..

  • Page - 699

    22.4.1 Worker Objects Worker() var loader = new Worker("utils/loader.js"); Worker() postMessage() postMessage() loader.postMessage("file.txt"); postMessage() postMessage() postMessage() Window.postMessage() worker.onmessage = function(e) { var message = e.data; // Get message from event console.log("URL contents: " + message); // Do read more..

  • Page - 700

    terminate() 22.4.2 Worker Scope Worker() postMessage() onmessage postMessage() onmessage postMessage() onmessage close() terminate() onclose postMessage() close() import Scripts() // Before we start working, load the classes and utilities we'll need importScripts("collections/Set.js", "collections/Map.js", "utils/base64.js"); importScripts() Worker() importScripts() importScripts() importScripts() importScripts() read more..

  • Page - 701

    Worker Execution Model onmessage onmessage onload setTimeout() JSON isNaN() Date() Global self window setTimeout() clearTimeout() setInterval() clearInterval() location Worker() location href protocol host host name port pathname search hash navigator appName appVersion platform userAgent onLine addEventListener() removeEventListener() onerror Window.onerror false XMLHttpRequest() 22.4 Web Workers | 683 Client-Side JavaScript read more..

  • Page - 702

    Worker() Worker() Advanced Worker Features postMessage() onmessage Message Channel() postMessage() 22.4.3 Web Worker Examples smear() <img> <canvas> <img> <canvas> postMessage() postMessage() <canvas> data:// src <img> 684 | Chapter 22: HTML5 APIs read more..

  • Page - 703

    // Asynchronously replace the contents of the image with a smeared version. // Use it like this: <img src="testimage.jpg" onclick="smear(this)"/> function smear(img) { // Create an offscreen <canvas> the same size as the image var canvas = document.createElement("canvas"); canvas.width = img.width; canvas.height = img.height; read more..

  • Page - 704

    return pixels; } terminate() Debugging Workers console.log() onmessage if (typeof e.data === "string") { console.log("Worker: " + e.data); return; } postMessage() onmessage onerror // This file will be loaded with new Worker(), so it runs as an independent // thread and can safely use the synchronous XMLHttpRequest API. // Messages are expected to be read more..

  • Page - 705

    var url = urls[i]; // For each URL var xhr = new XMLHttpRequest(); // Begin an HTTP request xhr.open("GET", url, false); // false makes this synchronous xhr.send(); // Blocks until response is read more..

  • Page - 706

    Typed Arrays, <canvas>, and Core JavaScript <canvas> getImageData() data var bytes = new Uint8Array(1024); // One kilobyte of bytes for(var i = 0; i < bytes.length; i++) // For each element of the array bytes[i] = i & 0xFF; // Set it to the low 8 bits of index var copy = new Uint8Array(bytes); read more..

  • Page - 707

    n var matrix = new Float64Array(9); // A 3x3 matrix var 3dPoint = new Int16Array(3); // A point in 3D space var rgba = new Uint8Array(4); // A 4-byte RGBA pixel value var sudoku = new Uint8Array(81); // A 9x9 sudoku board set() var bytes = new Uint8Array(1024) // A 1K buffer var pattern = new Uint8Array([0,1,2,3]); // An read more..

  • Page - 708

    bytes.buffer[1] // => 255: this just sets a regular JS property bytes[1] // => 0: the line above did not set the byte ArrayBuffer() var buf = new ArrayBuffer(1024*1024); // One megabyte var asbytes = new Uint8Array(buf); // Viewed as bytes var asints = new read more..

  • Page - 709

    setUint8() false true 22.6 Blobs var blob = ... // We'll see how to obtain a Blob later blob.size // Size of the Blob in bytes blob.type // MIME type of the Blob, or "" if unknown var subblob = blob.slice(0,1024, "text/plain"); // First 1K of the Blob as text var last = blob.slice(blob.size-1024, 1024); // Last 1K of the read more..

  • Page - 710

    <input type="file"> postMessage() send() 692 | Chapter 22: HTML5 APIs read more..

  • Page - 711

    createObjectURL() blob:// 22.6.1 Files As Blobs <input type="file"> value files <input type="file"> name lastModifiedDate <script> // Log information about a list of selected files function fileinfo(files) { for(var i = 0; i < files.length; i++) { // files is an array-like object var f = files[i]; console.log(f.name, read more..

  • Page - 712

    dataTransfer.files 22.6.2 Downloading Blobs // GET the contents of the url as a Blob and pass it to the specified callback. // This code is untested: no browsers supported this API when it was written. function getBlob(url, callback) { var xhr = new XMLHttpRequest(); // Create new XHR object xhr.open("GET", url); // Specify read more..

  • Page - 713

    bb.append(ab); // Now get the blob from the builder, specifying a made-up MIME type var blob = bb.getBlob("x-optional/mime-type-here"); slice() append() 22.6.4 Blob URLs createObjectURL() URL webkitURL var getBlobURL = (window.URL && URL.createObjectURL.bind(URL)) || (window.webkitURL && webkitURL.createObjectURL.bind(webkitURL)) || window.createObjectURL; URL webkitURL read more..

  • Page - 714

    // At the time of this writing, Firefox and Webkit disagree on the // name of the createObjectURL() function var getBlobURL = (window.URL && URL.createObjectURL.bind(URL)) || (window.webkitURL && webkitURL.createObjectURL.bind(webkitURL)) || window.createObjectURL; var revokeBlobURL = (window.URL && URL.revokeObjectURL.bind(URL)) || (window.webkitURL && read more..

  • Page - 715

    <style> /* Simple styles for the file drop target */ #droptarget { border: solid black 2px; width: 200px; height: 200px; } #droptarget.active { border: solid red 4px; } </style> </head> <body> <!-- The document starts off with just the file drop target --> <div id="droptarget">Drop Image Files Here</div> </body> </html> file:// postMessage() read more..

  • Page - 716

    22.6.5 Reading Blobs FileReader() onload onerror onprogress addEventListener() readAsText() readAsArray Buffer() readAsDataURL() readAsBinaryString() readAsText() readyState result state result onprogress onload readAsText() <script> // Read the specified text file and display it in the <pre> element below function readfile(f) { var reader = new FileReader(); // Create a FileReader object read more..

  • Page - 717

    var out = document.getElementById("output"); // Find output element out.innerHTML = ""; // Clear it out.appendChild(document.createTextNode(text)); // Display file contents } reader.onerror = function(e) { // If anything goes wrong read more..

  • Page - 718

    22.7 The Filesystem API // Obtaining a filesystem synchronously. Pass filesystem lifetime and size. // Returns a filesystem object or raises an exception. var fs = requestFileSystemSync(PERSISTENT, 1024*1024); // The asynchronous version uses callback functions for success and error requestFileSystem(TEMPORARY, // lifetime 50*1024*1024, read more..

  • Page - 719

    root createReader() // Read the text file "hello.txt" and log its contents. // The asynchronous API nests functions four deep. // This example doesn't include any error callbacks. requestFileSystem(PERSISTENT, 10*1024*1024, function(fs) { // Get filesystem fs.root.getFile("hello.txt", {}, function(entry) { // Get FileEntry entry.file(function(file) { read more..

  • Page - 720

    */ // Lots of the asynchronous functions we use accept an optional error callback. // This one just logs the error. function logerr(e) { console.log(e); } // requestFileSystem() gets us a sandboxed local filesystem accessible only // to apps from this origin. We can read and write files at will, but // can't get out of the sandbox to access the rest of the system. var read more..

  • Page - 721

    // Now write the blob to the file writer.write(blob); writer.onerror = logerr; // Log errors from write() if (callback) // If there is a callback read more..

  • Page - 722

    var name = entries[i].name; // Get entry name if (entries[i].isDirectory) name += "/"; // Mark directories list.push(name); // Add to list read more..

  • Page - 723

    if (entries[i].isDirectory) name += "/"; list.push(name); } } while(entries.length > 0); return list; } // Allow the main thread to use these utilities by sending a message onmessage = function(e) { // We expect the message to be an object like this: // { function: read more..

  • Page - 724

    get() put() add() openCursor() get() openCursor() 706 | Chapter 22: HTML5 APIs read more..

  • Page - 725

    put() get() open Cursor() onsuccess onerror onsuccess result get() put() get() put() abort() commit() setVersion() setVersion() setVersion() createObject Store() createIndex() 22.8 Client-Side Databases | 707 Client-Side JavaScript read more..

  • Page - 726

    <!DOCTYPE html> <html> <head> <title>Zipcode Database</title> <script> // IndexedDB implementations still use API prefixes var indexedDB = window.indexedDB || // Use the standard DB API window.mozIndexedDB || // Or Firefox's early version of it window.webkitIndexedDB; // Or Chrome's early read more..

  • Page - 727

    request.onerror = logerr; // Log any errors that occur request.onsuccess = function() { // Pass the result to this function // The result object is now in the request.result var object = request.result; if (object) // If we found a read more..

  • Page - 728

    output.innerHTML = "Matching zipcodes:"; lookupZipcodes(city, function(o) { var div = document.createElement("div"); var text = o.zipcode + ": " + o.city + ", " + o.state; div.appendChild(document.createTextNode(text)); output.appendChild(div); }); } // Set up the structure of the read more..

  • Page - 729

    // Now we need to download our zipcode data, parse it into objects // and store those objects in object store we created above. // // Our file of raw data contains lines formatted like this: // // 02130,Jamaica Plain,MA,42.309998,-71.11171 // read more..

  • Page - 730

    zipcode: fields[0], // All properties are string city: fields[1], state: fields[2], latitude: fields[3], read more..

  • Page - 731

    The WebSocket Protocol about:config true Web Socket() var socket = new WebSocket("ws://ws.example.com:1234/resource"); WebSocket() ws:// wss:// https:// socket.onopen = function(e) { /* The socket is now connected. */ }; socket.onclose = function(e) { /* The socket closed. */ }; socket.onerror = function(e) { /* Something went wrong! */ }; socket.onmessage = function(e) { var read more..

  • Page - 732

    socket.send("Hello, server!"); close() WebSocket() protocol <script> window.onload = function() { // Take care of some UI details var nick = prompt("Enter your nickname"); // Get user's nickname var input = document.getElementById("input"); // Find the input field input.focus(); read more..

  • Page - 733

    } // This is how we send messages to the server through the web socket input.onchange = function() { // When user strikes return var msg = nick + ": " + input.value; // Username plus user's input socket.send(msg); read more..

  • Page - 734

    wsserver.on("connection", function(socket) { socket.send("Welcome to the chat room."); // Greet the new client socket.on("message", function(msg) { // Listen for msgs from the client wsserver.broadcast(msg); // And broadcast them to everyone }); }); // Run the server on port 8000. Starting read more..

  • Page - 735

    PART III Core JavaScript Reference Arguments EvalError Number String Array Function Object SyntaxError Boolean Global RangeError TypeError Date JSON ReferenceError URIError Error Math RegExp replace() String.replace() replace eval() NaN read more..

  • Page - 736

    read more..

  • Page - 737

    Core JavaScript Reference arguments[ ] an array of function arguments Synopsis arguments Description arguments[] arguments arguments See Also Arguments Arguments arguments and other properties of a function Object Arguments Synopsis arguments arguments[n] Elements length 719 read more..

  • Page - 738

    Properties callee length Description arguments length callee callee Arguments.length Array.length See Also Function Arguments.callee not defined in strict mode the function that is currently running Synopsis arguments.callee Description arguments.callee Arguments.callee 720 | Core JavaScript Reference read more..

  • Page - 739

    Example // An unnamed function literal uses the callee property to refer // to itself so that it can be recursive var factorial = function(x) { if (x < 2) return 1; else return x * arguments.callee(x-1); } var y = factorial(5); // Returns 120 Arguments.length the number of arguments passed to a function Synopsis arguments.length Description length Function.length read more..

  • Page - 740

    Constructor new Array() new Array(size) new Array(element0, element1, ..., elementn) Arguments size length size element0, ... elementn Array() length Returns Array() length Array() new new Throws RangeError size Array() RangeError size Literal Syntax var a = [1, true, 'abc']; var b = [a[0], a[0]*2, f(x)]; Properties length Methods every() filter() forEach() indexOf() lastIndexOf() map() reduce() reduce Right() read more..

  • Page - 741

    concat() every() filter() forEach() indexOf() join() lastIndexOf() map() pop() push() reduce() reduceRight() reverse() shift() slice() some() sort() splice() toLocaleString() Array Core JavaScript Reference | 723 Core JavaScript Reference read more..

  • Page - 742

    toString() unshift() Description See Also Array.concat() concatenate arrays Synopsis array.concat(value, ...) Arguments value, ... array Returns array Description concat() array array concat() Example var a = [1,2,3]; a.concat(4, 5) // Returns [1,2,3,4,5] a.concat([4,5]); // Returns [1,2,3,4,5] a.concat([4,5],[6,7]) // Returns [1,2,3,4,5,6,7] a.concat(4, [5,[6,7]]) // Returns read more..

  • Page - 743

    Synopsis array.every(predicate) array.every(predicate, o) Arguments predicate o this predicate Returns true predicate true array false false Description every() array predicate predicate false false every() false predicate true every() true every() true i predicate predicate(array[i], i, array) predicate true false Array.forEach() Example [1,2,3].every(function(x) { return x < 5; }) // => true: all elts are < 5 read more..

  • Page - 744

    Arguments predicate array o predicate Returns array predicate true Description filter() array predicate true filter() array predicate filter() array predicate i predicate predicate(array[i], i, array) predicate true i array filter() array Array.forEach() Example [1,2,3].filter(function(x) { return x > 1; }); // => [2,3] See Also Array.every() Array.forEach() Array.indexOf() Array.map() Array.reduce() Array.forEach() read more..

  • Page - 745

    Returns Description forEach() array f i f f(array[i], i, array) f forEach() array Array Method Details forEach() map() filter() every() some() o o this o this null array array Example var a = [1,2,3]; a.forEach(function(x,i,a) { a[i]++; }); // a is now [2,3,4] See Also Array.every() Array.filter() Array.indexOf() Array.map() Array.reduce() Array.indexOf() ECMAScript 5 search an array Synopsis read more..

  • Page - 746

    start Returns start array === value Description array value start === Example ['a','b','c'].indexOf('b') // => 1 ['a','b','c'].indexOf('d') // => -1 ['a','b','c'].indexOf('a',1) // => -1 See Also Array.lastIndexOf() String.indexOf() Array.join() concatenate array elements to form a string Synopsis array.join() array.join(separator) Arguments separator Returns array separator Description join() separator read more..

  • Page - 747

    Example a = new Array(1, 2, 3, "testing"); s = a.join("+"); // s is the string "1+2+3+testing" See Also String.split() Array.lastIndexOf() ECMAScript 5 search backward through an array Synopsis array.lastIndexOf(value) array.lastIndexOf(value, start) Arguments value array start Returns start array === value Description array value start === See Also Array.indexOf() String.lastIndexOf() read more..

  • Page - 748

    Description length length length Array() length a = new Array(); // a.length initialized to 0 b = new Array(10); // b.length initialized to 10 c = new Array("one", "two", "three"); // c.length initialized to 3 c[3] = "four"; read more..

  • Page - 749

    Example [1,2,3].map(function(x) { return x*x; }); // => [1,4,9] See Also Array.every() Array.filter() Array.forEach() Array.indexOf() Array.reduce() Array.pop() remove and return the last element of an array Synopsis array.pop() Returns array Description pop() array pop() undefined Example pop() push() var stack = []; // stack: [] stack.push(1, 2); // stack: [1,2] read more..

  • Page - 750

    Returns Description push() array array push() pop() Array.pop() See Also Array.pop() Array.reduce() ECMAScript 5 compute a value from the elements of an array Synopsis array.reduce(f) array.reduce(f, initial) Arguments f initial reduce() array Returns f Description reduce() f array n reduce() f n-1 f array f array f reduce() reduce() initial initial reduce() array array reduce() initial f Array.reduce() 732 | Core read more..

  • Page - 751

    f initial array initial n+1 n array initial f n array initial reduce() array initial reduce() initial f array initial reduce() array f f reduce() array f Example [1,2,3,4].reduce(function(x,y) { return x*y; }) // => 24: ((1*2)*3)*4 See Also Array.forEach() Array.map() Array.reduceRight() Array.reduceRight() ECMAScript 5 reduce an array from right-to-left Synopsis array.reduceRight(f) array.reduceRight(f, initial) Arguments read more..

  • Page - 752

    See Also Array.reduce() Array.reverse() reverse the elements of an array Synopsis array.reverse() Description reverse() array array Example a = new Array(1, 2, 3); // a[0] == 1, a[2] == 3; a.reverse(); // Now a[0] == 3, a[2] == 1; Array.shift() shift array elements down Synopsis array.shift() Returns Description shift() array shift() undefined shift() array read more..

  • Page - 753

    Array.slice() return a portion of an array Synopsis array.slice(start, end) Arguments start end start Returns array start end Description slice() array start end end start array slice() Array.splice() Example var a = [1,2,3,4,5]; a.slice(0,3); // Returns [1,2,3] a.slice(3); // Returns [4,5] a.slice(1,-1); // Returns [2,3,4] a.slice(-3,-2); // Returns [3]; buggy in IE 4: returns read more..

  • Page - 754

    Array.some() ECMAScript 5 test whether a predicate is true for any element Synopsis array.some(predicate) array.some(predicate, o) Arguments predicate o this predicate Returns true predicate true array false false Description some() array predi cate predicate true true some() true predi cate false false some() false some() false every() Array.every() Array.forEach() Example [1,2,3].some(function(x) { return x > 5; }) // read more..

  • Page - 755

    Arguments orderfunc Returns Description sort() array sort() a b a b b a b a b orderfunc Example // An ordering function for a numerical sort function numberorder(a, b) { return a - b; } a = new Array(33, 4, 1111, 222); a.sort(); // Alphabetical sort: 1111, 222, 33, 4 a.sort(numberorder); // Numerical sort: 4, 33, 222, 1111 Array.splice() insert, read more..

  • Page - 756

    deleteCount start array value, ... array start Returns array Description splice() start slice() splice() array Example splice() var a = [1,2,3,4,5,6,7,8] a.splice(1,2); // Returns [2,3]; a is [1,4] a.splice(1,1); // Returns [4]; a is [1] a.splice(1,0,2,3); // Returns []; a is [1 2 3] See Also Array.slice() Array.toLocaleString() convert an array to a localized string Overrides read more..

  • Page - 757

    See Also Array.toString() Object.toLocaleString() Array.toString() convert an array to a string Overrides Object.toString() Synopsis array.toString() Returns array Throws TypeError Description toString() toString() toString() toString() toString() join() See Also Array.toLocaleString() Object.toString() Array.unshift() insert elements at the beginning of an array Synopsis array.unshift(value, ...) Arguments value, ... array read more..

  • Page - 758

    Description unshift() array shift() unshift() array Example unshift() shift() var a = []; // a:[] a.unshift(1); // a:[1] Returns: 1 a.unshift(22); // a:[22,1] Returns: 2 a.shift(); // a:[1] Returns: 22 a.unshift(33,[4,5]); // read more..

  • Page - 759

    Description toString() toString() See Also Object Boolean.toString() convert a boolean value to a string Overrides Object.toString() Synopsis b.toString() Returns b Throws TypeError Boolean.valueOf() the boolean value of a Boolean object Overrides Object.valueOf() Synopsis b.valueOf() Returns b Throws TypeError Boolean.valueOf() Core JavaScript Reference | 741 Core JavaScript Reference read more..

  • Page - 760

    Date manipulate dates and times Object Date Constructor new Date() new Date(milliseconds) new Date(datestring) new Date(year, month, day, hours, minutes, seconds, ms) Date() getTime() Date.parse() Date.UTC() Date() new Date() Arguments milliseconds datestring Date.parse() year 2001 month day hours minutes Date 742 | Core JavaScript Reference read more..

  • Page - 761

    seconds ms Methods get[UTC]Day() getDay() getUTCDay() get[UTC]Date() get[UTC]Day() get[UTC]FullYear() get[UTC]Hours() get[UTC]Milliseconds() get[UTC]Minutes() get[UTC]Month() get[UTC]Seconds() getTime() getUTCTime() getTimezoneOffset() getYear() getFullYear() Date Core JavaScript Reference | 743 Core JavaScript Reference read more..

  • Page - 762

    set[UTC]Date() set[UTC]FullYear() set[UTC]Hours() set[UTC]Milliseconds() set[UTC]Minutes() set[UTC]Month() set[UTC]Seconds() setTime() setYear() setFullYear() toDateString() toGMTString() toUTC String() toISOString() toJSON() toISOString() toLocaleDateString() toLocaleString() Date 744 | Core JavaScript Reference read more..

  • Page - 763

    toLocaleTimeString() toString() toTimeString() toUTCString() valueOf() Static Methods Date() Date.now() Date.parse() Date.UTC() Description new Date() toString() getTime() setTime() Date Core JavaScript Reference | 745 Core JavaScript Reference read more..

  • Page - 764

    Examples d = new Date(); // Get the current date and time document.write('Today is: " + d.toLocaleDateString() + '. '); // Display date document.write('The time is: ' + d.toLocaleTimeString()); // Display time var dayOfWeek = d.getDay(); // What weekday is it? var weekend = (dayOfWeek == read more..

  • Page - 765

    Date.getDay() return the day-of-the-week field of a Date Synopsis date.getDay() Returns date Date.getFullYear() return the year field of a Date Synopsis date.getFullYear() Returns date Date.getHours() return the hours field of a Date Synopsis date.getHours() Returns date Date.getMilliseconds() return the milliseconds field of a Date Synopsis date.getMilliseconds() Returns date Date.getMilliseconds() Core JavaScript read more..

  • Page - 766

    Date.getMinutes() return the minutes field of a Date Synopsis date.getMinutes() Returns date Date.getMonth() return the month field of a Date Synopsis date.getMonth() Returns date Date.getSeconds() return the seconds field of a Date Synopsis date.getSeconds() Returns date Date.getTime() return a Date in milliseconds Synopsis date.getTime() Returns date date Date.getMinutes() 748 | Core JavaScript Reference read more..

  • Page - 767

    Description getTime() getUTCTime() getTime() getDay() getDate() Date.parse() Date.UTC() See Also Date Date.parse() Date.setTime() Date.UTC() Date.getTimezoneOffset() determine the offset from GMT Synopsis date.getTimezoneOffset() Returns Description getTimezoneOffset() date Date.getUTCDate() return the day-of-the-month field of a Date (universal time) Synopsis date.getUTCDate() Returns date Date.getUTCDate() Core JavaScript Reference read more..

  • Page - 768

    Date.getUTCDay() return the day-of-the-week field of a Date (universal time) Synopsis date.getUTCDay() Returns date Date.getUTCFullYear() return the year field of a Date (universal time) Synopsis date.getUTCFullYear() Returns date Date.getUTCHours() return the hours field of a Date (universal time) Synopsis date.getUTCHours() Returns date Date.getUTCMilliseconds() return the milliseconds field of a Date (universal read more..

  • Page - 769

    Date.getUTCMinutes() return the minutes field of a Date (universal time) Synopsis date.getUTCMinutes() Returns date Date.getUTCMonth() return the month-of-the-year field of a Date (universal time) Synopsis date.getUTCMonth() Returns date Date.getUTCSeconds() return the seconds field of a Date (universal time) Synopsis date.getUTCSeconds() Returns date Date.getYear() deprecated return the year field of a Date read more..

  • Page - 770

    Description getYear() getFullYear() Date.now() ECMAScript 5 return the current time in milliseconds Synopsis Date.now() Returns Description Date.now = function() { return (new Date()).getTime(); } See Also Date Date.getTime() Date.parse() parse a date/time string Synopsis Date.parse(date) Arguments date Returns Description Date.parse() Date.setTime() Date.toISO String() Date.now() 752 | Core JavaScript Reference read more..

  • Page - 771

    toUTCString() toString() See Also Date Date.setTime() Date.toISOString() Date.toString() Date.setDate() set the day-of-the-month field of a Date Synopsis date.setDate(day_of_month) Arguments day_of_month date Returns Date.setFullYear() set the year and, optionally, the month and date fields of a Date Synopsis date.setFullYear(year) date.setFullYear(year, month) date.setFullYear(year, month, day) Arguments year date month read more..

  • Page - 772

    Date.setHours() set the hours, minutes, seconds, and milliseconds fields of a Date Synopsis date.setHours(hours) date.setHours(hours, minutes) date.setHours(hours, minutes, seconds) date.setHours(hours, minutes, seconds, millis) Arguments hours date minutes date seconds date millis date Returns Date.setMilliseconds() set the milliseconds field of a Date Synopsis date.setMilliseconds(millis) Arguments millis date Returns read more..

  • Page - 773

    Date.setMinutes() set the minutes, seconds, and milliseconds fields of a Date Synopsis date.setMinutes(minutes) date.setMinutes(minutes, seconds) date.setMinutes(minutes, seconds, millis) Arguments minutes date seconds date millis date Returns Date.setMonth() set the month and day fields of a Date Synopsis date.setMonth(month) date.setMonth(month, day) Arguments month date day date Date.setMonth() Core JavaScript Reference read more..

  • Page - 774

    Returns Date.setSeconds() set the seconds and milliseconds fields of a Date Synopsis date.setSeconds(seconds) date.setSeconds(seconds, millis) Arguments seconds date millis date Returns Date.setTime() set a Date in milliseconds Synopsis date.setTime(milliseconds) Arguments milliseconds Date() Date.UTC() Date.parse() Returns milliseconds Date.setSeconds() 756 | Core JavaScript Reference read more..

  • Page - 775

    Date.setUTCDate() set the day-of-the-month field of a Date (universal time) Synopsis date.setUTCDate(day_of_month) Arguments day_of_month date Returns Date.setUTCFullYear() set the year, month, and day fields of a Date (universal time) Synopsis date.setUTCFullYear(year) date.setSeconds(seconds, millis) date.setUTCFullYear(year, month, day) Arguments year date month date day date Returns Date.setUTCHours() set the hours, read more..

  • Page - 776

    date.setUTCHours(hours, minutes, seconds) date.setUTCHours(hours, minutes, seconds, millis) Arguments hours date minutes date seconds date millis date Returns Date.setUTCMilliseconds() set the milliseconds field of a Date (universal time) Synopsis date.setUTCMilliseconds(millis) Arguments millis date Returns Date.setUTCMinutes() set the minutes, seconds, and milliseconds fields of a Date (universal time) Synopsis read more..

  • Page - 777

    Arguments minutes date seconds date millis date Returns Date.setUTCMonth() set the month and day fields of a Date (universal time) Synopsis date.setUTCMonth(month) date.setUTCMonth(month, day) Arguments month date day date Returns Date.setUTCSeconds() set the seconds and milliseconds fields of a Date (universal time) Synopsis date.setUTCSeconds(seconds) date.setUTCSeconds(seconds, millis) Date.setUTCSeconds() Core JavaScript read more..

  • Page - 778

    Arguments seconds date millis date Returns Date.setYear() deprecated set the year field of a Date Synopsis date.setYear(year) Arguments year date Returns Description setYear() setFullYear() Date.toDateString() return the date portion of a Date as a string Synopsis date.toDateString() Returns date Date.setYear() 760 | Core JavaScript Reference read more..

  • Page - 779

    See Also Date.toString() Date.toTimeString() Date.toGMTString() deprecated convert a Date to a universal time string Synopsis date.toGMTString() Returns date Description toGMTString() Date.toUTCString() toUTCString() See Also Date.toUTCString() Date.toISOString() ECMAScript 5 convert a Date to an ISO8601-formatted string Synopsis date.toISOString() Returns date yyyy-mm-ddThh:mm:ss.sssZ See Also Date.parse() Date.toString() read more..

  • Page - 780

    Date.toJSON ECMAScript 5 JSON-serialize a Date object Synopsis date.toJSON(key) Arguments key JSON.stringify() toJSON() Returns toISOString() Description JSON.stringify() See Also Date.toISOString() JSON.stringify() Date.toLocaleDateString() return the date portion of a Date as a locally formatted string Synopsis date.toLocaleDateString() Returns date See Also Date.toDateString() Date.toLocaleString() Date.toLocaleTimeString() read more..

  • Page - 781

    Returns date Usage toLocaleString() toLocaleString() See Also Date.toISOString() Date.toLocaleDateString() Date.toLocaleTimeString() Date.to- String() Date.toUTCString() Date.toLocaleTimeString() return the time portion of a Date as a locally formatted string Synopsis date.toLocaleTimeString() Returns date See Also Date.toDateString() Date.toLocaleDateString() Date.toLocaleString() Date.toString() Date.toTimeString() Date.toString() convert read more..

  • Page - 782

    See Also Date.parse() Date.toDateString() Date.toISOString() Date.toLocaleString() Date.toTimeString() Date.toUTCString() Date.toTimeString() return the time portion of a Date as a string Synopsis date.toTimeString() Returns date See Also Date.toString() Date.toDateString() Date.toLocaleTimeString() Date.toUTCString() convert a Date to a string (universal time) Synopsis date.toUTCString() Returns date Description toUTCString() date read more..

  • Page - 783

    Arguments year month day hours minutes seconds ms Returns Description Date.UTC() Date() Date.UTC() Date() Date.setTime() Date() Date.UTC() Date() Date.UTC() d = new Date(Date.UTC(1996, 4, 8, 16, 30)); See Also Date Date.parse() Date.setTime() Date.UTC() Core JavaScript Reference | 765 Core JavaScript Reference read more..

  • Page - 784

    Date.valueOf() convert a Date to millisecond representation Overrides Object.valueOf() Synopsis date.valueOf() Returns date Date.getTime() decodeURI() unescape characters in a URI Synopsis decodeURI(uri) Arguments uri Returns uri Throws URIError uri Description decodeURI() uri encodeURI() See Also decodeURIComponent() encodeURI() encodeURIComponent() escape() unescape() decodeURIComponent() unescape characters in a URI component read more..

  • Page - 785

    Arguments s Returns s Throws URIError s Description decodeURIComponent() s encodeURIComponent() See Also decodeURI() encodeURI() encodeURIComponent() escape() unescape() encodeURI() escape characters in a URI Synopsis encodeURI(uri) Arguments uri Returns uri Throws URIError uri Description encodeURI() uri - _ . ! ~ * ' ( ) encodeURI() Core JavaScript Reference | 767 Core JavaScript Reference read more..

  • Page - 786

    encodeURI() ; / ? : @ & = + $ , # uri %xx %xx \u0080 \u07ff encodeURIComponent() decodeURI() escape() unescape() Example // Returns http://www.isp.com/app.cgi?arg1=1&arg2=hello%20world encodeURI("http://www.isp.com/app.cgi?arg1=1&arg2=hello world"); encodeURI("\u00a9"); // The copyright character encodes to %C2%A9 See Also decodeURI() decodeURIComponent() encodeURIComponent() escape() unescape() read more..

  • Page - 787

    Description encodeURIComponent() s - _ . ! ~ * ' ( ) encodeURI() encodeURIComponent() encodeURI() encodeURIComponent() Example encodeURIComponent("hello world?"); // Returns hello%20world%3F See Also decodeURI() decodeURIComponent() encodeURI() escape() unescape() Error a generic exception Object Error Constructor new Error() new Error(message) Arguments message Returns message message Error() new new Properties read more..

  • Page - 788

    Methods toString() Description throw try/catch name message toString() toString() message toString() name message Examples function factorial(x) { if (x < 0) throw new Error("factorial: x must be >= 0"); if (x <= 1) return 1; else return x * factorial(x-1); } Window.alert() try { &*(&/* an error is thrown here */ } catch(e) { if (e instanceof Error) { read more..

  • Page - 789

    Description message message Error() message message Error.name the type of an error Synopsis error.name Description name name name Error.toString() convert an Error object to a string Overrides Object.toString() Synopsis error. toString() Returns escape() deprecated encode a string Synopsis escape(s) Arguments s escape() Core JavaScript Reference | 771 Core JavaScript Reference read more..

  • Page - 790

    Returns s Description escape() s s escape() s % xx %u xxxx x \u0000 \u00ff % xx %u xxxx unescape() escape() escape() encodeURI() encodeURIComponent() escape() Example escape("Hello World!"); // Returns "Hello%20World%21" See Also encodeURI() encodeURIComponent() eval() execute JavaScript code from a string Synopsis eval(code) Arguments code Returns code Throws eval() code code eval() eval() 772 | Core read more..

  • Page - 791

    Description eval() code eval eval() code eval() code eval() undefined code eval() eval() eval eval eval() eval eval eval() eval() eval() eval() code code eval() eval() Indirect call, ES5 eval() code var geval = eval; geval() code code eval() eval() eval() code eval() eval() code eval() Core JavaScript Reference | 773 Core JavaScript Reference read more..

  • Page - 792

    eval() Example eval("1+2"); // Returns 3 // This code uses client-side JavaScript methods to prompt the user to // enter an expression and to display the results of evaluating it. // See the client-side methods Window.alert() and Window.prompt() for details. try { alert("Result: " + eval(prompt("Enter an expression:",""))); } read more..

  • Page - 793

    See Also Error Error.message Error.name Function a JavaScript function Object Function Synopsis functionfunctionname(argument_name_list) // Function definition statement { body } function (argument_name_list) {body} // Unnamed function literal functionname(argument_value_list) // Function invocation Constructor new Function(argument_names..., body) Arguments argument_names... body read more..

  • Page - 794

    prototype Methods apply() bind() call() toString() Description proto type Function() arguments arguments[] Arguments See Also Arguments Function.apply() invoke a function as a method of an object Synopsis function.apply(thisobj, args) Arguments thisobj function thisobj this null Function.apply() 776 | Core JavaScript Reference read more..

  • Page - 795

    args function Returns function Throws TypeError args Description apply() function thisobj args this thisobj args Function.call() Example // Apply the default Object.toString() method to an object that // overrides it with its own version of the method. Note no arguments. Object.prototype.toString.apply(o); // Invoke the Math.max() method with apply to find the largest // element in an array. Note that read more..

  • Page - 796

    See Also Arguments Function.bind() ECMAScript 5 return a function that invokes this as a method Synopsis function.bind(o) function.bind(o, args...) Arguments o args... Returns o args Description bind() o args bind() Example f bind() var g = f.bind(o, 1, 2); g g(3) f.call(o, 1, 2, 3); See Also Function.apply() Function.call() Function.call() invoke a function as a method of an object Synopsis read more..

  • Page - 797

    Arguments thisobj function thisobj this null args... function Returns function Throws TypeError Description call() function thisobj thisobj call() this thisobj thisobj null Function.apply() Example // Call the default Object.toString() method on an object that // overrides it with its own version of the method. Note no arguments. Object.prototype.toString.call(o); See Also Function.apply() Function.caller deprecated; read more..

  • Page - 798

    Function.length the number of declared arguments Synopsis function.length Description length length Arguments.length See Also Arguments.length Function.prototype the prototype for a class of objects Synopsis function.prototype Description prototype prototype prototype See Also Function.toString() convert a function to a string Synopsis function.toString() Returns Function.length 780 | Core JavaScript Reference read more..

  • Page - 799

    Throws TypeError Description toString() func tion toString() eval() Global the global object Object Global Synopsis this Global Properties undefined undefined Global.undefined Infinity NaN undefined undefined Global Functions parseInt() parseInt() Global.parseInt() decodeURI() encodeURI() decodeURIComponent() encodeURIComponent() encodeURI Global Core JavaScript Reference | 781 Core JavaScript Reference read more..

  • Page - 800

    encodeURIComponent escape() eval() isFinite() isNaN() parseFloat() parseInt() unescape() escape() Global Objects Array Array() Boolean Boolean() Date Date() Error Error() EvalError EvalError() Function Function() JSON Math Global 782 | Core JavaScript Reference read more..

  • Page - 801

    Number Number() Object Object() RangeError RangeError() ReferenceError ReferenceError() RegExp RegExp() String String() SyntaxError SyntaxError() TypeError TypeError() URIError URIError() Description this parseInt() parseInt Global() Global Core JavaScript Reference | 783 Core JavaScript Reference read more..

  • Page - 802

    Example for/in var variables = "" for(var name in this) variables += name + "\n"; See Also Window Infinity a numeric property that represents infinity Synopsis Infinity Description Infinity Infinity for/in delete Infinity Number.POSITIVE_INFINITY See Also isFinite() NaN Number.POSITIVE_INFINITY isFinite() determine whether a number is finite Synopsis isFinite(n) Arguments n Returns true n read more..

  • Page - 803

    isNaN() check for not-a-number Synopsis isNaN(x) Arguments x Returns true x false Description NaN NaN isNaN() false x NaN true x NaN NaN NaN x === NaN false x !== x true x NaN isNaN() parseFloat() parseInt() Example isNaN(0); // => false isNaN(0/0); // => true isNaN(parseInt("3")); // => false read more..

  • Page - 804

    JSON ECMAScript 5 JSON parsing and stringification Description JSON JSON.parse() JSON.stringify() JSON null true false undefined Example // Make a deep copy of any object or array that can be JSON-serialized function deepcopy(o) { return JSON.parse(JSON.stringify(o)); } See Also JSON.parse() JSON.stringify() JSON.parse() ECMAScript 5 parse a JSON-formatted string Synopsis JSON.parse(s) JSON.parse(s, reviver) read more..

  • Page - 805

    reviver reviver s reviver reviver s reviver reviver reviver undefined JSON.parse() Example JSON.parse() var data = JSON.parse(text); JSON.stringify() reviver undefined var data JSON.parse(text, function(name, value) { // Remove any values whose property name begins with an underscore if (name[0] == '_') return undefined; // If the value is a string in ISO 8601 date format read more..

  • Page - 806

    Arguments o filter indent Returns o filter indent Description JSON.stringify() JSON.parse() JSON.stringify() null JSON.stringify() toJSON() toJSON() toJSON() Date.toISOString() toJSON() toJSON() JSON.stringify() toJSON() this undefined JSON.stringify() 788 | Core JavaScript Reference read more..

  • Page - 807

    JSON.stringify() JSON.stringify() JSON.stringify() Examples // Basic serialization var text = JSON.stringify(data); // Specify exactly what fields to serialize var text = JSON.stringify(address, ["city","state","country"]); // Specify a replacer function so that RegExp objects can be serialized var text = JSON.stringify(patterns, function(key, value) { if (value.constructor read more..

  • Page - 808

    Math.LOG2E Math.PI π Math.SQRT1_2 Math.SQRT2 Static Functions Math.abs() Math.acos() Math.asin() Math.atan() Math.atan2() Math.ceil() Math.cos() Math.exp() Math.floor() Math.log() Math.max() Math.min() Math.pow() Math.random() Math 790 | Core JavaScript Reference read more..

  • Page - 809

    Math.round() Math.sin() Math.sqrt() Math.tan() Description y = Math.sin(x); area = radius * radius * Math.PI; Math() Math.sin() See Also Number Math.abs() compute an absolute value Synopsis Math.abs(x) Arguments x Returns x Math.acos() compute an arccosine Synopsis Math.acos(x) Math.acos() Core JavaScript Reference | 791 Core JavaScript Reference read more..

  • Page - 810

    Arguments x Returns x π Math.asin() compute an arcsine Synopsis Math.asin(x) Arguments x Returns x π π Math.atan() compute an arctangent Synopsis Math.atan(x) Arguments x Returns x π π Math.atan2() compute the angle from the X axis to a point Synopsis Math.atan2(y, x) Math.asin() 792 | Core JavaScript Reference read more..

  • Page - 811

    Arguments y x Returns π π x y Description Math.atan2() y x y x Math.ceil() round a number up Synopsis Math.ceil(x) Arguments x Returns x Description Math.ceil() Math.ceil() Math.round() Math.ceil() Example a = Math.ceil(1.99); // Result is 2.0 b = Math.ceil(1.01); // Result is 2.0 c = Math.ceil(1.0); // Result is 1.0 d = Math.ceil(-1.99); // Result is -1.0 Math.ceil() Core read more..

  • Page - 812

    Math.cos() compute a cosine Synopsis Math.cos(x) Arguments x π Returns x Math.E the mathematical constant e Synopsis Math.E Description Math.E Math.exp() compute ex Synopsis Math.exp(x) Arguments x Returns x Math.cos() 794 | Core JavaScript Reference read more..

  • Page - 813

    Math.floor() round a number down Synopsis Math.floor(x) Arguments x Returns x Description Math.floor() Math.floor() Math.round() Math.floor() Example a = Math.floor(1.99); // Result is 1.0 b = Math.floor(1.01); // Result is 1.0 c = Math.floor(1.0); // Result is 1.0 d = Math.floor(-1.01); // Result is -2.0 Math.LN10 the mathematical constant loge10 Synopsis Math.LN10 Description read more..

  • Page - 814

    Description Math.LN2 Math.log() compute a natural logarithm Synopsis Math.log(x) Arguments x Returns x Description Math.log() log10x = log10e · logex log2x = log2e · logex function log10(x) { return Math.LOG10E * Math.log(x); } function log2(x) { return Math.LOG2E * Math.log(x); } Math.LOG10E the mathematical constant log10e Synopsis Math.LOG10E Description Math.LOG10E Math.LOG2E the mathematical read more..

  • Page - 815

    Description Math.LOG2E Math.max() return the largest argument Synopsis Math.max(args...) Arguments args... Returns -Infinity NaN NaN Math.min() return the smallest argument Synopsis Math.min(args...) Arguments args... Returns Infinity NaN NaN Math.PI the mathematical constant π Synopsis Math.PI Description Math.PI π Math.PI Core JavaScript Reference | 797 Core JavaScript Reference read more..

  • Page - 816

    Math.pow() compute xy Synopsis Math.pow(x, y) Arguments x y x Returns x y Description Math.pow() x y x y Math.pow() Math.pow() NaN x y Infinity Math.random() return a pseudorandom number Synopsis Math.random() Returns Math.round() round to the nearest integer Synopsis Math.round(x) Arguments x Returns x Math.pow() 798 | Core JavaScript Reference read more..

  • Page - 817

    Description Math.round() Math.sin() compute a sine Synopsis Math.sin(x) Arguments x π Returns x Math.sqrt() compute a square root Synopsis Math.sqrt(x) Arguments x Returns x NaN x Description Math.sqrt() Math.pow() Math.cuberoot = function(x){ return Math.pow(x,1/3); } Math.cuberoot(8); // Returns 2 Math.SQRT1_2 the mathematical constant 1/√2 Synopsis Math.SQRT1_2 Math.SQRT1_2 Core JavaScript Reference | 799 Core read more..

  • Page - 818

    Description Math.SQRT1_2 √ Math.SQRT2 the mathematical constant √2 Synopsis Math.SQRT2 Description Math.SQRT2 √ Math.tan() compute a tangent Synopsis Math.tan(x) Arguments x π Returns x NaN the not-a-number property Synopsis NaN Description NaN NaN for/in delete NaN isNaN() NaN Math.SQRT2 800 | Core JavaScript Reference read more..

  • Page - 819

    See Also Infinity isNaN() Number.NaN Number support for numbers Object Number Constructor new Number(value) Number(value) Arguments value Returns Number() new Number() new NaN Constants Number.MAX_VALUE Number.MIN_VALUE Number.NaN Number.NEGATIVE_INFINITY Number.POSITIVE_INFINITY Methods toString() toLocaleString() toFixed() Number Core JavaScript Reference | 801 Core JavaScript Reference read more..

  • Page - 820

    toExponential() toPrecision() valueOf() Description Number() Number() new NaN Number() NaN Number() MAX_VALUE var biggest = Number.MAX_VALUE var n = new Number(2); var biggest = n.MAX_VALUE toString() Number() var value = 1234; var binary_value = n.toString(2); See Also Infinity Math NaN Number.MAX_VALUE the maximum numeric value Synopsis Number.MAX_VALUE Number.MAX_VALUE 802 | Core JavaScript Reference read more..

  • Page - 821

    Description Number.MAX_VALUE Number.MIN_VALUE the minimum numeric value Synopsis Number.MIN_VALUE Description Number.MIN_VALUE Number.NaN the special not-a-number value Synopsis Number.NaN Description Number.NaN parseInt() parse Float() Number.NaN Number.NaN NaN NaN NaN Number.NaN isNaN() NaN Number.NaN See Also isNaN() NaN Number.NEGATIVE_INFINITY negative infinity Synopsis Number.NEGATIVE_INFINITY Number.NEGATIVE_INFINITY Core JavaScript read more..

  • Page - 822

    Description Number.NEGATIVE_INFINITY -Number.MAX_VALUE) NEGATIVE_INFINITY -Infinity -Infinity Num ber.NEGATIVE_INFINITY See Also Infinity isFinite() Number.POSITIVE_INFINITY infinity Synopsis Number.POSITIVE_INFINITY Description Number.POSITIVE_INFINITY Number.MAX_VALUE) Number.MIN_VALUE POSITIVE_INFINITY Infinity Infinity Number.POSITIVE_INFINITY See Also Infinity isFinite() Number.toExponential() format a number using exponential notation Synopsis read more..

  • Page - 823

    Returns number digits Throws digits Example var n = 12345.6789; n.toExponential(1); // Returns 1.2e+4 n.toExponential(5); // Returns 1.23457e+4 n.toExponential(10); // Returns 1.2345678900e+4 n.toExponential(); // Returns 1.23456789e+4 See Also Number.toFixed() Number.toLocaleString() Number.toPrecision() Number.toString() Number.toFixed() format a number using fixed-point notation read more..

  • Page - 824

    Example var n = 12345.6789; n.toFixed(); // Returns 12346: note rounding, no fractional part n.toFixed(1); // Returns 12345.7: note rounding n.toFixed(6); // Returns 12345.678900: note added zeros (1.23e+20).toFixed(2); // Returns 123000000000000000000.00 (1.23e-10).toFixed(2) // Returns 0.00 See Also read more..

  • Page - 825

    precision toString() Returns number precision precision number precision Throws digits Example var n = 12345.6789; n.toPrecision(1); // Returns 1e+4 n.toPrecision(3); // Returns 1.23e+4 n.toPrecision(5); // Returns 12346: note rounding n.toPrecision(10); // Returns 12345.67890: note added zero See Also Number.toExponential() Number.toFixed() Number.toLocaleString() Number.toString() Number.toString() convert read more..

  • Page - 826

    Throws Description toString() radix See Also Number.toExponential() Number.toFixed() Number.toLocaleString() Number.toPrecision() Number.valueOf() return the primitive number value Overrides Object.valueOf() Synopsis number.valueOf() Returns Throws See Also Object.valueOf() Object a superclass that contains features of all JavaScript objects Constructor new Object() new Object(value) Arguments value Number.valueOf() 808 | Core read more..

  • Page - 827

    Returns value value Object() new new Properties constructor Methods hasOwnProperty() isPrototypeOf() propertyIsEnumerable() for/in toLocaleString() toString() toString() toString() valueOf() Static Methods Object.create() Object.defineProperties() Object.defineProperty() Object Core JavaScript Reference | 809 Core JavaScript Reference read more..

  • Page - 828

    Object.freeze() Object.getOwnPropertyDescriptor() Object.getOwnPropertyNames() Object.getPrototypeOf() Object.isExtensible() Object.isFrozen() Object.isSealed() Object.keys() Object.preventExtensions() Object.seal() Description Object() See Also Array Boolean Function Function.prototype Number String Object.constructor an object’s constructor function Synopsis object.constructor Object.constructor 810 | Core JavaScript Reference read more..

  • Page - 829

    Description constructor a Array() a.constructor a = new Array(1,2,3); // Create an object a.constructor == Array // Evaluates to true constructor typeof constructor function isArray(x) { return ((typeof x == "object") && (x.constructor == Array)); } Object.toString() See Also Object.toString() Object.create() ECMAScript 5 create an object with specified prototype and properties read more..

  • Page - 830

    Description Object.create() proto proto descriptors Object.create() Object.defineProperties() Object.create(p,d) Object.defineProperties(Object.create(p), d); Object.defineProperties() descriptors Object.ge- tOwnPropertyDescriptor() Example // Create an object that has own properties x and y and inherits property z var p = Object.create({z:0}, { x: { value: 1, writable: false, enumerable:true, configurable: true}, read more..

  • Page - 831

    Description Object.defineProperties() o descriptors descriptors o Object.defineProperties() Object.defineProperty() Object.getOwnPropertyDescriptor() Example // Add read-only properties x and y to a newly-created object var p = Object.defineProperties({}, { x: { value: 0, writable: false, enumerable:true, configurable: true}, y: { value: 1, writable: false, enumerable:true, configurable: true}, }); read more..

  • Page - 832

    Throws o o Description Object.defineProperty() name o desc Object.getOwnPropertyDescriptor() o name desc desc false null name o Object.defineProperty() desc desc Example function constant(o, n, v) { // Define a constant o.n with value v Object.defineProperty(o, n, { value: v, writable: false enumerable: true, read more..

  • Page - 833

    Description Object.freeze() o Object.preventExtensions() Object.seal() o Object.freeze() Object.freeze() See Also Object.defineProperty() Object.isFrozen() Object.preventExtensions() Object.seal() Object.getOwnPropertyDescriptor() ECMAScript 5 query property attributes Synopsis Object.getOwnPropertyDescriptor(o, name) Arguments o name Returns undefined Description Object.getOwnPropertyDescriptor() Property Descriptors Object.getOwnPropertyDescriptor() read more..

  • Page - 834

    { value: /* any JavaScript value */, writable: /* true or false */, enumerable: /* true or false */, configurable: /* true or false */ } { get: /* function or undefined: replaces the property value */, set: /* function or undefined: replaces the writable read more..

  • Page - 835

    Object.getPrototypeOf() ECMAScript 5 return the prototype of an object Synopsis Object.getPrototypeOf(o) Arguments o Returns o Description Object.getPrototypeOf() Example var p = {}; // An ordinary object Object.getPrototypeOf(p) // => Object.prototype var o = Object.create(p) // An object that inherits from p Object.getPrototypeOf(o) read more..

  • Page - 836

    Description hasOwnProperty() Example var o = new Object(); // Create an object o.x = 3.14; // Define a noninherited local property o.hasOwnProperty("x"); // Returns true: x is a local property of o o.hasOwnProperty("y"); // Returns false: o doesn't have read more..

  • Page - 837

    Object.isFrozen() ECMAScript 5 is an object immutable? Synopsis Object.isFrozen(o) Arguments o Returns true o false Description Object.isFro zen() Object.freeze() Object.preventExtensions() Object.define- Property() See Also Object.defineProperty() Object.freeze() Object.isExtensible() Object.isSealed() Ob- ject.preventExtensions() Object.seal() Object.isPrototypeOf() is one object the prototype of another? Synopsis object.isPrototypeOf(o) read more..

  • Page - 838

    Description prototype isPrototypeOf() Example var o = new Object(); // Create an object Object.prototype.isPrototypeOf(o) // true: o is an object Function.prototype.isPrototypeOf(o.toString); // true: toString is a function Array.prototype.isPrototypeOf([1,2,3]); // true: [1,2,3] read more..

  • Page - 839

    See Also Object.defineProperty() Object.freeze() Object.isExtensible() Object.isFrozen() Ob- ject.preventExtensions() Object.seal() Object.keys() ECMAScript 5 return own enumerable property names Synopsis Object.keys(o) Arguments o Returns o Description Object.keys() o o Object.getOwnPropertyNames() for/in Example Object.keys({x:1, y:2}) // => ["x", "y"] See Also Object.getOwnPropertyNames() read more..

  • Page - 840

    Returns o Description Object.preventExtensions() o Object.preventExtensions() See Also Object.freeze() Object.isExtensible() Object.seal() Object.propertyIsEnumerable() will property be seen by a for/in loop? Synopsis object.propertyIsEnumerable(propname) Arguments propname object Returns true object propname for/in object Description for/in propertyIsEnumerable() propertyIsEnumerable() Example var o = new Object(); read more..

  • Page - 841

    See Also Function.prototype Object.hasOwnProperty() Object.seal() ECMAScript 5 prevent the addition or deletion of properties Synopsis Object.seal(o) Arguments o Returns o Description Object.seal() o Object.preventExtensions() Object.seal() Object.freeze() Object.seal() See Also Object.defineProperty() Object.freeze() Object.isSealed() Object.preventExten- sions() Object.toLocaleString() return an object’s localized string representation read more..

  • Page - 842

    Description toLocaleString() toString() See Also Array.toLocaleString() Date.toLocaleString() Number.toLocaleString() Object.to- String() Object.toString() define an object’s string representation Synopsis object.toString() Returns Description toString() toString() alert(my_object); + var msg = 'My object is: ' + my_object; toString() toString() toString() [objectclass] class toString() Object.toString() 824 | Core JavaScript read more..

  • Page - 843

    toString() Object.toString() o Object.prototype.toString.apply(o); class Object.constructor toString() toString() toString() y = Math.sqrt(x); // Compute a number ystr = y.toString(); // Convert it to a string toString() toString() toString() alert(my_obj.toString()); See Also Object.constructor Object.toLocaleString() Object.valueOf() Object.valueOf() the primitive value of the specified object read more..

  • Page - 844

    valueOf() valueOf() typeof valueOf() Object() Object() valueOf() Complex.prototype.valueOf = new Function("return this.real"); valueOf() Math.sqrt() See Also Object.toString() parseFloat() convert a string to a number Synopsis parseFloat(s) Arguments s Returns NaN s parse Float() NaN s Description parseFloat() s parseFloat() s parseFloat() 826 | Core JavaScript Reference read more..

  • Page - 845

    s parseFloat() NaN isNaN() parseInt() parseFloat() See Also isNaN() parseInt() parseInt() convert a string to an integer Synopsis parseInt(s) parseInt(s, radix) Arguments s radix par seInt() NaN Returns NaN s par seInt() NaN s Description parseInt() s parseInt() s radix s parseInt() NaN isNaN() radix parseInt() radix radix parseInt() s s 0x parseInt() s parseInt() Example parseInt("19", 10); // Returns 19 read more..

  • Page - 846

    parseInt("17", 8); // Returns 15 (8 + 7) parseInt("1f", 16); // Returns 31 (16 + 15) parseInt("10"); // Returns 10 parseInt("0x10"); // Returns 16 See Also isNaN() parseFloat() RangeError thrown when a number is out of its legal range Object Error RangeError Constructor new RangeError() new RangeError(message) Arguments message message read more..

  • Page - 847

    ReferenceError thrown when reading a variable that does not exist Object Error ReferenceError Constructor new ReferenceError() new ReferenceError(message) Arguments message message Returns message message ReferenceError() new new Properties message Error.mes- sage name Description Error See Also Error Error.message Error.name RegExp regular expressions for pattern matching Object RegExp Literal Syntax /pattern/attributes read more..

  • Page - 848

    Arguments pattern attributes pattern Returns RegExp pattern RegExp() RegExp() new new pattern pattern Throws SyntaxError pattern attributes TypeError pattern attributes Instance Properties global ignoreCase lastIndex multiline source Methods exec() test() RegExp 830 | Core JavaScript Reference read more..

  • Page - 849

    Description See Also RegExp.exec() general-purpose pattern matching Synopsis regexp.exec(string) Arguments string Returns null Throws TypeError Description exec() RegExp.test() String.search() String.replace() String.match() exec() string regexp null regexp length length exec() index input string String.match() exec() regexp exec() string lastIndex regexp lastIndex exec() exec() RegExp.exec() Core JavaScript Reference | 831 Core read more..

  • Page - 850

    null lastIndex lastIndex exec() regexp exec() String.match() exec() Example exec() var pattern = /\bJava\w*\b/g; var text = "JavaScript is more fun than Java or JavaBeans!"; var result; while((result = pattern.exec(text)) != null) { alert("Matched '" + result[0] + "' at position " + result.index + " next search begins at read more..

  • Page - 851

    Description ignoreCase RegExp.lastIndex the starting position of the next match Synopsis regexp.lastIndex Description lastIndex RegExp.exec() RegExp.test() lastIndex exec() test() lastIndex See Also RegExp.exec() RegExp.test() RegExp.source the text of the regular expression Synopsis regexp.source Description source RegExp.source Core JavaScript Reference | 833 Core JavaScript Reference read more..

  • Page - 852

    RegExp.test() test whether a string matches a pattern Synopsis regexp.test(string) Arguments string Returns true string regexp false Throws TypeError Description test() string regexp true false test() r s (r.exec(s) != null) Example var pattern = /java/i; pattern.test("JavaScript"); // Returns true pattern.test("ECMAScript"); // Returns false See Also RegExp.exec() RegExp.lastIndex read more..

  • Page - 853

    Description RegExp.toString() new RegExp("/","g") RegExp.toString() ///g /\//g String support for strings Object String Constructor new String(s) // Constructor function String(s) // Conversion function Arguments s Returns String() new s s String() new s Properties length Methods charAt() charCodeAt() concat() indexOf() lastIndexOf() String Core JavaScript Reference | 835 Core JavaScript Reference read more..

  • Page - 854

    localeCompare() match() replace() search() slice() split() substr() substring() substring() toLowerCase() toString() toUpperCase() trim() valueOf() Static Methods String.fromCharCode() HTML Methods var s = "click here!"; var html = s.bold().link("javascript:alert('hello')").fontcolor("red"); String 836 | Core JavaScript Reference read more..

  • Page - 855

    anchor( name ) <a name=> big() <big> blink() <blink> bold() <b> fixed() <tt> fontcolor( color ) <font color=> fontsize( size ) <font size=> italics() <i> link( url ) <a href=> small() <small> strike() <strike> sub() <sub> sup() <sup> Description length String.toUpperCase() String Core JavaScript Reference | 837 Core JavaScript Reference read more..

  • Page - 856

    s s[2] s.charAt(2) for/ in See Also String.charAt() get the ‘n’th character from a string Synopsis string.charAt(n) Arguments n string Returns n string Description String.charAt() n string n string.length See Also String.charCodeAt() String.indexOf() String.lastIndexOf() String.charCodeAt() get the nth character code from a string Synopsis string.charCodeAt(n) Arguments n Returns n string String.charAt() 838 | Core read more..

  • Page - 857

    Description charCodeAt() charAt() n charCodeAt() NaN String.fromCharCode() See Also String.charAt() String.fromCharCode() String.concat() concatenate strings Synopsis string.concat(value, ...) Arguments value, ... string Returns string Description concat() string string String.concat() Array.concat() + See Also Array.concat() String.fromCharCode() create a string from character encodings Synopsis String.fromCharCode(c1, c2, ...) Arguments read more..

  • Page - 858

    Returns Description fromCharCode() String() String.charCodeAt() Example // Create the string "hello" var s = String.fromCharCode(104, 101, 108, 108, 111); See Also String.charCodeAt() String.indexOf() search a string Synopsis string.indexOf(substring) string.indexOf(substring, start) Arguments substring string start string string .length Returns substring string start Description String.indexOf() string substring start read more..

  • Page - 859

    substring string String.indexOf() See Also String.charAt() String.lastIndexOf() String.substring() String.lastIndexOf() search a string backward Synopsis string.lastIndexOf(substring) string.lastIndexOf(substring, start) Arguments substring string start string string .length Returns substring string start string Description String.lastIndexOf() substring start string string start substring String.lastIn dexOf() start substring read more..

  • Page - 860

    String.length the length of a string Synopsis string.length Description String.length string s s .length length for/in delete String.localeCompare() compare one string to another, using locale-specific ordering Synopsis string.localeCompare(target) Arguments target string string Returns string target locale Compare() string target Description < > localeCompare() Example var strings; // The array of strings to read more..

  • Page - 861

    String.match() find one or more regular-expression matches Synopsis string.match(regexp) Arguments regexp RegExp() Returns regexp Description match() string regexp regexp regexp match() string match() null index string input string regexp match() string null string index input match() string RegExp.exec() Example "1 plus 2 equals 3".match(/\d+/g) // Returns ["1", "2", "3"] var url = read more..

  • Page - 862

    var result = text.match(url); if (result != null) { var fullurl = result[0]; // Contains "http://www.isp.com/~david" var protocol = result[1]; // Contains "http" var host = result[2]; // Contains "www.isp.com" var path = result[3]; // Contains "~david" } See Also RegExp RegExp.exec() read more..

  • Page - 863

    Characters Replacement $1, $2, ..., $99 The text that matched the 1st through 99th parenthesized subexpression within regexp $& The substring that matched regexp $' The text to the left of the matched substring $' The text to the right of the matched substring $$ A literal dollar sign replacement replace() string replacement string Example text.replace(/javascript/i, "JavaScript"); read more..

  • Page - 864

    Returns string regexp Description search() regexp string search() g lastIndex regexp string Example var s = "JavaScript is fun"; s.search(/script/i) // Returns 4 s.search(/a(.)a/) // Returns 1 See Also RegExp RegExp.exec() RegExp.test() String.match() String.replace() String.slice() extract a substring Synopsis string.slice(start, end) Arguments start end start Returns string start end Description slice() read more..

  • Page - 865

    slice() substr() substr() String.slice() Array.slice() Example var s = "abcdefg"; s.slice(0,4) // Returns "abcd" s.slice(2,4) // Returns "cd" s.slice(4) // Returns "efg" s.slice(3,-1) // Returns "def" s.slice(3,-2) // Returns "de" s.slice(-3,-1) // Should return "ef"; returns "abcdef" in IE 4 Bugs start See read more..

  • Page - 866

    limit delimiter delimiter limit delimiter String.split() Array.join() Example split() "1:2:3:4:5".split(":"); // Returns ["1","2","3","4","5"] "|a|b|c|".split("|"); // Returns ["", "a", "b", "c", ""] split() var words = sentence.split(' '); var words = sentence.split(/\s+/); limit read more..

  • Page - 867

    String.substr() deprecated extract a substring Synopsis string.substr(start, length) Arguments start length Returns string start length length Description substr() string string substr() String.substring() String.splice() Example var s = "abcdefg"; s.substr(2,2); // Returns "cd" s.substr(3); // Returns "defg" s.substr(-3,2); // Should return "ef"; returns "ab" in IE 4 read more..

  • Page - 868

    Arguments from string to Returns to from string from to string Description String.substring() string from to from to from to from to from to to from String.slice() String.substr() String.substring() See Also String.charAt() String.indexOf() String.lastIndexOf() String.slice() String.substr() String.toLocaleLowerCase() convert a string to lowercase Synopsis string.toLocaleLowerCase() Returns string toLowerCase() See Also read more..

  • Page - 869

    String.toLocaleUpperCase() convert a string to uppercase Synopsis string.toLocaleUpperCase() Returns string toUpperCase() See Also String.toLocaleLowerCase() String.toLowerCase() String.toUpperCase() String.toLowerCase() convert a string to lowercase Synopsis string.toLowerCase() Returns string String.toString() return the string Overrides Object.toString() Synopsis string.toString() Returns string Throws TypeError See Also String.valueOf() read more..

  • Page - 870

    String.toUpperCase() convert a string to uppercase Synopsis string.toUpperCase() Returns string String.trim() ECMAScript 5 strip leading and trailing whitespace Synopsis string.trim() Returns string See Also String.replace() String.valueOf() return the string Overrides Object.valueOf() Synopsis string.valueOf() Returns string Throws TypeError See Also String.toString() SyntaxError thrown to signal a syntax error Object Error read more..

  • Page - 871

    Arguments message message Returns message message SyntaxError() new new Properties message Error.mes- sage name Description eval() Function() RegExp() Error See Also Error Error.message Error.name TypeError thrown when a value is of the wrong type Object Error TypeError Constructor new TypeError() new TypeError(message) Arguments message message Returns message message TypeError Core JavaScript Reference | 853 Core read more..

  • Page - 872

    TypeError() new new Properties message Er- ror.message name Description null undefined new Error See Also Error Error.message Error.name undefined the undefined value Synopsis undefined Description undefined undefined undefined for/in delete undefined === == undefined null undefined 854 | Core JavaScript Reference read more..

  • Page - 873

    unescape() deprecated decode an escaped string Synopsis unescape(s) Arguments s Returns s Description unescape() escape() s % xx %u xxxx x \u00 xx \ u xxxx unescape() deco deURI() decodeURIComponent() unescape() escape() See Also decodeURI() decodeURIComponent() escape() String URIError thrown by URI encoding and decoding methods Object Error URIError Constructor new URIError() new URIError(message) Arguments message read more..

  • Page - 874

    Properties message Er- ror.message name Description decodeURI() decodeURIComponent() encodeURI() encodeURIComponent() Error See Also Error Error.message Error.name URIError 856 | Core JavaScript Reference read more..

  • Page - 875

    PART IV Client-Side JavaScript Reference Window Document Element Event XMLHttpRequest Storage Canvas File jQuery read more..

  • Page - 876

    ApplicationCache DOMException HTMLOptionsCollection Script ArrayBuffer DOMImplementation IFrame Select ArrayBufferView DOMSettableTokenList Image Storage Attr DOMTokenList ImageData StorageEvent Audio Element Input Style BeforeUnloadEvent ErrorEvent jQuery Table Blob Event Label TableCell BlobBuilder EventSource Link TableRow Button EventTarget Location TableSection Canvas FieldSet MediaElement Text CanvasGradient File MediaError TextArea read more..

  • Page - 877

    Client-Side JavaScript Reference ApplicationCache application cache management API EventTarget applicationCache Constants status unsigned short UNCACHED = 0 manifest unsigned short IDLE = 1 unsigned short CHECKING = 2 unsigned short DOWNLOADING = 3 unsigned short UPDATEREADY = 4 unsigned short OBSOLETE = 5 Properties readonly unsigned short status 859 read more..

  • Page - 878

    Methods void swapCache() status UPDATEREADY swapCache() Location.reload() void update() Event Handlers EventTarget ProgressEvent oncached onchecking ondownloading onerror onnoupdate onobsolete ApplicationCache 860 | Client-Side JavaScript Reference read more..

  • Page - 879

    onprogress ProgressEvent onupdateready ArrayBuffer a fixed-length sequence of bytes ArrayBufferView TypedArray Constructor new ArrayBuffer(unsigned long length) Properties readonly unsigned long byteLength ArrayBufferView common properties for types based on ArrayBuffers Array- Buffer TypedArray DataView Properties readonly ArrayBuffer buffer readonly unsigned long byteLength buffer readonly unsigned long byteOffset read more..

  • Page - 880

    Attr an element attribute attributes getAttributeNode() getAttributeNodeNS() Element.getAttribute() Element.setAttribute() Properties readonly string localName readonly string name readonly string namespaceURI null readonly string prefix null string value Audio an HTML <audio> element Node, Element, MediaElement <audio> MediaElement Constructor new Audio([string src]) <audio> preload src src BeforeUnloadEvent Event read more..

  • Page - 881

    Window.confirm() returnValue Event Window Properties string returnValue Blob an opaque chunk of data, such as file contents FileReader BlobBuilder XMLHttpRequest Properties readonly unsigned long size readonly string type Methods Blob slice(unsigned long start, unsigned long length, [string contentType]) length start contentType type BlobBuilder create new Blobs Blob ArrayBuffer append() getBlob() read more..

  • Page - 882

    Constructor new BlobBuilder() BlobBuilder() Methods void append(string text, [string endings]) text void append(Blob data) data void append(ArrayBuffer data) data Blob getBlob([string contentType]) contentType type type Button an HTML <button> Node, Element, FormControl <button> FormControl Element type FormControl form FormControl Properties <button> type string formAction formaction action read more..

  • Page - 883

    string formTarget formtarget target Canvas an HTML element for scripted drawing Node, Element width height toDataURL() getContext() CanvasRenderingContext2D Properties unsigned long height unsigned long width width height <canvas> width height style width height Methods object getContext(string contextId, [any args...]) args getContext("2d") string toDataURL([string type], [any args...]) toDataURL() read more..

  • Page - 884

    var image = document.createElement("img"); image.src = canvas.toDataURL(); document.body.appendChild(image); type type toDataURL() <canvas> drawImage() CanvasGradient a color gradient for use in a canvas strokeStyle fillStyle create LinearGradient() createRadialGradient() addColorStop() Methods void addColorStop(double offset, string color) addColorStop() color offset CanvasGradient 866 | Client-Side JavaScript read more..

  • Page - 885

    CanvasPattern an image-based pattern for use in a Canvas createPattern() strokeStyle fillStyle CanvasRenderingContext2D the object used for drawing on a canvas Canvas CanvasGradient CanvasPattern ImageData TextMetrics Creating and rendering paths moveTo() lineTo() rect() arc() arcTo() bezierCurveTo() quadratic CurveTo() stroke() fill() clip() fill() clip() CanvasRenderingContext2D Client-Side JavaScript Reference | 867 read more..

  • Page - 886

    closePath() isPointIn Path() fill() clip() Colors, gradients, and patterns fillStyle strokeStyle createLinearGradient() createRadialGradient() createPattern() Line width, line caps, and line joins lineWidth lineCap lineJoin Drawing rectangles strokeRect() fillRect() clearRect() Drawing images <img> Image() Image <canvas> <video> drawImage() CanvasRenderingContext2D 868 | Client-Side JavaScript Reference read more..

  • Page - 887

    Drawing Text fillText() strokeText() font textAlign textBaseline Coordinate space and transformations (0,0) x y width height <canvas> translate() scale() rotate() lineTo() Shadows shadowColor shadowOffsetX shadowOffsetY shadowBlur Compositing globalCompositeOperation result S D R α α Value Formula Meaning "copy" R = S Draws the source pixel, ignoring the destination pixel. "destination-atop" R=(1- d)S read more..

  • Page - 888

    Value Formula Meaning "destination-in" R = sD Multiply the destination pixel by the opacity of the source pixel, but ignore the color of the source. "destination-out" R = (1- s)D The destination pixel is made transparent when the source is opaque and is left unchanged when the source is transparent. The color of the source pixel is ignored. "destination-over" R read more..

  • Page - 889

    Properties readonly Canvas canvas any fillStyle string font font <canvas> double globalAlpha string globalCompositeOperation globalAlpha string lineCap lineCap Value Meaning "butt" This default value specifies that the line should have no cap. The end of the line is straight and is perpendicular to the direction of the line. The line is not extended beyond its endpoint. read more..

  • Page - 890

    string lineJoin lineJoin miterLimit double lineWidth double miterLimit lineJoin miterLimit miterLimit double shadowBlur string shadowColor double shadowOffsetX double shadowOffsetY any strokeStyle string textAlign fillText() strokeText() dir <canvas> CanvasRenderingContext2D 872 | Client-Side JavaScript Reference read more..

  • Page - 891

    string textBaseline fillText() strokeText() Methods void arc(double x, y,radius, startAngle,endAngle, [boolean anticlockwise]) true false void arcTo(double x1, y1, x2, y2, radius) x1 y1 x2 y2 radius c c.beginPath(); c.moveTo(150, 100); // Start in the middle of the top edge c.arcTo(200,100,200,200,40); // Draw top edge and rounded upper right corner read more..

  • Page - 892

    void bezierCurveTo(double cp1x, cp1y,cp2x, cp2y, x, y) bezierCurveTo() (x,y) (cpX1, cpY1) (cpX2, cpY2) (x,y) void clearRect(double x, y, width, height) clearRect() rect() void clip() save() restore() fill() clip() void closePath() closePath() moveTo() fill() clip() closePath() stroke() ImageData createImageData(ImageData imagedata) data ImageData createImageData(double w, double h) w h width height w read more..

  • Page - 893

    CanvasPattern createPattern(Element image, string repetition) image <img> <canvas> <video> repetition Value Meaning "repeat" Tile the image in both directions. This is the default. "repeat-x" Tile the image in the X dimension only. "repeat-y" Tile the image in the Y dimension only. "no-repeat" Do not tile the image; use it a single time read more..

  • Page - 894

    stroke() fill() fill() void fillRect(double x, y, width, height) fillRect() fillStyle rect() fillRect() void fillText(string text, double x, y, [double maxWidth]) fillText() text font fillStyle x y textAlign textBaseline textAlign left start end textAlign center textAlign textBaseline textBaseline textBaseline maxwidth text maxWidth ImageData getImageData(double sx, sy, sw, sh) ImageData width height sw sh read more..

  • Page - 895

    boolean isPointInPath(double x, y) isPointInPath() true false x canvas.width y canvas.height isPointInPath() width height style.width style.height <canvas> // An onclick handler for a canvas tag. Assumes a path is currently defined. function hittest(event) { var canvas = this; // Called in the context of the canvas var c = read more..

  • Page - 896

    void putImageData(ImageData imagedata, double dx, dy, [sx, sy, sw, sh]) putImageData() globalCompositeOperation globalAlpha dx dy data sx sy getImageData() putImageData() void quadraticCurveTo(double cpx, cpy, x, y) (x,y) (cpX, cpY) (x,y) bezierCurveTo() void rect(double x, y, w, h) (x,y) c.moveTo(x,y); c.lineTo(x+w, y); c.lineTo(x+w, y+h); c.lineTo(x, y+h); c.closePath(); void restore() save() void read more..

  • Page - 897

    void save() save() restore() canvas rotate() scale() translate() clip() void scale(double sx, double sy) scale() sx sy void setTransform(double a, b, c, d, e, f) translate() scale() rotate() x' a c e x = ax + cy + e y' = b d f × y = bx + dy + f 1 0 0 1 1 void stroke() stroke() strokeStyle lineWidth lineCap lineJoin miterLimit read more..

  • Page - 898

    void transform(double a, b, c, d, e, f) T a c e b d f 0 0 1 transform() T CTM' = CTM × T transform() transform(1,0,0,1,dx,dy) transform(sx, 0, 0, sy, 0, 0) x transform(cos(x),sin(x),-sin(x), cos(x), 0, 0) k transform(1,0,k,1,0,0) transform(1,k,0,1,0,0) void translate(double x, double y) translate() dx dy ClientRect an element bounding box get BoundingClientRect() Element Properties readonly read more..

  • Page - 899

    readonly float width right-left CloseEvent specifies whether a WebSocket closed cleanly Event WebSocket Properties readonly boolean wasClean true false Comment an HTML or XML comment Node <!-- --> data nodeValue Document.createComment() Properties string data readonly unsigned long length Methods void appendData(string data) void deleteData(unsigned long offset, unsigned long count) void insertData(unsigned long read more..

  • Page - 900

    Console debugging output console console.log() console ConsoleCommandLine Methods void assert(any expression, string message) message expression false null undefined 0 void count([string title]) title void debug(any message...) console.log() void dir(any object) object void dirxml(any node) node void error(any message...) console.log() void group(any message...) message log() groupEnd() void read more..

  • Page - 901

    void groupEnd() group() groupCollapsed() void info(any message...) console.log() void log(string format, any message...) format printf() message format message void profile([string title]) title void profileEnd() void time(string name) name void timeEnd(string name) name time() void trace() void warn(any message...) console.log() ConsoleCommandLine global utilities for the console window read more..

  • Page - 902

    Properties readonly Element $0 readonly Element $1 $0 Methods void cd(Window frame) cd() frame void clear() void dir(object o) o Console.dir() void dirxml(Element elt) elt Console.dirxml() Element $(string id) document.getElementById() NodeList $$(string selector) selector document.querySelectorAll() void inspect(any object, [string tabname]) object string[] keys(any object) object void read more..

  • Page - 903

    void unmonitorEvents(Element object, [string type]) type object any[] values(any object) object CSS2Properties see CSSStyleDeclaration CSSRule a rule in a CSS stylesheet Description CSSStyleSheet selectorText style CSSStyleDeclaration selectorText style Constants unsigned short STYLE_RULE = 1 unsigned short IMPORT_RULE = 3 unsigned short MEDIA_RULE = 4 unsigned short FONT_FACE_RULE = 5 unsigned read more..

  • Page - 904

    readonly CSSStyleSheet parentStyleSheet string selectorText type STYLE_RULE readonly CSSStyleDeclaration style type STYLE_RULE selectorText style readonly unsigned short type CSSStyleDeclaration a set of CSS attributes and their values style style Window.getComputedStyle() fontFamily float cssFloat Properties string cssText readonly unsigned long length CSSStyleDeclaration 886 | Client-Side JavaScript Reference read more..

  • Page - 905

    CSSStyleSheet a CSS stylesheet CSSRule styleSheets[] sheet <style> <link> rules[] cssRules[] addRule() removeRule() insertRule() deleteRule() Properties readonly CSSRule[] cssRules rules boolean disabled true false readonly string href null readonly string media appendMedium() deleteMedium() readonly Node ownerNode null Link Style readonly CSSRule ownerRule null readonly CSSStyleSheet parentStyleSheet null readonly read more..

  • Page - 906

    Methods void deleteRule(unsigned long index) index cssRules removeRule() unsigned long insertRule(string rule, unsigned long index) rule index cssRules addRule() DataTransfer a transfer of data via drag-and-drop dataTransfer Event items Properties string dropEffect string effectAllowed DataTransfer 888 | Client-Side JavaScript Reference read more..

  • Page - 907

    readonly File[] files readonly string[] types setData() contains() indexOf() Methods void addElement(Element element) element void clearData([string format]) format setData() string getData(string format) format format void setData(string format, string data) data format void setDragImage(Element image, long x, long y) image <img> x y DataView read and write values from an read more..

  • Page - 908

    TypedArray Constructor new DataView(ArrayBuffer buffer, [unsigned long byteOffset], [unsigned long byteLength]) buffer buffer byteOffset byteLength byte Offset Methods littleEndian false true float getFloat32(unsigned long byteOffset, [boolean littleEndian]) byteOffset double getFloat64(unsigned long byteOffset, [boolean littleEndian]) byteOffset short getInt16(unsigned long read more..

  • Page - 909

    void setFloat64(unsigned long byteOffset, double value, [boolean littleEndian]) value byteOffset void setInt16(unsigned long byteOffset, short value, [boolean littleEndian]) value byteOffset void setInt32(unsigned long byteOffset, long value, [boolean littleEndian]) value byteOffset void setInt8(unsigned long byteOffset, byte value) value byteOffset void setUint16(unsigned read more..

  • Page - 910

    responseXML XMLHttpRequest Properties name <iframe> <form> <img> <iframe> <iframe> readonly Element activeElement Element body <body> <frameset> readonly string characterSet string charset characterSet readonly string compatMode string cookie readonly string defaultCharset readonly Window defaultView Document 892 | Client-Side JavaScript Reference read more..

  • Page - 911

    string designMode contenteditable string dir dir <html> documentElement.dir readonly DocumentType doctype <!DOCTYPE> readonly Element documentElement <html> childNodes[] body string domain null readonly HTMLCollection embeds <embed> readonly HTMLCollection forms readonly Element head <head> readonly HTMLCollection images readonly DOMImplementation implementation readonly string lastModified readonly read more..

  • Page - 912

    readonly string readyState readonly string referrer null referer readonly HTMLCollection scripts <script> readonly CSSStyleSheet[] styleSheets <link> <style> string title <title> readonly string URL location.href location.hash location URL Document.URL Window.URL Methods Node adoptNode(Node node) node ownerDocument importNode() void close() open() Comment createComment(string data) DocumentFragment read more..

  • Page - 913

    Element createElement(string localName) Element createElementNS(string namespace, string qualifiedName) Event createEvent(string eventInterface) initEvent() initUIEvent() initMouseEvent() Event.initEvent() dispatchE vent() EventTarget isTrusted false ProcessingInstruction createProcessingInstruction(string target, string data) Text createTextNode(string data) Element elementFromPoint(float x, float y) x y read more..

  • Page - 914

    Element getElementById(string elementId) id elementId null id elementId NodeList getElementsByClassName(string classNames) class classNames classNames Element NodeList getElementsByName(string elementName) name elementName length NodeList getElementsByTagName(string qualifiedName) NodeList getElementsByTagNameNS(string namespace, string localName) getElementsByTagName() boolean hasFocus() Node importNode(Node node, read more..

  • Page - 915

    Window open(string url, string name, string features, [boolean replace]) open() open() Window Document open([string type], [string replace]) open() write() writeln() close() type replace boolean queryCommandEnabled(string commandId) true commandId execCommand() boolean queryCommandIndeterm(string commandId) true commandId queryCommandState() boolean queryCommandState(string commandId) commandId true read more..

  • Page - 916

    NodeList querySelectorAll(string selectors) selectors getElementsByTagName() void write(string text...) <script> open() void writeln(string text...) HTMLDocument.write() <pre> Events Element EventTarget ready State onreadystatechange EventTarget onDOMContentLoaded DocumentFragment adjacent nodes and their subtrees Node parentNode null Document.createDocumentFragment() querySelector() querySelectorAll() DocumentFragment 898 read more..

  • Page - 917

    Methods Element querySelector(string selectors) Document.querySelector() NodeList querySelectorAll(string selectors) Document.querySelectorAll() DocumentType the <!DOCTYPE> declaration of a document Node <!DOCTYPE> doctype DOMImplementa tion.createDocument() DOMImplementa tion.createDocumentType() Properties readonly string name <!DOCTYPE> readonly string publicId readonly string systemId DOMException an exception thrown read more..

  • Page - 918

    Constants unsigned short INDEX_SIZE_ERR = 1 unsigned short HIERARCHY_REQUEST_ERR = 3 unsigned short WRONG_DOCUMENT_ERR = 4 unsigned short INVALID_CHARACTER_ERR = 5 unsigned short NO_MODIFICATION_ALLOWED_ERR = 7 unsigned short NOT_FOUND_ERR = 8 unsigned short NOT_SUPPORTED_ERR = 9 unsigned short INVALID_STATE_ERR = 11 unsigned short SYNTAX_ERR = 12 unsigned short INVALID_MODIFICATION_ERR = read more..

  • Page - 919

    Methods Document createDocument(string namespace, string qualifiedName, DocumentType doctype) qualifiedName documentElement qualifiedName doctype null ownerDocument DocumentType createDocumentType(string qualifiedName, publicId, systemId) <!DOCTYPE> createDocument() Document createHTMLDocument(string title) documentElement <html> <head> <body> <head> <title> title DOMSettableTokenList a token read more..

  • Page - 920

    DOMTokenList a set of space-separated tokens className Element length contains() add() remove() toggle() classList Element DOMSettableTokenList Properties readonly unsigned long length Methods void add(string token) token boolean contains(string token) true token false string item(unsigned long index) index null index void remove(string token) token boolean toggle(string token) token Element a document read more..

  • Page - 921

    docu mentElement <html> head body <head> <body> id Document.getElementById() getElementsByTagName() getElementsByClassName() querySelectorAll() Document.createElement() EventTarget Properties readonly Attr[] attributes attributes[] readonly unsigned long childElementCount readonly HTMLCollection children readonly DOMTokenList classList DOMTokenList string className class class className class class readonly long clientHeight read more..

  • Page - 922

    readonly long clientLeft readonly long clientTop CSSStyleDeclaration currentStyle Window.getComputedStyle() readonly object dataset dataset data-x dataset x dataset.x getAttribute("data-x") dataset delete for/in readonly Element firstElementChild firstChild Node string id id id string innerHTML readonly boolean isContentEditable true false contenteditable designMode string lang lang Element 904 | Client-Side JavaScript read more..

  • Page - 923

    readonly Element lastElementChild lastChild Node readonly string localName tagName prefix readonly string namespaceURI null readonly Element nextElementSibling nextSibling Node readonly long offsetHeight readonly long offsetWidth readonly long offsetLeft readonly long offsetTop offsetParent readonly Element offsetParent offsetLeft offsetTop offsetParent <body> offsetParent <td> <th> <table> offsetParent string read more..

  • Page - 924

    offsetHeight offsetWidth long scrollLeft long scrollTop overflow auto <html> Document.documentElement <iframe> readonly CSSStyleDeclaration style style CSSStyleDeclaration readonly string tagName <p> tagName nodeName string title title Methods void blur() body Document void click() void focus() string getAttribute(string qualifiedName) getAttribute() null Element 906 | Client-Side JavaScript Reference read more..

  • Page - 925

    getAttributeNS() string getAttributeNS(string namespace, string localName) getAttribute() ClientRect getBoundingClientRect() ClientRect ClientRect[] getClientRects() NodeList getElementsByClassName(string classNames) class classNames classNames Document NodeList getElementsByTagName(string qualifiedName) getElementsByTagName() NodeList getElementsByTagNameNS(string namespace, string localName) getElementsByTagName() boolean read more..

  • Page - 926

    void insertAdjacentHTML(string position, string text) text position position Position Meaning beforebegin Insert the text before the opening tag afterend Insert the text after the closing tag afterbegin Insert the text right after the opening tag beforeend Insert the text right before the closing tag Element querySelector(string selectors) selectors NodeList querySelectorAll(string selectors) read more..

  • Page - 927

    void setAttributeNS(string namespace, string qualifiedName, string value) setAttribute() Event Handlers EventTarget <body> <body> Window <audio> <video> MediaElement FormControl Event Handler Invoked When... onabort resource loading canceled at user’s request onblur* element loses input focus onchange user changes form control content or state (fired for complete edits, not read more..

  • Page - 928

    Event Handler Invoked When... onkeydown the user presses a key onkeypress a keypress generates a printable character onkeyup the user releases a key onload* resource loading (e.g., for <img>) has completed onmousedown the user presses a mouse button onmousemove the user moves the mouse onmouseout the mouse leaves an element onmouseover the mouse enters an element onmouseup the user releases read more..

  • Page - 929

    Attribute Description accessKey keyboard shortcut class CSS class: see the className and classList properties above. contentEditable Whether element content is editable. contextMenu The ID of a <menu> element to display as a context menu. Supported only by IE at the time of this writing. dir Text direction: “ltr” or “rtl”. draggable A boolean attribute set on elements that are drag sources read more..

  • Page - 930

    Element Attributes <base> href, target <blockquote> cite <body> onafterprint, onbeforeprint, onbeforeunload, onblur, onerror, onfocus, onhashchange, onload, onmessage, onoffline, ononline, onpagehide, onpageshow, onpopstate, onredo, onresize, onscroll, onstorage, onundo, onunload <button> autofocus, disabled, form, formaction, formenctype, formmethod, formnovalidate, formtarget, name, type, value read more..

  • Page - 931

    Element Attributes <param> name, value <progress> value, max, form <q> cite <script> src, async, defer, type, charset <select> autofocus, disabled, form, multiple, name, required, size <source> src, type, media <style> media, type, scoped <table> summary <td> colspan, rowspan, headers <textarea> autofocus, cols, disabled, form, maxlength, name, placeholder, read more..

  • Page - 932

    Event details for standard events, IE events and jQuery events BeforeUnloadEvent CloseEvent ErrorEvent HashChangeEvent MessageEvent PageTransitionEvent PopStateEvent ProgressEvent StorageEvent MessageEvent Constants eventPhase unsigned short CAPTURING_PHASE = 1 unsigned short AT_TARGET = 2 Event 914 | Client-Side JavaScript Reference read more..

  • Page - 933

    unsigned short BUBBLING_PHASE = 3 Properties readonly boolean altKey readonly boolean bubbles* true stopPropagation() false readonly unsigned short button button button which readonly boolean cancelable true preventDefault() false boolean cancelBubble true stopPropagation() readonly integer charCode String.fromCharCode() keyCode keyCode charCode Event Client-Side JavaScript Reference | 915 Client-Side JavaScript Reference read more..

  • Page - 934

    readonly long clientX readonly long clientY clientY pageX pageY readonly boolean ctrlKey readonly EventTarget currentTarget target readonly DataTransfer dataTransfer DataTransfer clientX clientY DataTransfer readonly boolean defaultPrevented true defaultPrevented() false isDefaultPrevented() readonly long detail readonly unsigned short eventPhase readonly boolean isTrusted true false readonly Element fromElement fromElement read more..

  • Page - 935

    readonly integer keyCode readonly boolean metaKey readonly integer offsetX, offsetY srcElement readonly integer pageX, pageY clientX clientY readonly EventTarget relatedTarget target fromElement toElement boolean returnValue false preventDefault() readonly long screenX, screenY readonly boolean shiftKey readonly EventTarget srcElement target Event Client-Side JavaScript Reference | 917 Client-Side JavaScript Reference read more..

  • Page - 936

    readonly EventTarget target EventTarget srcElement readonly unsigned long timeStamp Date() Date.getTime() Element toElement toElement relatedTarget readonly string type* readonly Window view readonly integer wheelDelta readonly integer wheelDeltaX readonly integer wheelDeltaY wheelDeltaY wheelDelta readonly integer which button keyCode Methods Event 918 | Client-Side JavaScript Reference read more..

  • Page - 937

    void initEvent(string type, boolean bubbles, boolean cancelable) type bubbles cancelable createEvent() Document EventTarget dispatchEvent() type bubbles cancelable createEvent() initMouseEvent() void preventDefault() returnValue false void stopImmediatePropagation() stopPropagation() void stopPropagation() cancelBubble stopPropagation() Proposed Properties readonly unsigned short buttons button readonly string char read more..

  • Page - 938

    DOM_DELTA_PIXEL DOM_DELTA_LINE DOM_DELTA_PAGE readonly long deltaX, deltaY, deltaZ readonly unsigned long inputMethod DOM_INPUT_METHOD_UNKNOWN DOM_INPUT_METHOD_KEYBOARD DOM_INPUT_METHOD_PASTE DOM_INPUT_METHOD_DROP DOM_INPUT_METHOD_IME DOM_INPUT_METHOD_OPTION DOM_INPUT_METHOD_HANDWRITING DOM_INPUT_METHOD_VOICE DOM_INPUT_METHOD_MULTIMODAL DOM_INPUT_METHOD_SCRIPT readonly string key char readonly string locale readonly unsigned long location read more..

  • Page - 939

    EventSource a Comet connection to an HTTP server EventTarget EventSource() EventSource Constructor new EventSource(string url) EventSource url url Constants unsigned short CONNECTING = 0 unsigned short OPEN = 1 unsigned short CLOSED = 2 close() Properties readonly unsigned short readyState readonly string url Methods void close() Event Handlers EventTarget EventSource Client-Side JavaScript Reference | read more..

  • Page - 940

    onerror Event onmessage data onopen Event EventTarget an object that receives events Methods void addEventListener(string type, function listener, [boolean useCapture]) listener type type useCapture true false boolean dispatchEvent(Event event) event document.createEvent() initEvent() Event isTrusted false Event void removeEventListener(string type, function listener, [boolean useCapture]) listener read more..

  • Page - 941

    Internet Explorer Methods addEventListener() removeEventListener() void attachEvent(string type, function listener) listener type type void detachEvent(string type, function listener) attachEvent() FieldSet a <fieldset> in an HTML form Node, Element, FormControl <fieldset> <form> FormControl Properties boolean disabled true readonly HTMLFormControlsCollection elements <fieldset> File a file in read more..

  • Page - 942

    readonly string name FileError error while reading a file FileReader FileReaderSync error Constants unsigned short NOT_FOUND_ERR = 1 unsigned short SECURITY_ERR = 2 unsigned short ABORT_ERR = 3 unsigned short NOT_READABLE_ERR = 4 unsigned short ENCODING_ERR = 5 readAsDataURL() data:// Properties readonly unsigned short code FileReader asynchronously read a File or Blob EventTarget FileReader() read more..

  • Page - 943

    onload result onerror error FileReaderSync Constructor new FileReader() FileReader() Constants readyState unsigned short EMPTY = 0 unsigned short LOADING = 1 unsigned short DONE = 2 Properties readonly FileError error FileError readonly unsigned short readyState readonly any result readyState null Methods void abort() readyState DONE result null error FileError code FileError.ABORT_ERR FileReader Client-Side read more..

  • Page - 944

    void readAsArrayBuffer(Blob blob) blob result void readAsBinaryString(Blob blob) blob result String.charCodeAt() void readAsDataURL(Blob blob) blob data:// result void readAsText(Blob blob, [string encoding]) blob encoding result Event Handlers EventTarget onabort abort() onerror error onload result onloadend FileReader 926 | Client-Side JavaScript Reference read more..

  • Page - 945

    onloadstart onprogress result FileReaderSync synchronously read a File or Blob FileReader Worker FileReaderSync() Constructor new FileReaderSync() FileReaderSync() Methods ArrayBuffer readAsArrayBuffer(Blob blob) blob string readAsBinaryString(Blob blob) blob String.fromChar- Code() string readAsDataURL(Blob blob) blob type blob data:// string readAsText(Blob blob, [string encoding]) blob encoding Form a read more..

  • Page - 946

    document.forms[] Form.elements name f f.phone FormControl FieldSet Input Label Select TextArea Properties string acceptCharset string action string autocomplete readonly HTMLFormControlsCollection elements string enctype readonly long length elements f n f[n] f.elements[n] string method action string name name Form 928 | Client-Side JavaScript Reference read more..

  • Page - 947

    boolean noValidate true novalidate string target Methods boolean checkValidity() true false void dispatchFormChange() void dispatchFormInput() void reset() void submit() Event Handlers onreset false onsubmit false FormControl common features of all form controls <input> <button> <select> <textarea> FormControl Client-Side JavaScript Reference | 929 Client-Side JavaScript Reference read more..

  • Page - 948

    Form Input Select TextArea <fieldset> <output> Properties boolean autofocus true boolean disabled true readonly Form form null <form> form <form> readonly NodeList labels Label string name name string type <input> type type <input> <button> <select> textarea multiple <fieldset> type <output> readonly string validationMessage readonly FormValidity validity FormControl 930 | read more..

  • Page - 949

    string value value value textContent Node readonly boolean willValidate true false Event Handlers Event Handler Invoked when onformchange When a change event is fired on any control in the form, the form broadcasts a nonbubbling formchange event to all of its controls. Controls can use this handler property to detect changes to their sibling controls. onforminput When an input event is read more..

  • Page - 950

    Constructor new FormData() Methods void append(string name, any value) name value value Blob File FormValidity the validity of a form control validity FormControl FormValidity valid false true Properties readonly boolean customError FormControl.setCustomValidity() readonly boolean patternMismatch pattern readonly boolean rangeOverflow readonly boolean rangeUnderflow readonly boolean stepMismatch step readonly boolean read more..

  • Page - 951

    Geocoordinates a geographical position Properties readonly double accuracy latitude longitude readonly double altitude null readonly double altitudeAccuracy altitude altitude null altitudeAccuracy null readonly double heading null speed heading NaN readonly double latitude readonly double longitude readonly double speed null heading Geolocation obtain the user’s latitude and longitude Naviga- tor navigator.geolocation read more..

  • Page - 952

    error long watchPosition(function success, [function error], [object options]) getCurrentPosition() success clearWatch() Options options getCurrentPosition() watchPosition() boolean enableHighAccuracy false true long maximumAge successCallback getCurrentPosition() watchPosition() long timeout Infinity timeout errorCallback timeout GeolocationError an error while querying the user’s location Constants code unsigned short read more..

  • Page - 953

    unsigned short TIMEOUT = 3 timeout Geolocation Properties readonly unsigned short code readonly string message Geoposition a timestamped position report Geocoordinates Properties readonly Geocoordinates coords readonly unsigned long timestamp Date HashChangeEvent event object for hashchange events Event hash Location location.hash Properties readonly string newURL location.href readonly string oldURL location.href read more..

  • Page - 954

    History the browsing history of a Window Properties readonly long length Methods void back() back() history.go(-1); void forward() forward() history.go(1); void go([long delta]) History.go() history.go(-1) history.back() void pushState(any data, string title, [string url]) data title url PopStateEvent data state title url url url History 936 | Client-Side JavaScript Reference read more..

  • Page - 955

    void replaceState(any data, string title, [string url]) pushState() data title url HTMLCollection an element collection accessible by name or number Element name id forms image item() namedItem() document.images[0] // A numbered element of an HTMLCollection document.forms.address // A named element of an HTMLCollection Properties readonly unsigned long length Methods Element item(unsigned read more..

  • Page - 956

    HTMLFormControlsCollection a array-like object of form controls HTMLCollection name value value value HTMLOptionsCollection a collection of Option elements HTMLCollection Option Select namedItem() length Properties unsigned long length length length <option/> long selectedIndex Methods void add(Element option, [any before]) option <option> <optgroup> before before before before option read more..

  • Page - 957

    Element item(unsigned long index) index null index object namedItem(string name) null name void remove(long index) <option> index IFrame an HTML <iframe> Node, Element <iframe> <iframe> getElementById() <iframe> frames <iframe> <iframe> Properties readonly Document contentDocument <iframe> <iframe> readonly Window contentWindow <iframe> frameElement string height read more..

  • Page - 958

    sandbox <iframe> sandbox <iframe> sandbox sandbox boolean seamless seamless true <iframe> <iframe> seamless string src src <iframe> string srcdoc srcdoc <iframe> srcdoc string width <iframe> width Image an <img> in an HTML document Node, Element <img> document.images[] src <img> document.createElement() Image() src Image 940 | Client-Side JavaScript Reference read more..

  • Page - 959

    Constructor new Image([unsigned long width, unsigned long height]) docu ment.createElement() Image() width height width height <img> Properties alt usemap ismap readonly boolean complete true src false unsigned long height readonly unsigned long naturalHeight readonly unsigned long naturalWidth string src unsigned long width ImageData an array of pixel data from a <canvas> createImageData() read more..

  • Page - 960

    var blue = image.data[offset+2]; var alpha = image.data[offset+3]; data[] i i.data.length i.width * i.height * 4 Properties readonly byte[] data readonly unsigned long height readonly unsigned long width Input an HTML <input> element Node, Element, FormControl <input> type <input> type value name form FormControl Properties Element FormControl string accept type accept string autocomplete read more..

  • Page - 961

    boolean defaultChecked checked checked string defaultValue value readonly File[] files type File string formAction* action formaction string formEnctype* enctype formenctype string formMethod* method formmethod boolean formNoValidate* noValidate formnovalidate string formTarget* target formtarget boolean indeterminate readonly Element list* <datalist> <option> string max* long maxLength type size maxlength string min* read more..

  • Page - 962

    boolean multiple* true type multiple string pattern* pattern string placeholder placeholder boolean readOnly true readonly boolean required* true required readonly Option selectedOption* list multiple false list unsigned long selectionEnd setSelectionRange() unsigned long selectionStart <textarea> setSe lectionRange() unsigned long size size maxLength string step* step Date valueAsDate* value FormControl double read more..

  • Page - 963

    Methods Element FormControl void select() void setSelectionRange(unsigned long start, unsigned long end) start end void stepDown([long n])* step n void stepUp([long n])* step n jQuery jQuery 1.4 the jQuery library Description sel idx elt elts f jQuery Factory Function jQuery jQuery() $ jQuery $() jQuery() jQuery Client-Side JavaScript Reference | 945 Client-Side JavaScript Reference read more..

  • Page - 964

    jQuery(sel [, context=document]) context sel jQuery(elts) elts jQuery(html, [props]) html html props jQuery(f) f f jQuery Selector Grammar * tagname .classname #id A B A > B A + B A ~ B [attr] [attr=val] [attr!=val] [attr^=val] [attr$=val] [attr*=val] [attr~=val] [attr|=val] :button read more..

  • Page - 965

    :animated :disabled :hidden :visible :checked :enabled :selected :eq(n) :first :last :nth(n) :even :gt(n) :lt(n) :odd :first-child :nth-child(n) :last-child :nth-child(even) read more..

  • Page - 966

    length map(f(idx,elt)):jQuery f null undefined selector $() size():int length toArray():array jQuery Selection Methods add(sel, [context]) add(elts) add(html) add() $() andSelf() children([sel]) closest(sel, [context]) sel context context context contents() end() eq(idx) jQuery 948 | Client-Side JavaScript Reference read more..

  • Page - 967

    filter(sel) filter(elts) filter(f(idx):boolean) sel elts f true find(sel) sel first() has(sel) has(elt) sel elt last() next([sel]) sel nextAll([sel]) sel nextUntil(sel) sel not(sel) not(elts) not(f(idx):boolean) filter() sel elts f true elts f offsetParent() parent([sel]) sel parents([sel]) sel jQuery Client-Side JavaScript Reference | 949 Client-Side JavaScript Reference read more..

  • Page - 968

    parentsUntil(sel) sel prev([sel]) sel prevAll([sel]) sel prevUntil(sel) sel pushStack(elts) end() elts siblings([sel]) sel slice(startidx, [endidx]) startidx endidx endidx length jQuery Element Methods current addClass(names) addClass(f(idx,current):names) class f attr(name):value attr(name, value) attr(name, f(idx,current):value) attr(obj) value f jQuery 950 | Client-Side JavaScript Reference read more..

  • Page - 969

    css(name):value css(name, value) css(name, f(idx,current):value) css(obj) attr() data():obj data(key):value data(key, value) data(obj) value hasClass(name):boolean true name class height():int height(h) height(f(idx,current):int) h f innerHeight():int innerWidth():int offset():coords offset(coords) offset(f(idx,current):coords) coords f top left offsetParent():jQuery outerHeight([margins=false]):int margins true outerWidth([margins=false]):int margins read more..

  • Page - 970

    position():coords top left removeAttr(name) removeClass(names) removeClass(f(idx,current):names) class removeData([key]) scrollLeft():int scrollLeft(int) scrollTop():int scrollTop(int) toggleClass(names, [add]) toggleClass(f(idx,current):names, [add]) class f add true false val():value val(value) val(f(idx,current)):value value f width():int width(w) width(f(idx,current):int) w f jQuery 952 | Client-Side JavaScript Reference read more..

  • Page - 971

    jQuery Insertion and Deletion Methods content target after(content) after(f(idx):content) content f append(content) append(f(idx,html):content) content f appendTo(target):jQuery target before(content) before(f(idx):content) after() clone([data=false]):jQuery data true detach([sel]) remove() empty() html():string html(htmlText) html(f(idx,current):htmlText) htmlText f insertAfter(target):jQuery target insertBefore(target):jQuery target jQuery Client-Side read more..

  • Page - 972

    prepend(content) prepend(f(idx,html):content) append() prependTo(target):jQuery appendTo() remove([sel]) sel replaceAll(target) target replaceWith(content) replaceWith(f(idx,html):content) content f text():string text(plainText) text(f(idx,current):plainText) plainText f unwrap() wrap(wrapper) wrap(f(idx):wrapper) wrapper wrapper wrapAll(wrapper) wrapper wrapper wrapper jQuery 954 | Client-Side JavaScript Reference read more..

  • Page - 973

    wrapInner(wrapper) wrapInner(f(idx):wrapper) wrap() wrapper f jQuery Event Methods () (f(event)) f ajaxComplete() blur() focusin() mousedown() mouseup() ajaxError() change() focusout() mouseenter() resize() ajaxSend() click() keydown() mouseleave() scroll() ajaxStart() dblclick() keypress() mousemove() select() ajaxStop() read more..

  • Page - 974

    one(type, [data], f(event)) one(events) bind() ready(f()) f $(f) toggle(f1(event), f2(event),...) trigger(type, [params]) trigger(event) type params params event type triggerHandler(type, [params]) trigger() unbind([type],[f(event)]) type f type type undelegate() undelegate(sel, type, [f(event)]) type sel f jQuery Effects and Animation Methods complete duration easing queue specialEasing read more..

  • Page - 975

    animate(props, opts) props opts animate(props, [duration], [easing], [f()]) props duration easing f clearQueue([qname="fx"]) delay(duration, [qname="fx"]) dequeue([qname="fx"]) fadeIn([duration=400],[f()]) fadeOut([duration=400],[f()]) duration f fadeTo(duration, opacity, [f()]) duration f hide() hide(duration, [f()]) duration f slideDown([duration=400],[f()]) slideUp([duration=400],[f()]) slideToggle([duration=400],[f()]) read more..

  • Page - 976

    toggle([show]) toggle(duration, [f()]) show true show() show false hide() show duration f queue([qname="fx"]):array queue([qname="fx"], f(next)) queue([qname="fx"], newq) f newq jQuery Ajax Functions success error notmodified timeout parsererror text html xml script json read more..

  • Page - 977

    jQuery.getJSON(url, [data], [f(object,status)]):XMLHttpRequest url data f jQuery.getScript(url, [f(text,status)]):XMLHttpRequest url f f jQuery.get(url, [data], [f(data,status,xhr)], [type]):XMLHttpRequest url data type Content-Type f jQuery.get() jQuery.post(url, [data], [f(data,status,xhr)], [type]):XMLHttpRequest jQuery.get() jQuery.param(o, [old=false]):string o www-form-urlencoded data true jQuery.parseJSON(text):object text load(url, [data], read more..

  • Page - 978

    jQuery Utility Functions jQuery.boxModel jQuery.support.boxModel jQuery.browser msie mozilla webkit opera version jQuery.contains(a,b):boolean a b jQuery.data(elt):data jQuery.data(elt, key):value jQuery.data(elt, data) jQuery.data(elt, key, value) data() jQuery.dequeue(elt, [qname="fx"]) $(elt).dequeue(qname) jQuery.each(o, f(name,value)):o jQuery.each(a, f(index,value)):a f f f f false jQuery.error(msg) msg jQuery.error = alert read more..

  • Page - 979

    jQuery.grep(a, f(elt,idx):boolean, [invert=false]):array a f true invert true f false jQuery.inArray(v, a):integer a v jQuery.isArray(x):boolean true x jQuery.isEmptyObject(x):boolean true x jQuery.isFunction(x):boolean true x jQuery.isPlainObject(x):boolean true x jQuery.isXMLDoc(x):true x jQuery.makeArray(a):array a jQuery.map(a, f(elt, idx)):array f a null jQuery.merge(a,b):array b a a jQuery.noConflict([radical=false]) $ jQuery radical true read more..

  • Page - 980

    jQuery.support jQuery.support.boxModel jQuery.trim(s):string s KeyEvent see Event Label a <label> for a form control Node, Element <label> Properties readonly Element control FormControl htmlFor <label> readonly Form form form string htmlFor for for FormControl Link an HTML hyperlink Node, Element <a> <area> <link> <a> <area> <link> <head> <a> <area> <link> read more..

  • Page - 981

    <a> href Properties hreflang media ping rel sizes target type host pathname href <a> <area> <link> sheet disabled relList <link> boolean disabled <link> string hash href string host href string hostname href string href href <a> <area> string pathname href string port href string protocol href readonly DOMTokenList relList classList rel <link> string search href readonly read more..

  • Page - 982

    string title title <link> rel Location represents and controls browser location location href href location location.href href search hash hash Properties http://www.oreilly.com:1234/catalog/search.html?q=JavaScript&m=10#results string hash string host string hostname string href Location 964 | Client-Side JavaScript Reference read more..

  • Page - 983

    string pathname string port string protocol string search Methods void assign(string url) url href url void reload() void replace(string url) url MediaElement a media player element Node, Element <audio> <video> Audio Video Constants NETWORK networkState HAVE readyState unsigned short NETWORK_EMPTY = 0 src MediaElement Client-Side JavaScript Reference | 965 Client-Side JavaScript Reference read more..

  • Page - 984

    unsigned short NETWORK_IDLE = 1 preload unsigned short NETWORK_LOADING = 2 unsigned short NETWORK_NO_SOURCE = 3 unsigned short HAVE_NOTHING = 0 unsigned short HAVE_METADATA = 1 duration currentTime currentTime unsigned short HAVE_CURRENT_DATA = 2 currentTime unsigned short HAVE_FUTURE_DATA = 3 unsigned short HAVE_ENOUGH_DATA = 4 Properties boolean autoplay true autoplay readonly TimeRanges read more..

  • Page - 985

    double currentTime double defaultPlaybackRate readonly double duration NaN Infinity readonly boolean ended readonly MediaError error null code readonly double initialTime boolean loop true loop boolean muted <video> audio="muted" readonly unsigned short networkState readonly boolean paused true double playbackRate readonly TimeRanges played string preload MediaElement Client-Side JavaScript Reference | 967 read more..

  • Page - 986

    preload readonly unsigned short readyState HAVE_ readonly TimeRanges seekable currentTime duration readonly boolean seeking true currentTime true seeking true string src src currentSrc readonly Date startOffsetTime double volume muted Event Handlers <audio> <video> addEventListener() EventTarget Event Event Handler Invoked When... onabort The element has stopped loading data, typically at the user’s read more..

  • Page - 987

    Event Handler Invoked When... onemptied An error or abort has caused the networkState to return to NETWORK_EMPTY. onended Playback has stopped because the end of the media has been reached. onerror A network or other error prevented media data from being loaded. error.code is a value other than MEDIA_ERR_ABORTED (see MediaError). onloadeddata Data for the current playback position has read more..

  • Page - 988

    void pause() void play() MediaError an <audio> or <video> error <audio> <video> error code Constants unsigned short MEDIA_ERR_ABORTED = 1 unsigned short MEDIA_ERR_NETWORK = 2 unsigned short MEDIA_ERR_DECODE = 3 unsigned short MEDIA_ERR_SRC_NOT_SUPPORTED = 4 src Properties readonly unsigned short code MessageChannel a pair of connected MessagePorts postMessage() Window Worker ports read more..

  • Page - 989

    Constructor new MessageChannel() Properties readonly MessagePort port1 readonly MessagePort port2 MessageEvent a message from another execution context Event Window Worker WebSocket EventSource MessagePort onmessage data Properties readonly any data data readonly string lastEventId lastEventId readonly string origin readonly MessagePort[] ports MessagePort postMessage() MessageEvent Client-Side JavaScript Reference | 971 read more..

  • Page - 990

    readonly Window source MessagePort pass asynchronous messages EventTarget MessageChannel postMessage() postMessage() Methods void close() postMessage() void postMessage(any message, [MessagePort[] ports]) message ports message void start() message EventTarget addEventListener() onmessage start() Event Handlers onmessage start() MessagePort 972 | Client-Side JavaScript Reference read more..

  • Page - 991

    Meter a graphical meter or gauge Node, Element <meter> <meter> Properties readonly Form form form double high high max readonly NodeList labels double low min low double max <meter> double min <meter> double optimum double value <meter> MouseEvent see Event MouseEvent Client-Side JavaScript Reference | 973 Client-Side JavaScript Reference read more..

  • Page - 992

    Navigator information about the web browser navigator Properties readonly string appName readonly string appVersion readonly Geolocation geolocation Geolocation readonly boolean onLine false true Window readonly string platform readonly string userAgent Mozilla/5.0 (X11; U; Linux i686; en-US) AppleWebKit/534.16 (KHTML, like Gecko) Chrome/10.0.648.45 Safari/534.16 Navigator 974 | Client-Side JavaScript Reference read more..

  • Page - 993

    Methods void registerContentHandler(string mimeType, string url, string title) url mimeType title url mimeType url void registerProtocolHandler(string scheme, string url, string title) registerContentHandler() scheme scheme void yieldForStorageUpdates() Document.cookie Window.localStorage Window.sessionStorage Stor- age Node parentNode childNodes[] childNodes[] firstChild nextSibling lastChild previousSibling read more..

  • Page - 994

    Constants unsigned short ELEMENT_NODE = 1 unsigned short TEXT_NODE = 3 unsigned short PROCESSING_INSTRUCTION_NODE = 7 unsigned short COMMENT_NODE = 8 unsigned short DOCUMENT_NODE = 9 unsigned short DOCUMENT_TYPE_NODE = 10 unsigned short DOCUMENT_FRAGMENT_NODE = 11 nodeType Node() unsigned short DOCUMENT_POSITION_DISCONNECTED = 0x01 unsigned short DOCUMENT_POSITION_PRECEDING = 0x02 unsigned read more..

  • Page - 995

    readonly unsigned short nodeType string nodeValue readonly Document ownerDocument null readonly Node parentNode null parentNode null readonly Node previousSibling childNodes[] parentNode null string textContent Text Comment data Element DocumentFragment Methods Node appendChild(Node newChild) newChild newChild newChild childNodes[] ownerDocument newChild ownerDocu ment Document.adoptNode() Node cloneNode(boolean deep) read more..

  • Page - 996

    unsigned short compareDocumentPosition(Node other) other DOCUMENT_POSITION_ DOCUMENT_POSITION_ Value Meaning DISCONNECTED 0x01 The two nodes are not in the same document, so their position cannot be compared. PRECEDING 0x02 The other node appears before this node. FOLLOWING 0x04 The other node comes after this node. CONTAINS 0x08 The other node contains this node. When this bit is set, read more..

  • Page - 997

    string lookupNamespaceURI(string prefix) prefix null prefix null string lookupPrefix(string namespace) namespace null void normalize() Node removeChild(Node oldChild) oldChild childNodes[] removeChild() oldChild oldChild Node replaceChild(Node newChild, Node oldChild) oldChild newChild oldChild oldChild newChild newChild oldChild NodeList a read-only array-like object of Nodes Node length length item() null read more..

  • Page - 998

    Properties readonly unsigned long length Methods Node item(unsigned long index) null Option an <option> in a Select element Node, Element Select options[] Document.cre ateElement() options HTMLOptionsCollection Constructor new Option([string text, string value, boolean defaultSelected, boolean selected]) Option() <option> textContent Node value defaultSelected selected Properties boolean defaultSelected selected read more..

  • Page - 999

    boolean selected true false string text textContent Node string value value textContent Output an HTML form <output> element Node, Element, FormControl <output> FormControl Properties string defaultValue textContent Node value defaultValue readonly DOMSettableTokenList htmlFor for <output> <output> for htmlFor DOMTokenList PageTransitionEvent event object for pageshow and pagehide events Event persisted read more..

  • Page - 1000

    Properties readonly boolean persisted false true true PopStateEvent history transition event Event pushState() History Properties readonly any state History.pushState() History.replaceState() state ProcessingInstruction a processing instruction in an XML document Node Properties string data ?> readonly string target <? Progress a progress bar Node, Element <progress> PopStateEvent 982 | Client-Side JavaScript read more..

  • Page - 1001

    <progress> Properties readonly Form form form readonly NodeList labels double max max readonly double position value/ max double value max value removeAttribute() Element ProgressEvent downloading, uploading, or file reading progress Event ApplicationCache FileReader XMLHttpRequest ProgressEvent Client-Side JavaScript Reference | 983 Client-Side JavaScript Reference read more..

  • Page - 1002

    <progress> Progress onprogress <progress> Properties readonly boolean lengthComputable true total false true e var percentComplete = Math.floor(100*e.loaded/e.total); readonly unsigned long loaded readonly unsigned long total size Content-Length Screen information about the display screen screen Properties readonly unsigned long availHeight readonly unsigned long availWidth readonly unsigned long colorDepth read more..

  • Page - 1003

    readonly unsigned long height availHeight readonly unsigned long width availWidth Script an HTML <script> element Node, Element <script> text textContent Node <script> src text <script> <script> <script> src type Properties boolean async true <script> async false string charset src boolean defer true <script> defer false string src string text <script> </script> string read more..

  • Page - 1004

    Select a graphical selection list Node, Element, FormControl <select> multiple size multiple size size size multiple size multiple options[] <option> Option <option> HTMLOptionsCollection multiple selectedIndex options[] selected Properties Ele- ment FormControl multiple required size unsigned long length options s n s[n] s.options[n] readonly HTMLOptionsCollection options Option long selectedIndex options multiple read more..

  • Page - 1005

    size selectedIndex onchange() readonly HTMLCollection selectedOptions Methods options HTMLOptionsCollection Element FormControl void add(Element element, [any before]) options.add() any item(unsigned long index) options.item() any namedItem(string name) options.namedItem() HTMLOptionsCollection void remove(long index) options.remove() Storage client-side storage of name/value pairs localStorage sessionStorage Window read more..

  • Page - 1006

    Methods void clear() any getItem(string key) key key string key(unsigned long n) n null n length void removeItem(string key) key delete key void setItem(string key, any value) key value key value key setItem() StorageEvent Event localStorage sessionStorage Storage Properties readonly string key Storage.clear() newValue oldValue null readonly any newValue key null StorageEvent 988 | Client-Side read more..

  • Page - 1007

    readonly any oldValue null readonly Storage storageArea localStorage sessionStorage readonly string url Style an HTML <style> element Node, Element <style> Properties boolean disabled true <style> false string media media boolean scoped true scoped <style> false readonly CSSStyleSheet sheet CSSStyleSheet <style> string title title <style> string type type Table an HTML <table> Node, read more..

  • Page - 1008

    TableCell TableRow Table- Section Properties summary Element caption <caption> null readonly HTMLCollection rows <thead> <tfoot> <tbody> readonly HTMLCollection tBodies <tbody> TableSection tFoot <tfoot> null TableSection tHead <thead> null Methods Element createCaption() <caption> <caption> TableSection createTBody() <tbody> <tbody> TableSection createTFoot() <tfoot> read more..

  • Page - 1009

    void deleteCaption() <caption> void deleteRow(long index) <thead> <tfoot> void deleteTFoot() <tfoot> void deleteTHead() <thead> TableRow insertRow([long index]) <tr> index index index <tbody> TableRow.insertCell() insertRow() TableSection TableCell a cell in an HTML table Node, Element <td> <th> Properties readonly long cellIndex unsigned long colSpan colspan unsigned read more..

  • Page - 1010

    Properties readonly HTMLCollection cells <td> <th> readonly long rowIndex readonly long sectionRowIndex <thead> <tbody> <tfoot> Methods void deleteCell(long index) index Element insertCell([long index]) <td> index index <td> <th> Document.cre ateElement() Node.insertBefore() TableSection a header, footer, or body section of a table Node, Element <tbody> <thead> read more..

  • Page - 1011

    index index Text a run of text in a document Node data nodeValue Document.createTextNode() Properties string data readonly unsigned long length readonly string wholeText normalize() Node data Methods void appendData(string text) text void deleteData(unsigned long offset, unsigned long count) offset count offset count offset void insertData(unsigned long offset, string text) text offset void read more..

  • Page - 1012

    Text replaceWholeText(string text) text wholeText normalize() Node Text splitText(unsigned long offset) offset offset offset parentNode string substringData(unsigned long offset, unsigned long count) offset count String.substring() TextArea a multiline text input area Node, Element, FormControl <textarea> <textarea> </textarea> value form name type value FormControl Properties Element read more..

  • Page - 1013

    readonly unsigned long textLength value FormControl Methods Element FormControl void select() <textarea> void setSelectionRange(unsigned long start, unsigned long end) <textarea> start end TextMetrics measurements of a string of text measureText() width Properties readonly double width TimeRanges a set of media time ranges buffered played seekable MediaElement played length start() end() read more..

  • Page - 1014

    Methods double end(unsigned long n) n n length double start(unsigned long n) n n length TypedArray fixed-size binary arrays ArrayBufferView ArrayBufferView ArrayBuffer Int8Array Int16Array Int32Array Uint8Array Uint16Array Uint32Array Float32Array Float64Array DataView TypedArray 996 | Client-Side JavaScript Reference read more..

  • Page - 1015

    Constructor new TypedArray(unsigned long length) new TypedArray(TypedArray array) new TypedArray(type[] array) new TypedArray(ArrayBuffer buffer,[unsigned long byteOffset],[unsigned long length]) Constants long BYTES_PER_ELEMENT Properties readonly unsigned long length byte Length ArrayBufferView Methods void set(TypedArray array, [unsigned long offset]) array offset void set(number[] array, [unsigned long read more..

  • Page - 1016

    end start end URL Blob URL methods URL webkitURL Functions string createObjectURL(Blob blob) blob blob void revokeObjectURL(string url) url Video an HTML <video> element Node, Element, MediaElement <video> <video> <audio> MediaElement Properties DOMSettableTokenList audio audio unsigned long height <video> height string poster poster URL 998 | Client-Side JavaScript Reference read more..

  • Page - 1017

    readonly unsigned long videoHeight readonly unsigned long videoWidth <video> readyState HAVE_NOTHING unsigned long width <video> width WebSocket a bidirectional socket-like network connection EventTarget WebSocket() send() Constructor new WebSocket(string url, [string[] protocols]) WebSocket() url ws:// wss:// protocols protocols Constants readyState unsigned short CONNECTING = 0 unsigned short OPEN = 1 read more..

  • Page - 1018

    Properties readonly unsigned long bufferedAmount send() readonly string protocol WebSocket() readonly unsigned short readyState readonly string url WebSocket() Methods void close() readyState CLOSING close() readyState CLOSED void send(string data) data readyState CONNECTING Event Handlers XMLHttpRequest EventTarget onclose readyState CloseEvent onerror WebSocket 1000 | Client-Side JavaScript Reference read more..

  • Page - 1019

    onmessage MessageEvent data onopen WebSocket() url Window a web browser window, tab, or frame EventTarget document window.document alert() window.alert() Global EventTarget window self <iframe> frames parent top Window.open() open() opener Properties id Window Client-Side JavaScript Reference | 1001 Client-Side JavaScript Reference read more..

  • Page - 1020

    readonly ApplicationCache applicationCache ApplicationCache readonly any dialogArguments showModalDialog() arguments showModalDialog() readonly Document document Document readonly Event event readonly Element frameElement <iframe> IFrame null readonly Window frames self window w[0] w w.frames[0] readonly History history History readonly long innerHeight readonly long innerWidth readonly unsigned long length frames readonly read more..

  • Page - 1021

    target <a> <form> target readonly Navigator navigator Navigator readonly Window opener open() null opener readonly long outerHeight readonly long outerWidth readonly long pageXOffset readonly long pageYOffset pageXOffset pageYOffset readonly Window parent parent parent string returnValue showModalDialog() close() showModalDialog() readonly Screen screen Screen readonly long screenX readonly long screenY readonly read more..

  • Page - 1022

    localStorage readonly Window top top top parent readonly object URL URL URL() readonly Window window window self window Constructors Image() XMLHttpRequest() Image XMLHttpRequest Methods Global void alert(string message) alert() message alert() string atob(string atob) charCodeAt() btoa() void blur() blur() string btoa(string btoa) String.fromChar Code() atob() Window 1004 | Client-Side JavaScript Reference read more..

  • Page - 1023

    void clearInterval(long handle) clearInterval() setInterval() intervalId setInterval() void clearTimeout(long handle) clearTimeout() setTimeout() timeoutId setTimeout() void close() close() boolean confirm(string message) question confirm() true confirm() false void focus() CSSStyleDeclaration getComputedStyle(Element elt, [string pseudoElt]) style null getComputedStyle() style currentStyle Window open([string read more..

  • Page - 1024

    url url features Window.open() replace replace true false Location.replace() void postMessage(any message, string targetOrigin, [MessagePort[] ports]) message ports targetOrigin message targetOrigin targetOrigin MessageEvent void print() print() string prompt(string message, [string default]) prompt() message prompt() null prompt() default void scroll(long x, long y) scrollTo() void scrollBy(long x, read more..

  • Page - 1025

    long setInterval(function f, unsigned long interval, any args...) setInterval() f interval interval f this args setInterval() setInterval() Window.clearInterval() code f <script> interval setTimeout() long setTimeout(function f, unsigned long timeout, any args...) setTimeout() setInterval() f timeout clearTimeout() f args f timeout <script> any showModalDialog(string url, [any read more..

  • Page - 1026

    Event Handler Invoked... onload When the document and its external resources are fully loaded onmessage When a script in another window sends a message by calling the postMessage() method. See Mes- sageEvent. onoffline When the browser loses its connection to the Internet ononline When the browser regains a connection to the Internet onpagehide When the page is about to be cached and read more..

  • Page - 1027

    ports MessageChannel void terminate() Event Handlers EventTarget onerror onerror ErrorEvent onmessage postMessage() WorkerGlobalScope MessageEvent data postMessage() WorkerGlobalScope EventTarget, Global Global Properties Math JSON readonly WorkerLocation location window.location Location WorkerGlobalScope Client-Side JavaScript Reference | 1009 Client-Side JavaScript Reference read more..

  • Page - 1028

    readonly WorkerNavigator navigator window.navigator Navigator readonly WorkerGlobalScope self window Methods isNaN() eval() void clearInterval(long handle) void clearTimeout(long handle) void close() void importScripts(string urls...) urls location void postMessage(any message, [MessagePort[] ports]) message ports message data postMessage() long setInterval(any handler, [any timeout], any args...) read more..

  • Page - 1029

    Event Handlers EventTarget onerror onerror onerror false false onmessage postMessage() data message WorkerLocation the URL of a worker’s main script location Location location location location.href Properties readonly string hash readonly string host readonly string hostname WorkerLocation Client-Side JavaScript Reference | 1011 Client-Side JavaScript Reference read more..

  • Page - 1030

    readonly string href Worker() readonly string pathname readonly string port readonly string protocol readonly string search WorkerNavigator browser information for workers navigator Navigator Properties readonly string appName appName readonly string appVersion appVersions readonly boolean onLine true false readonly string platform readonly string userAgent XMLHttpRequest An HTTP request and response EventTarget read more..

  • Page - 1031

    XMLHttpRequest() open() onreadystatechange setRequestHeader() send() onreadystatechange readyState status getResponseHeader() getResponseHeaders() responseText responseXML Constructor new XMLHttpRequest() Constants readyState unsigned short UNSENT = 0 abort() unsigned short OPENED = 1 open() send() unsigned short HEADERS_RECEIVED = 2 send() unsigned short LOADING = 3 XMLHttpRequest Client-Side JavaScript Reference | 1013 read more..

  • Page - 1032

    unsigned short DONE = 4 Properties readonly unsigned short readyState readyState abort() open() readystatechange readyState readonly any response response Type responseType responseType Document responseType ArrayBuffer responseType Blob readonly string responseText readyState readyState ready State string responseType response responseText responseXML response readonly Document responseXML readonly unsigned short status read more..

  • Page - 1033

    readonly string statusText status status unsigned long timeout open() send() readonly XMLHttpRequestUpload upload XMLHttpRequestUpload boolean withCredentials false Methods void abort() readyState string getAllResponseHeaders() string getResponseHeader(string header) header null header void open(string method, string url, [boolean async, string user, string pass]) send() method url XMLHttpRequest read more..

  • Page - 1034

    async false send() Worker user pass void overrideMimeType(string mime) mime Content-Type void send(any body) open() readyState send() open() setRequestHeader() body body null ArrayBuff- er Blob FormData async open() false readyState send() void setRequestHeader(string name, string value) setRequestHeader() name value send() readyState open() send() name value open() Authorization setRequestHeader() XMLHttpRequest 1016 | read more..

  • Page - 1035

    Event Handlers onreadystatechange EventTarget upload XMLHttpRequestUpload onabort onerror onload onloadend onloadstart onprogress onreadystatechange readyState ontimeout timeout XMLHttpRequestUpload EventTarget upload XMLHttpRequestUpload Client-Side JavaScript Reference | 1017 Client-Side JavaScript Reference read more..

  • Page - 1036

    EventTarget onreadystatechange Event Handlers onabort onerror onload onloadend onloadstart onprogress ontimeout timeout XMLHttpRequestUpload 1018 | Client-Side JavaScript Reference read more..

  • Page - 1037

    Index Symbols 1019 read more..

  • Page - 1038

    1020 | Index read more..

  • Page - 1039

    A Index | 1021 read more..

  • Page - 1040

    1022 | Index read more..

  • Page - 1041

    Index | 1023 read more..

  • Page - 1042

    B 1024 | Index read more..

  • Page - 1043

    Index | 1025 read more..

  • Page - 1044

    C 1026 | Index read more..

  • Page - 1045

    Index | 1027 read more..

  • Page - 1046

    1028 | Index read more..

  • Page - 1047

    Index | 1029 read more..

  • Page - 1048

    1030 | Index read more..

  • Page - 1049

    Index | 1031 read more..

  • Page - 1050

    D 1032 | Index read more..

  • Page - 1051

    Index | 1033 read more..

  • Page - 1052

    1034 | Index read more..

  • Page - 1053

    Index | 1035 read more..

  • Page - 1054

    E 1036 | Index read more..

  • Page - 1055

    Index | 1037 read more..

  • Page - 1056

    1038 | Index read more..

  • Page - 1057

    Index | 1039 read more..

  • Page - 1058

    F 1040 | Index read more..

  • Page - 1059

    Index | 1041 read more..

  • Page - 1060

    1042 | Index read more..

  • Page - 1061

    G Index | 1043 read more..

  • Page - 1062

    1044 | Index read more..

  • Page - 1063

    H Index | 1045 read more..

  • Page - 1064

    1046 | Index read more..

  • Page - 1065

    I Index | 1047 read more..

  • Page - 1066

    1048 | Index read more..

  • Page - 1067

    Index | 1049 read more..

  • Page - 1068

    J K 1050 | Index read more..

  • Page - 1069

    L Index | 1051 read more..

  • Page - 1070

    1052 | Index read more..

  • Page - 1071

    M Index | 1053 read more..

  • Page - 1072

    N 1054 | Index read more..

  • Page - 1073

    Index | 1055 read more..

  • Page - 1074

    O 1056 | Index read more..

  • Page - 1075

    Index | 1057 read more..

  • Page - 1076

    1058 | Index read more..

  • Page - 1077

    P Index | 1059 read more..

  • Page - 1078

    1060 | Index read more..

  • Page - 1079

    Index | 1061 read more..

  • Page - 1080

    Q R 1062 | Index read more..

  • Page - 1081

    Index | 1063 read more..

  • Page - 1082

    1064 | Index read more..

  • Page - 1083

    S Index | 1065 read more..

  • Page - 1084

    1066 | Index read more..

  • Page - 1085

    Index | 1067 read more..

  • Page - 1086

    1068 | Index read more..

  • Page - 1087

    Index | 1069 read more..

  • Page - 1088

    T 1070 | Index read more..

  • Page - 1089

    Index | 1071 read more..

  • Page - 1090

    1072 | Index read more..

  • Page - 1091

    U Index | 1073 read more..

  • Page - 1092

    V 1074 | Index read more..

  • Page - 1093

    W Index | 1075 read more..

  • Page - 1094

    1076 | Index read more..

  • Page - 1095

    X Index | 1077 read more..

  • Page - 1096

    Y Z 1078 | Index read more..

  • Page - 1097

    About the Author Colophon read more..

  • Page - 1098

    read more..

Write Your Review