Upgrade to Pro — share decks privately, control downloads, hide ads and more …

JavaScript - A second Look

JavaScript - A second Look

Avatar for Cory Loriot

Cory Loriot

August 24, 2013

Other Decks in Programming

Transcript

  1. Agenda • Overview • Variables • Objects • Functions •

    Arrays • Intro to DOM? • Browser Objects • Querying DOM • Manipulating DOM • Event Handling • Consuming Data
  2. Who I am … • MCPD, SharePoint 2010 • MCITP

    , SharePoint 2010 • Certified Master Candidate, SharePoint • Passionate about writing code … in all forms • Passionate about SharePoint…
  3. Who is CTS? • IT professional services firm • Established

    in 1993 • 200+ employees • 33 active clients in various industries • $27M Revenue – 2012 Mobile
  4. Overview – Brief History • 1995 – Browser Client Scripting

    Language • 1997 – Formalized to ECMAScript • 2009 – Node.js moves JavaScript to Server Side Processing • 2012 – Microsoft moves JavaScript to Client Application Development – out of the browser
  5. Overview - Characteristics • Not Object Oriented • Though it

    does have characteristics, you could never implement all facets of OOP Design Principles • Prototype-based language • Object Emulation, no Inheritance (more on this in a few slides) • Dynamic • You can append properties to any object, because there is no static object declaration • Weakly-Typed • You initialize variables as the “Variant” or “var” type, which is basically base for all type. • Context determines the type and applicability of operators to that type.
  6. Overview - Characteristics • First Class functions • All functions

    operate as pointers on a stack, just like an object, and follow the same rules as any object in JavaScript • For instance, you can add a property to a function, and there can be good reasons for doing so  • K&R style syntax, with many of the same constructs • if … else • try { } catch {} • switch { case: }
  7. What the heck? • Prototype-based programming is a style of

    object-oriented programming in which classes are not present, and behavior reuse (known as inheritance in class-based languages) is performed via a process of cloning existing objects that serve as prototypes. This model can also be known as classless, prototype-oriented or instance-based programming. Delegation is the language feature that supports prototype-based programming. • The first prototype-oriented programming language was Self developed by David Ungar and Randall Smith in the mid-1980s to research topics in object-oriented language design. Since the late 1990s, the classless paradigm has grown increasingly popular. Some current prototype-oriented languages are ECMAScript (and its implementations JavaScript, JScript and Flash's ActionScript 1.0), Cecil, NewtonScript, Io, MOO, REBOL, and Lisaac.
  8. Why? • Advocates of prototype-based programming often argue that class-

    based languages encourage a model of development that focuses first on the taxonomy and relationships between classes. • In contrast, prototype-based programming is seen as encouraging the programmer to focus on the behavior of some set of examples and only later worry about classifying these objects into archetypal objects that are later used in a fashion similar to classes. • As such, many prototype-based systems encourage the alteration of prototypes during run-time, whereas only very few class-based object-oriented systems allow classes to be altered during the execution of a program.
  9. Code First … • JavaScript lets you build as you

    go… • A nice modular design may include JS files that build on each other, adding properties and methods to “base” or prototype classes as needed to extend the functionality and meet changing needs
  10. Agenda • Overview • Variables • Objects • Functions •

    Arrays • Intro to DOM? • Browser Objects • Querying DOM • Manipulating DOM • Event Handling • Consuming Data
  11. Variables • As mentioned… they are weakly typed • Store

    information for the duration of the page life in the browser, or in Windows Apps, life of the “screen” • Common types: • String, number, Boolean, array, object, null, undefined
  12. Variable Declaration • var myVar; • var myVar = “”;

    • var myVar = 1; • var myVar = { 1, 2, 3, 4 };
  13. Variable Naming Rules 1. Cannot start with numbers 2. Cannot

    have mathematical or logical operators in them (+ - % / < > = || && ) 3. Cannot use punctuation except for “_” character ( . , : ; ) • myVar.ForFun would assume a ForFun child property of myVar and return undefined  4. Must not contain spaces 5. Cannot use JS keywords (window document string ) 6. Case Sensitive … • Once you make myVar, don’t assign to MyVar or myVAR … they aren’t the same thing • And no … there is no Option Explicit on the web … but there is “use strict” in the ECMAScript 5 specification • Simply add “use strict” as a string at the top of your code, or in your function
  14. A moment for “Implicit Globals” • An implicit global is

    a variable that is used, but not declared in the current scope • Var x = 10; function f () { x++; } • f() assumes the existence of x because it is not declare locally • Dangers? • Yes, large projects with many code files can share implicit globals without realizing • If the implicit global is not declared, you get a reference error. • Is it ok to use? • Yes. Just dangerous.
  15. And… back to Variables • Variables can be anything at

    any time • Be careful how you use them • If you are concerned with making mistakes, use strict
  16. Agenda • Overview • Variables • Objects • Functions •

    Arrays • Intro to DOM? • Browser Objects • Querying DOM • Manipulating DOM • Event Handling • Consuming Data
  17. Objects • Most of the advanced functionality in JS really

    requires an understanding of how class definitions work
  18. Objects • A few concepts • Dynamic property creation •

    Object Initializer Syntax • JSON – JavaScript Object Notation
  19. Objects • Dynamic property creation • If you have an

    object, and you want it to have a new property, just add the property and give it a value • Not a structured approach
  20. Objects • Dynamic property creation var obj = { };

    obj.newProp = “my new prop”;
  21. Objects • Object Initializer Syntax • Provide properties during the

    initialization for the object • Allows quotes on the property names • Allows for methods (anonymous functions assigned to a property) • This is a structured approach
  22. Objects • Object Initializer Syntax var obj = { prop:

    “my prop”, func: function () { … } }; obj.prop = “z”; obj.func();
  23. Objects - JSON • JSON • Same concept as Object

    Initializer • Does not allow for methods in the definition • Requires quotes around the property names • Structured and standards compliant
  24. Objects - JSON • JSON var obj = { “prop”:

    “my prop” }; obj.prop = “z”;
  25. Objects - JSON • Commonly used as a return value

    to serialize information from a web service call or asynchronous post back • You would assign this to an object to use for modifying the DOM { “prop”: “my prop”; };
  26. Objects • So… JSON isn’t really scary after all. •

    But learning how to use it effectively is going to make more sense in the session on DOM Manipulation
  27. Agenda • Overview • Variables • Objects • Functions •

    Arrays • Intro to DOM? • Browser Objects • Querying DOM • Manipulating DOM • Event Handling • Consuming Data
  28. Functions • Function are objects, so they can be stored

    as variables • First class citizens in JavaScript
  29. Functions – Basic Characteristics • Callable behaviors • They can

    be declared in one place, contain functionality, and be invoked in multiple places • Implemented as objects • Everything is an object in JS, but function is the only object that can be invoked (which gets interesting when we get to classes) • Pass as pointers to variables, or as arguments to other functions
  30. Functions – A few types • Declared (static) functions are

    the traditional format • function x () { alert(‘Hello World’); }; • Anonymous functions are nice for single use methods, or for event handling • var y = function () { alert(‘Hello World’); }; • Immediate functions are self executing anonymous functions
  31. Functions – Arguments • Arguments are not only defined by

    the signature of the function, but by the function call • This is the nature of a prototype language, you have to assume the calling point could give you anything • “arguments” is a keyword/object that contains an array of all the arguments passed to the function
  32. Passing functions as parameters • Remember the order of execution

    • If you pass a function using the (), it will execute the function, and pass the return value as an argument • If you don’t add the (), it passes the function itself, which can then be executed by reference • This follows the Dependency Injection principle
  33. Functions vs. Methods • Standard Definition, a function does something

    and returns a value, a method does something but does not return a value • In JS, that definition is wrong. There are only functions, and they may or may not implicitly return anything (although technically there is always a return value) • So… what is a method? • A method is an anonymous or declared function that is the property of an object … it may or may not return something
  34. Extension Functions/Properties • Modifying objects to include new functionality on

    all existing “instances” of the object • Remember, there are no class definitions, just classes that are cloned. • So you have to modify the definition of the initial cloned object • If you just add a property to the base, it does not affect existing instances, or future instances
  35. Extension Properties • We can extend our own objects •

    We can extend objects that belong to the system, such as Window and Document • We can extend type based objects, such as string and number
  36. Extension Functions/Properties • Why? • What if you needed a

    means to perform a uniform operation on a type, such as reversing the contents of a string. • You would normally write a method, and pass the string • What if you could add the reverse method to every string? • var myString = “Hello, World”; • myString.reverse(); • Wouldn’t that be easier?
  37. Extension Functions/Properties • How? • The prototype object is implicit

    to every object in the language, and everything in the language is an object. • Example: • string.prototype.reverse = function () { }; • Call the prototype object on the object you want to modify, then use the ‘.’ operator to append the new property/method name. use the gets operator to define the functionality or default value.
  38. Function Scoping • Closest thing to encapsulation that JavaScript has

    available • Basic guideline, variables created inside of a method cannot be utilized outside that method • Use this as a means to manage accessibility to variables and functions
  39. Function Scoping • Different scopes • Global Scope • Objects

    declared outside any other scopes are global and accessible to the tighter scopes • Function scope • Objects declared within or passed as arguments are treated as global to all child scopes • Block scope • Objects declared within a block are only accessible inside that block
  40. Function Scoping • Don’t confuse scope with the following keywords

    in C# • public, private, protected • There is no way to grant outside entities access to objects that are internally scoped • Well, almost no way, you can return it • This grants access to the value, not to the object
  41. Function Scoping • Functions within functions are scoped only to

    that function • Functions still follow the rules though, an immediate function will still execute immediately when it is reached in the function call.
  42. Function Scoping • Why? • Function scoping is the closest

    thing JavaScript has for encapsulation. • If you are building a very large program, utilizing scoping can simplify your code so that you don’t bombard developers with the complexity of your API. • For instance jQuery does a lot more under the hood than we see through the available functions.
  43. Function Scoping • How? • Simply add properties and methods

    into your function • Anything declared inside the function will be inaccessible outside the function
  44. Function Scoping var x = 2000; function get_value() { var

    y = 13; // y is inaccessible // outside this method return y; } var z = x + y; // y is undefined var z = x + get_value(); // z == 2013
  45. Function Scoping • Why this is cool… • The contents

    of the initial function don’t have to be empty, and has access to members of the prototype (yes, even before the prototype is defined) • Works like a constructor  and doesn’t leave “miscellaneous” variables out there as part of the object
  46. Module Pattern • Setting a var to the return value

    of an immediate function. • Interesting pattern, allows you to define an immediate function that returns an object utilizing functionality from the immediate function • Basically a constructor and object definition in one
  47. Module Pattern var obj = (function() { var a =

    1, b = 2, c = 3; return { x: a, y: b, product: function() { return a*b*c; } }; })(); // all of these will work alert(obj.x); alert(obj.y); alert(obj.product());
  48. Agenda • Overview • Variables • Objects • Functions •

    Arrays • Intro to DOM? • Browser Objects • Querying DOM • Manipulating DOM • Event Handling • Consuming Data
  49. Arrays • What is an array? • An object that

    has multiple values that are accessible through an indexer • In JS, arrays are always arrays of objects, not of a single type necessarily • Because everything is an object in JS, anything can go in an array, even functions!
  50. Arrays • Important Notes: • JS Arrays use a zero-base

    indexer, therefore, ary[0] is the first element, and ary[1] is the second. • However … the length() method returns arrays using normal counting practice, so an array with 5 elements will return 5 from the length(), but the last element will be ary[4]. • If you overflow the boundaries of the array, you will get an error. • If you are iterating through the array, don’t use the <= comparison to the length, use the < operator
  51. Arrays • How to declare an array: var ary =

    [ 1, 2, 3, 4 ]; • How to use the array: for (var i = 0; i < ary.length; i++) { alert(ary[i]); }
  52. Multi-Dimensional Arrays • An “Array of Arrays” is the best

    way to think of it • You create an array which has elements that are arrays • If the child elements do not all have the same length, this is called a Jagged Array
  53. Multi-Dimensional Arrays • How to declare: var ary = [

    [1, 2], [2, 3], [4, 5] ]; • How to use the array: for (var i = 0; i < ary.length; i++) { for (var x = 0; x < ary.length[i]; x++) { alert(ary[i][x]); } }
  54. Arrays • The latest version of ECMAScript has new features

    for arrays, to make them developer friendly • Everyone say it… Thank you ECMA …
  55. Arrays • Three kinds of methods on an array: •

    Mutators – modify the contents and structure of the array • pop, push, reverse, shift, sort, splice, unshift • Accessors – do not modify the array, and return some representation of the array • concat, join, slice, indexOf, lastIndexOf • Iterators – provide a method as an argument to be executed against every element in the array (as of the time it is called) • forEach, every, some, filter, map, reduce, reduceRight
  56. Arrays • Methods are either mutable or immutable • Mutable

    methods will modify the contents of the array in place • Immutable methods will not modify the array directly, but return a new instance of the array • Mutators – Mutable • Accessors – Immutable • Iterators – Mutable to the Elements of the array, but not to the array itself
  57. Array methods • Mutators • pop • push • reverse

    • shift • sort • splice • unshift
  58. pop() • Removes the last element of the array •

    Returns the value for that element • Sounds like a Stack (LIFO) method var fib = [ 0, 1, 1, 2, 3, 5, 8, 13 ]; alert(fib.pop()); // returns 13 // fib = [ 0, 1, 1, 2, 3, 5, 8 ];
  59. push() • Adds new elements to the end of an

    array • Returns the new length of the array • Works to make the array into a stack or queue var fib = [ 0, 1, 1, 2, 3, 5, 8, 13 ]; alert(fib.push(21)); // returns 9
  60. reverse() • Reverse the items in the array in the

    exact opposite order as the original. var fib = [ 0, 1, 1, 2, 3, 5, 8, 13 ]; alert(people.reverse()); // fib == [ 13, 8, 5, 3, 2, 1, 1, 0 ];
  61. shift() • Removes the first element of the array •

    Returns the value for that element • Sounds like a queue (FIFO) method var fib = [ 0, 1, 1, 2, 3, 5, 8, 13 ]; alert(fib.shift()); // returns 0 // fib = [1, 1, 2, 3, 5, 8, 13 ];
  62. sort() • Sorts the items in alphabetical order ascending var

    people = [“John”,“Aaron”,“Zoe”,“Carol”]; alert(people.sort().reverse()); // people == [“Aaron”,“Carol”,“John”,“Zoe”]
  63. sort().reverse() • Sorts the items in alphabetical order descending var

    people = [“John”,“Aaron”,“Zoe”,“Carol”]; alert(people.sort().reverse()); // people == [“Zoe”,“John”,“Carol”,“Aaron”]
  64. sort (fn(a, b)) • Numbers sorted alphabetically don’t work well,

    since 4 comes before 5, but alphabetically 40 would also come before 5 • Because it’s literally comparing the ASCII number of the first character • You can resolve this, by passing a function to the sort method, which feels a lot like a lambda in Linq… var numbers = [ 10, 4, 2, 1, 66, 0]; alert(numbers.sort(function(a, b) { return a-b;}); // numbers == [ 0, 1, 2, 4, 10, 66 ];
  65. sort (fn(a, b)) • What about descending? • Simply reverse

    a and b in the calculation var numbers = [ 10, 4, 2, 1, 66, 0]; alert(numbers.sort(function(a, b) { return b-a; }); // numbers == [ 66, 10, 4, 2, 1, 0 ];
  66. splice (index, remove, […]) • Inserts elements into the array

    starting at the index provided • If remove is > 0, then it will overwrite that many elements before increasing the size of the array • The return value is an array of items removed from the array with the length of remove • Last arguments are the items to insert into the array, as many as you like, just separate them by commas as below var numbers = [ 10, 4, 2, 1, 66, 0 ]; alert(numbers.splice(2, 2, 7, 8, 12)); // returns [2, 1] // numbers == [ 10, 4, 7, 8, 12, 66, 0 ];
  67. unshift() • Adds an element to the beginning of the

    array • Kind of like the reverse of shift that pops from the front • Returns the new length of the array var fib = [ 1, 1, 2, 3, 5, 8, 13 ]; alert(fib.unshift(0)); // returns 8 // fib = [ 0, 1, 1, 2, 3, 5, 8, 13 ];
  68. concat() • Merges the contents of multiple arrays, taking array

    objects as parameters • Arrays are appended into the calling array in the order they are listed as arguments and the return value is the resulting array var ary1 = [ 1, 2, 3 ]; var ary2 = [ 4, 5, 6 ]; var aryN = [ 7, 8, 9 ]; var mrg = ary1.concat(ary2, aryN); // mrg == [1, 2, 3, 4, 5, 6, 7, 8, 9 ];
  69. join() || toString() • Joins all of the elements in

    the array into a single string, comma separated • Important to remember, it does not add them together, it concatenates them. Even when they are numbers var fib = [ 0, 1, 1, 2, 3, 5, 8, 13 ]; alert(fib.join()); // == 0,1,1,2,3,5,8,13 alert(fib.toString()); // == 0,1,1,2,3,5,8,13
  70. indexOf() • Search the array for an element and return

    the index location (zero-based) of the first instance in the array • Great for finding that lost element … var fib = [ 0, 1, 1, 2, 3, 5, 8, 13 ]; alert(fib.indexOf(1)); // == 1 (second)
  71. lastIndexOf() • Search the array backwards for an element and

    return the index location (zero-based) of the last instance in the array var fib = [ 0, 1, 1, 2, 3, 5, 8, 13 ]; alert(fib.lastIndexOf(1)); // == 2 (third)
  72. slice(start, end) • Extracts selected elements in a sequence from

    the array • Note: it will go from the start index to the end index, not including the end • Returns an array of the selected elements var fib = [ 0, 1, 1, 2, 3, 5, 8, 13 ]; alert(fib.slice(2, 4)); // returns [1, 2];
  73. Array Methods • Iterators • forEach • every • some

    • filter • map • reduce • reduceRight
  74. To start • The typical method signature for an iterator

    is as follows: function(element, index, array){} • But that doesn’t mean we have to use all of them, as long as we know how to use them right. (and we can use arguments to pick up the other two if we need them) function(e){}
  75. forEach() • Calls a function for every element in the

    array • Possible to change the contents of the elements of the array in place function doIt (element, index, array){ alert(element + “ @ “ + index); } ary.forEach(doIt);
  76. every() • Returns true value to specify if all contents

    in the array meet a given condition in the callback function, otherwise false function checkIt (el){ return el >= 10; } ary.every(checkIt);
  77. some() • Returns true value to specify if any contents

    in the array meet a given condition in the callback function, otherwise false function checkIt (el){ return el >= 10; } ary.some(checkIt);
  78. filter() • Returns a new array containing all of the

    elements that meet the specified criteria • Like the select keyword in Linq function checkIt (el){ return el >= 10; } ary.filter(checkIt);
  79. map() • Projects a new list of whatever return type

    is specified out from the results • Like the select keyword in Linq, projecting an “anonymous type” function get_as_class(el, idx){ if (el >= 10) { return { Nice: el, Loc: idx, f: function() {} }; } } var x = ary.map(get_as_class);
  80. reduce() • Iterate the elements of the array, performing an

    operation on the previous and next elements, returning a value that is compounded until the end of the array. • Iterates from the beginning to the end • Allows for an argument to specify the initial value var startAt = 10; function x (prev, next, index, array) { return prev + next; }; ary.reduce(x, startAt);
  81. reduceRight() • Iterate the elements of the array, performing an

    operation on the previous and next elements, returning a value that is compounded until the end of the array. • Iterates from the end to the beginning • Allows for an argument to specify the initial value • This could be useful for flattening a multi-dimensional array ary.reduceRight(function (a, b) { return a.concat(b); });
  82. Agenda • Overview • Variables • Objects • Functions •

    Arrays • Intro to DOM? • Browser Objects • Querying DOM • Manipulating DOM • Event Handling • Consuming Data
  83. What is the DOM? • Document Object Model • A

    model, representing the HTML Document • Similar to XML DOM? • No… exactly the same, pretty much • C# .Net XPath is a congruent topic
  84. What is the DOM? • Time for a good question,

    and an important note • What is the difference between HTML and XML?
  85. What is the DOM? • HTML • HyperText Markup Language

    • The language of the web, interpreted by browsers • Static pre-defined elements with very few rules for structure • XML • eXtensible Markup Language • Universal data modeling language • Utilizes a hierarchy of nodes to represent a parent-child relationship • Allows only one root node • Requires all attributes to operate in key=value pairs
  86. What is the DOM? • XHTML • eXtensible HyperText Markup

    Language • Follows more rigid rules for document components • Capable of parsing with an XML DOM parser
  87. What is the DOM? • Important Note: • You should

    always structure your documents as XHTML because they will be easier to parse and find information using JavaScript and the DOM
  88. What is the DOM? • One last thing … •

    You might hear the term DHTML • This stands for Dynamic HTML • Literally: JavaScript DOM Manipulation to add and remove elements from the DOM which may or may not have existed in the Response from the server • We will learn more about this concept in this lesson
  89. Agenda • Overview • Variables • Objects • Functions •

    Arrays • Intro to DOM? • Browser Objects • Querying DOM • Manipulating DOM • Event Handling • Consuming Data
  90. Browser Objects • window • Represents the browser to JavaScript

    • Allows for full manipulation of the window • Resize it • Create new windows • Redirect the browser • If the document contains <frame> or <iframe> elements, the browser has one window object for each 
  91. Browser Objects • document • JS representation of the HTML

    document loaded into the browser • Provides access to all HTML elements on the page • All the properties of node included
  92. Browser Objects • document: Common properties • anchors • Collection

    of <a name=“*”> elements in the document • body • Returns the <body> element in the document • cookie • Returns all the key/value pairs in the document • domain • The DNS name of the server that provided the document • forms • Collection of <form> elements in the document
  93. Browser Objects • document: Common properties • images • Collection

    of <img> elements in the document • links • Collection of <a href=“*”> and <area> elements in the document • referrer • The url of the document that loaded the current document • title • Gets or sets the title of the document from the <title /> element • url • Returns the full url of the document from the address bar
  94. Browser Objects • document.readyState • Returns a value based on

    the current status of the document • uninitialized - Has not started loading yet • loading - Is loading • interactive - Has loaded enough and the user can interact with it • complete - Fully loaded • Not W3C Compliant, but supported by all major browsers
  95. Browser Objects • document: Common functions • close()/open(mimetype, replace) •

    Open or close an output stream to collect output from .write() or .writeln() • write(s)/writeln(s) • Provide new content for output to the document specified by the most recent .open() command • writeln() adds a newline character at the and of the string
  96. Browser Objects • location • Contains information about the current

    url • Not W3C compliant, but supported in all major browsers
  97. Browser Objects • navigator • Contains information about the browser,

    such as current state and platform • Not W3C compliant, but supported by all major browsers
  98. Browser Objects • history • Accesses the browser history •

    Allows you to move backward and forward in the history • Not W3C compliant, but supported by all major browsers
  99. Browser Objects • screen • Provides information about the user

    desktop workspace • Not W3C Compliant, but supported by all major browsers
  100. Agenda • Overview • Variables • Objects • Functions •

    Arrays • Intro to DOM? • Browser Objects • Querying DOM • Manipulating DOM • Event Handling • Consuming Data
  101. Querying the DOM • Kind of like CSS Selectors: •

    Select by ID • Select by Type (tag name) • Select by Class • Select by Attribute
  102. Querying the DOM • Why Query the DOM? • The

    information provided in HTML is essentially a document • Forms provide users with the ability to add information to this document • It can be useful to retrieve values from the form to provide immediate feedback or change the document dynamically
  103. Querying the DOM • In order to manipulate the DOM

    with JavaScript, you have to find what you are looking for…
  104. Querying the DOM • getElementById( id ) • Selects a

    single element in the DOM that has the provided ID • Every element in the DOM must have a unique Identifier • Returns an object with attributes relative to the DOM element • For instance: • <div id=“myElement” /> • var el = document.getElementById(“myElement”);
  105. Querying the DOM • getElementsByTagName( type ) • Selects all

    elements of a type in the DOM • Returns a NodeList of the objects meeting the criteria • For instance: • var paragraphs = document.getElementsByTagName (“p”);
  106. Querying the DOM • querySelector( query ) • Selects the

    first instance of element that matches the query • Returns the instance of that element • For instance: • var typeSelector= document.querySelector (“p”); • var idSelector = document.querySelector (“#myElement”); • var classSelector = document.querySelector (“.rowitem”); • var attrSelector = document.querySelector (“input[type=‘radio’]:checked”);
  107. Querying the DOM • querySelectorAll( query ) • Selects all

    instances of items that match the query • Returns staticNodeList meeting the criteria
  108. Querying the DOM • NodeList • Array of HTML/XML Nodes

    in the DOM • Keeps itself up to date • If the DOM changes, the NodeList updates automatically • Items are listed in the order they appear in the DOM
  109. Querying the DOM • staticNodeList • Array of HTML/XML Nodes

    in the DOM • Static content, only contains nodes as of the last query • Items are listed in the order they appear in the DOM
  110. Agenda • Overview • Variables • Objects • Functions •

    Arrays • Intro to DOM? • Browser Objects • Querying DOM • Manipulating DOM • Event Handling • Consuming Data
  111. DOM Manipulation • What is it? • Now that we

    have found what we want, we have to decide what to do with it. • Allows us to add and remove elements from the DOM dynamically (DHTML) • Allows us to modify elements and change styles
  112. DOM Manipulation • Why? • Ultimately, because we can… right?

    • Simple idea: • Add the value of two input boxes and place the result in a div … so that they can’t modify it directly • Complex: • Iterate over the <tr> of a <table> summing the values in multiple columns, then add a new <tfoot> element with a row showing the totals in the correct columns
  113. DOM Manipulation • Before we can manipulate the DOM we

    have to know a few more properties, but to start lets see some terminology (sorry) • Node - Everything in the document is a node! • Attribute Node – inside of an element node • Element Node – in HTML, these are tags <html> • Text Node – any text inside of an element node • Comment Node - <!-- Comment Node -->
  114. DOM Manipulation • Node Relationships • Root Node – outermost

    element node <html> • Parent Node – element node that contains other element nodes • Child Node – element node that has a parent, which is every node except the Root • Sibling Node – element nodes that exist at the same level, like <head> and <body> in the <html> node
  115. DOM Manipulation • Properties • className • Gets or sets

    the class attribute directly • innerHTML • Gets or sets the contents of an element node, including all child elements • innerText • Gets or sets the Text Node Contents of an element node
  116. DOM Manipulation • Properties • style.* • Very nearly every

    single CSS property that can be applied to an Element or Text Node has a corresponding property on the Style Object • In order words, it won’t fit on the slide  • http://www.w3schools.com/jsref/dom_obj_style.as p
  117. DOM Manipulation • Methods • el.appendChild (el) • Add a

    new child node to the element • el.removeChild (el) • Remove the specified child node • el.replaceChild (orig, new) • Replaces the original element with the new element • el.insertBefore (new, existing) • Inserts the element before the child node • el.createAttribute (attr) • Creates an attribute on the element
  118. DOM Manipulation • Methods • el.createElement (s) • Creates an

    element node for the DOM to use, but does not add it to the DOM • Use appendChild() to add the new element into the DOM • el.createTextNode (s) • Creates a text node for the DOM to use, but does not add it to the DOM • el.getAttribute (s) • Gets the value of the specified attribute node for the element node on which its called • el.setAttribute (s, v) • Sets the attribute to the specified value for the element node on which it’s called
  119. DOM Manipulation • Changing the DOM can mean many different

    things • Changing HTML content • Changing CSS styles • Changing HTML attributes • Creating new HTML elements • Removing existing HTML elements • Changing event(handlers) – this happens in the next section
  120. DOM Manipulation • Changing HTML Content • We already saw

    the document.write() method, this is one way to get the job done • The other (better) way is to modify the .innerHTML or innerText property on an element
  121. DOM Manipulation • Changing HTML Content <div id=“dynamic”>I am Static</div>

    <p id=“myP”></p> <script> var el = document.getElementById(“dynamic”); el.innerHTML = “I am Dynamic”; var myP = document.getElementById(“myP”); myP.innerText = “Need some content here”; </script>
  122. DOM Manipulation • Changing CSS Styles • We saw the

    className property, and this is the fastest, simplest way to change it • Don’t forget about transitions and animations when you do this! • You can also use the .style.property to get more granular control
  123. DOM Manipulation • Changing CSS Styles <style> .myClass { font-size:

    40pt; }</style> <div id=“dynamic”>I am Static</div> <p id=“myP”>I am going to disappear</p> <script> var el = document.getElementById(“dynamic”); el.className = “myClass”; var myP = document.getElementById(“myP”); myP.style.display = “none”; </script>
  124. DOM Manipulation • Changing or Adding HTML Attributes • setAttribute()

    is the best way to do this • Provide the attribute name, and a value • If the attribute does not already exist on the element, add it, otherwise update it
  125. DOM Manipulation • Changing or Adding HTML Attributes <input type=“text”

    id=“dynamic” value=“I am a textbox” /> <script> var el = document.getElementById(“dynamic”); el.setAttribute(“type”, “button”); </script>
  126. DOM Manipulation • Creating new HTML Elements • Create the

    element using createElement (s) or createTextNode(s) • Use the appendChild (el) to add it into an element node • It’s important to note that you can add as many nodes as you like, and nest them, but eventually, you have to add the parent to a node element that is structured into the DOM
  127. DOM Manipulation • Creating new HTML Elements <div id=“dynamic” />

    <script> var el = document.getElementById(“dynamic”); var p = document.createElement(“p”); var txt = document.createTextNode(“Hola, Mundo”); p.appendChild(txt); el.appendChild(p) </script>
  128. DOM Manipulation • Removing HTML Elements <div id=“dynamic”> <p>Hola, Mundo</p>

    </div> <script> var el = document.getElementById(“dynamic”); var p = el.querySelector(“p”); el.removeChild(p) </script>
  129. Agenda • Overview • Variables • Objects • Functions •

    Arrays • Intro to DOM? • Browser Objects • Querying DOM • Manipulating DOM • Event Handling • Consuming Data
  130. Event Handling • What is an event? • Delegate method

    stub that allows assignment of a function to execute when triggered • You can defined your own, but that’s outside the scope of the lesson
  131. Event Handling • Common Events • onclick • Triggered when

    the user clicks the element • onload/onunload • Triggered when the user enters or leaves the page and only binds to the window object • onchange • Triggered on input fields when the value changes • onmouseover/onmousemove/onmouseout • Triggered when the mouse moves over the element, or leaves the element
  132. Event Handling • Common Events • onmousedown/onmouseup • Triggered when

    the user clicks the mouse button down, and releases it • onkeydown/onkeypress/onkeyup • Triggered when the user presses and releases a key on the keyboard • onfocus/onblur • Triggered when the control focus is given or taken away from an input field • onsubmit • Triggered when the user submits the form
  133. Event Handling • Just for reference, when you attachEvent or

    addEventListener, remove the “on” portion for the events
  134. Event Handling • Declarative events • Defined by the element

    node as an attribute, as part of the original response • Programmatic/Dynamic Events • Added to the element node to define additional or new functionality
  135. Event Handling • Programmatic/Dynamic Events • Different ways to add

    events • Set it directly • Add an event listener • Different ways to remove events • Set it to null • Remove the event listener
  136. Event Handling • Setting event directly • el.onEvent = function

    () { } • Set onEvent to an anonymous function • el.onEvent = null; • Clear the onEvent delegate
  137. Event Handling • Adding an event listener • el.addEventListener(“click”, function

    () {}); • Add anonymous event handler to the click event • el.addEventListener(“click”, handlerFunc); • Add defined method to the click event, notice no (), so it’s passing the method as a reference • el.removeEventListener(“click”, handlerFunc); • Remove the defined method from the click event
  138. Event Handling • Adding an event listener • Allows you

    to add multiple events into an array of functions that execute in order when the event triggers • Using anonymous functions does not allow you to remove the event, you have to reset the element
  139. Agenda • Overview • Variables • Objects • Functions •

    Arrays • Intro to DOM? • Browser Objects • Querying DOM • Manipulating DOM • Event Handling • Consuming Data
  140. Consuming Data • This is a very big topic, and

    I want to do it justice, but … I need to just hit the highlights • Implications of Consuming data • Retrieving it from somewhere (XMLHTTPRequest) • Recognizing the type of data (JSON, XML) • Parsing and using the data
  141. Consuming Data • XMLHTTPRequest • According to W3C Schools it’s

    “the developer’s dream” • Update a web page without reloading the page • Request data from a server after the page has loaded • Receive data from a server after the page has loaded • Send data to a server in the background
  142. Consuming Data • Why? • As mentioned above, it’s really

    cool… but no seriously • It’s how the web works today, we can lazy load a page by simply dumping a minimal response to the browser, with JavaScript to call additional information asynchronously • By tapping into the XMLHTTPRequest object, you are reaching into the heart of a what a browser really is … a client/server TCP/IP application that typically operates on port 80 using the HTTP protocol
  143. Consuming Data • XDomainRequest • Similar to the XMLHTTPRequest •

    All the same properties and methods as you will see below • Only available in IE 8+, not in any other browsers • Attempts cross-domain async web calls
  144. Consuming Data • Why are cross-domain calls such a big

    deal? • In computing, the same origin policy is an important security concept for a number of browser-side programming languages, such as JavaScript. The policy permits scripts running on pages originating from the same site – a combination of scheme, hostname, and port number – to access each other's methods and properties with no specific restrictions, but prevents access to most methods and properties across pages on different sites. Same origin policy also applies to XMLHttpRequest and to robots.txt.
  145. Consuming Data • XMLHTTPRequest Methods • abort() • Cancel the

    current request for the object • getAllResponseHeaders() • Returns all header information as a string, delimited by CRLF • getResponseHeader(header) • Returns specific header information
  146. Consuming Data • XMLHTTPRequest Methods • open(method, url, isAsync, uname,

    pwd) • Specifies the type of request, the URL, if the request should be handled asynchronously or not, and other optional attributes of a request • send(postdata) • Sends the request off to the server. • Passes the postdata when the method of open() is post. • setRequestHeader(header, value) • Adds a key/value pair to the header to be sent
  147. Consuming Data • XMLHTTPRequest Properties • readyState • Holds the

    status of the XMLHttpRequest. Changes from 0 to 4: • 0: request not initialized • 1: server connection established • 2: request received • 3: processing request • 4: request finished and response is ready
  148. Consuming Data • XMLHTTPRequest Properties • responseText • Returns the

    response data as a string • responseXML • Returns the response data as XML DOM, works for HTML as well • status • Returns the status-number (e.g. "404" for "Not Found" or "200" for "OK") • statusText • Returns the status-text (e.g. "Not Found" or "OK")
  149. Consuming Data • XMLHTTPRequest Events • onerror()* • Raised when

    there is an error that prevents the completion of the cross-domain request. • onload()* • Raised when the object has been completely received from the server. • onprogress()* • Raised when the browser starts receiving data from the server.
  150. Consuming Data • XMLHTTPRequest Events • onreadystatechanged = (function(){}) •

    Stores a function to be called automatically each time the readyState property changes • ontimeout()* • Raised when there is an error that prevents the completion of the request. The stars mean you need to use the addEventListener() method to handle these events
  151. Consuming Data • How does this fit together? • Create

    an instance of XMLHTTPRequest var xhr = new XMLHTTPRequest(); • If you are going to work asynchronously, set a function for the onreadystatechanged that checks the readyState property and does something with the result xhr.onreadystatechanged(function() { if (xhr.readyState == 4 && xhr.status == 200) { document.getElementById(“mygooglediv”).innerHMTL = xhr.responseText; } });
  152. Consuming Data • How does this fit together? • Open

    (prep) the connection to the server. xhr.open(“get”, “https://www.google.com/search?q=xmlhttprequest”, true); xhr.open(“post”, “https://www.google.com/search”, true); • AND … send it! xhr.send(null); xhr.send(“q=xmlhttprequest”);
  153. Consuming Data • How does this fit together? • Just

    in case you missed in, the onreadystatechanged took the response from the server as text, and appended it to the inside of a div
  154. Consuming Data • So now, how do you figure out

    if it’s HTML, XML or JSON? • Check the “Content-Type” header: • application/json • application/xml • text/html • text/xml • text/plain  this one is evil because it means nothing and everything • Trust the source to be the right type (if you own it, you should know what to expect) • Use jQuery or other to determine the type for you
  155. Conclusion • JavaScript is a first class citizen in the

    Application Development world • Has the power an functionality of a language like C# • Syntactically similar to C# • It’s really hard to recap everything we discussed, suffice to say, it’s an awesome language, and we have just hit the tip of this iceberg