Vous êtes sur la page 1sur 184

JavaScript: Second Look

What you might be missing

Deliver Solutions, Deliver Careers, Deliver Results

Agenda
Overview Variables Objects Functions Arrays

Intro to DOM? Browser Objects Querying DOM Manipulating DOM Event Handling Consuming Data

Who I am
MCPD, SharePoint 2010 MCITP , SharePoint 2010 Certified Master Candidate, SharePoint

Passionate about writing code in all forms Passionate about SharePoint

B.E.L.T.
Blog: blogs.askcts.com Email: cloriot@askcts.com LinkedIn: in/coryloriot Twitter: @coryloriot

Who is CTS?

IT professional services firm Established in 1993 200+ employees 33 active clients in various industries $27M Revenue 2012

Mobile

clients

awards

askcts.com

Rayne Hoover Recruiter rhoover@askcts.com (404) 419-0856

.NET / GIS Developer SharePoint Developer

2012 Computer Technology Solutions, Inc.

Lets Start Learning JavaScript

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

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.

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: }

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.

Why?
Advocates of prototype-based programming often argue that classbased 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.

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

Agenda
Overview Variables Objects Functions Arrays

Intro to DOM? Browser Objects Querying DOM Manipulating DOM Event Handling Consuming Data

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

If Programming is the Force

Strongly Typed Languages


C C++ Java C# etc.

Weakly-Typed Languages
JavaScript VBScript etc.

C#?

Variable Declaration
var myVar; var myVar = ; var myVar = 1; var myVar = { 1, 2, 3, 4 };

Variable Naming Rules


1. 2. 3. 4. 5. 6. Cannot start with numbers Cannot have mathematical or logical operators in them (+ - % / < > = || && ) Cannot use punctuation except for _ character ( . , : ; ) myVar.ForFun would assume a ForFun child property of myVar and return undefined Must not contain spaces Cannot use JS keywords (window document string ) Case Sensitive Once you make myVar, dont assign to MyVar or myVAR they arent 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

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.

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

Agenda
Overview Variables Objects Functions Arrays

Intro to DOM? Browser Objects Querying DOM Manipulating DOM Event Handling Consuming Data

Objects
Most of the advanced functionality in JS really requires an understanding of how class definitions work

Objects
A few concepts Dynamic property creation Object Initializer Syntax JSON JavaScript Object Notation

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

Objects
Dynamic property creation
var obj = { }; obj.newProp = my new prop;

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

Objects
Object Initializer Syntax
var obj = { prop: my prop, func: function () { } }; obj.prop = z; obj.func();

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

Objects - JSON
JSON
var obj = { prop: my prop }; obj.prop = z;

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

Objects
So JSON isnt really scary after all. But learning how to use it effectively is going to make more sense in the session on DOM Manipulation

Agenda
Overview Variables Objects Functions Arrays

Intro to DOM? Browser Objects Querying DOM Manipulating DOM Event Handling Consuming Data

Functions
Function are objects, so they can be stored as variables First class citizens in JavaScript

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

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

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

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 dont add the (), it passes the function itself, which can then be executed by reference This follows the Dependency Injection principle

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

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

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

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? Wouldnt that be easier?
var myString = Hello, World; myString.reverse();

Extension Functions/Properties
How? The prototype object is implicit to every object in the language, and everything in the language is an object. Example: 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.
string.prototype.reverse = function () { };

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

Function Scoping
Different scopes Global Scope
Objects declared outside any other scopes are global and accessible to the tighter scopes Objects declared within or passed as arguments are treated as global to all child scopes
Objects declared within a block are only accessible inside that block

Function scope Block scope

Function Scoping
Dont 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

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.

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 dont 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.

Function Scoping
How? Simply add properties and methods into your function Anything declared inside the function will be inaccessible outside the function

Function Scoping
var x = 2000; function get_value() { var y = 13; return y;

// y is inaccessible // outside this method

}
var z = x + y; var z = x + get_value(); // y is undefined // z == 2013

Function Scoping
Why this is cool The contents of the initial function dont have to be empty, and has access to members of the prototype (yes, even before the prototype is defined) Works like a constructor and doesnt leave miscellaneous variables out there as part of the object

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

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());

Agenda
Overview Variables Objects Functions Arrays

Intro to DOM? Browser Objects Querying DOM Manipulating DOM Event Handling Consuming Data

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!

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, dont use the <= comparison to the length, use the < operator

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

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

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

Arrays
The latest version of ECMAScript has new features for arrays, to make them developer friendly Everyone say it Thank you ECMA

Arrays
Three kinds of methods on an array: Mutators modify the contents and structure of the array Accessors do not modify the array, and return some representation of the array
pop, push, reverse, shift, sort, splice, unshift 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

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

Array methods
Mutators pop push reverse shift sort splice unshift

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 ];

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

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 ];

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 ];

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

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

sort (fn(a, b))


Numbers sorted alphabetically dont work well, since 4 comes before 5, but alphabetically 40 would also come before 5 Because its 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 ];

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 ];

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 ];

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 ];

Array Methods
Accessors
concat join slice indexOf lastIndexOf

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 ];

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

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)

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)

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];

Array Methods
Iterators forEach every some filter map reduce reduceRight

To start
The typical method signature for an iterator is as follows:
function(element, index, array){}

But that doesnt 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){}

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

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

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

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

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

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

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

Agenda
Overview Variables Objects Functions Arrays

Intro to DOM? Browser Objects Querying DOM Manipulating DOM Event Handling Consuming Data

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

What is the DOM?


Time for a good question, and an important note What is the difference between HTML and XML?

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

What is the DOM?


XHTML eXtensible HyperText Markup Language Follows more rigid rules for document components Capable of parsing with an XML DOM parser

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

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

Agenda
Overview Variables Objects Functions Arrays

Intro to DOM? Browser Objects Querying DOM Manipulating DOM Event Handling Consuming Data

Browser Objects
window document location navigator history screen

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

Browser Objects
window: Common properties innerHeight/innerWidth name
Get or set the size of the content space available
Get or set the name of a window, helpful if you have a bunch (see window.open()) The window object that opened or created the current window object

opener

Browser Objects
window: Common properties pageXOffset/pageYOffset
Get or set the number of pixels the scrollbars have moved in the horizontal or vertical direction from the start of the document
Get or set the number of pixels that the browser is in relation to the left and top edges of the primary monitor Get or set the status bar text on the browser

screenLeft/screen && screenTop/screen status

Browser Objects
window: Common functions alert(s) blur()/focus()
Provides a modal dialog to the screen with a message and an OK button Remove or Set focus on the window (bring the browser window to the front or send it to the back set () specifies a function that will execute every N milliseconds with no defined end clear () stops the interval defined by set()

clearInterval(id)/setInterval(f, n)

Browser Objects
window: Common functions clearTimeOut(id)/setTimeOut(f, n)
set () specifies a function that will execute only once after N milliseconds have passed clear() stops the set() from execution if before the N milliseconds Closes the window object its called on Displays a dialog box with OK and Cancel options Returns the result of true if OK or false if Cancel

close()

confirm(s)

Browser Objects
window: Common functions moveBy(x, y)/moveTo(x, y)
By: moves in relation to current position To: moves to a specific location on the screen (regardless of current location) Creates a new browser window, allowing arguments to specify the functionality available in the window, and the URL for that window Calls the print function on the browser

open(url, name, specs, replace) print()

Browser Objects
window: Common functions prompt(s) resizeBy(w, h)/resizeTo(w, h) scrollBy(x, y)/scrollTo(x, y)
Displays a dialog with a message and an field to retrieve user input, returns the value provided by the user Resizes the browser window to the specified width and height By: will only move the bottom right to change the size of the browser By: will move the scroll bar the specified number of pixels relative to the current scroll location in the document To: will move the scroll bar to the specified point in the document directly, regardless of the current position

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

Browser Objects
document: Common properties anchors

body

Collection of <a name=*> elements in the document Returns the <body> element in the document

cookie

domain forms

Returns all the key/value pairs in the document


The DNS name of the server that provided the document Collection of <form> elements in the document

Browser Objects
document: Common properties images

links

Collection of <img> elements in the document Collection of <a href=*> and <area> elements in the document

referrer title url

The url of the document that loaded the current document


Gets or sets the title of the document from the <title /> element Returns the full url of the document from the address bar

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

Browser Objects
document: Common functions close()/open(mimetype, replace) write(s)/writeln(s)
Open or close an output stream to collect output from .write() or .writeln() 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

Browser Objects
location Contains information about the current url Not W3C compliant, but supported in all major browsers

Browser Objects
location: Common properties hash host/hostname/port
Returns the anchor portion of a URL host: returns the host and port of the URL hostname: only returns the host port: only returns the port

href

protocol search

Returns the entire URL with query string


Returns the protocol, HTTP/HTTPS Returns the query string of the URL

Browser Objects
location: Common functions assign(url) reload(force) replace(url)
Loads a new document in place of the current one Updates history by appending the new document Causes the browser to reload the document with the initial state force == true: performs a get operation on the current URL Loads a new document in place of the current one Replaces the current document in the history (cant hit the back button)

Browser Objects
navigator Contains information about the browser, such as current state and platform Not W3C compliant, but supported by all major browsers

Browser Objects
navigator: Common properties appCodeName appName
The class id (namespace) name of the browser
The common name of the browser The version number of the browser

appVersion

cookieEnabled

Determines if cookies are enabled in the browser

Browser Objects
navigator: Common properties onLine platform
Returns true if the browser is online or false if not
Returns the platform for which the browser was compiled Returns the user-agent string sent by the browser to the server

userAgent

Browser Objects
navigator: functions javaEnabled()
Returns true if the browser allows Java execution or false if not

taintEnabled()
Returns true if the browser allows data tainting or false if not

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

Browser Objects
history: Properties and Functions length back()
Total number of items in the browser history Loads the previous URL in the history Loads the next (if any) URL in the history Loads a specific URL in the history based on the N index provided

forward() go(n)

Browser Objects
screen Provides information about the user desktop workspace Not W3C Compliant, but supported by all major browsers

Browser Objects
screen: Properties availHeight/availWidth colorDepth
The height and width of the screen, not including the windows taskbar The bit depth of color palette for displaying images Return the total height and width of the screen (including taskbar) The color resolution(bits per pixel) of the screen

height/width pixelDepth

Agenda
Overview Variables Objects Functions Arrays

Intro to DOM? Browser Objects Querying DOM Manipulating DOM Event Handling Consuming Data

Querying the DOM


Kind of like CSS Selectors: Select by ID Select by Type (tag name) Select by Class Select by Attribute

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

Querying the DOM


In order to manipulate the DOM with JavaScript, you have to find what you are looking for

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

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

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

Querying the DOM


querySelectorAll( query ) Selects all instances of items that match the query Returns staticNodeList meeting the criteria

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

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

Agenda
Overview Variables Objects Functions Arrays

Intro to DOM? Browser Objects Querying DOM Manipulating DOM Event Handling Consuming Data

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

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

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

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

DOM Manipulation
Properties className innerHTML innerText
Gets or sets the class attribute directly
Gets or sets the contents of an element node, including all child elements Gets or sets the Text Node Contents of an element node

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 wont fit on the slide http://www.w3schools.com/jsref/dom_obj_style.as p

DOM Manipulation
Methods el.appendChild (el)

el.removeChild (el)

Add a new child node to the element Remove the specified child node

el.replaceChild (orig, new)

el.insertBefore (new, existing) el.createAttribute (attr)

Replaces the original element with the new element


Inserts the element before the child node Creates an attribute on the element

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 Creates a text node for the DOM to use, but does not add it to the DOM Gets the value of the specified attribute node for the element node on which its called

el.createTextNode (s)

el.getAttribute (s)

el.setAttribute (s, v)

Sets the attribute to the specified value for the element node on which its called

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

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

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>

DOM Manipulation
Changing CSS Styles We saw the className property, and this is the fastest, simplest way to change it
Dont forget about transitions and animations when you do this!

You can also use the .style.property to get more granular control

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>

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

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>

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

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>

DOM Manipulation
Removing HTML Elements Use the removeChild(el) on the parent node to remove the element

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>

Agenda
Overview Variables Objects Functions Arrays

Intro to DOM? Browser Objects Querying DOM Manipulating DOM Event Handling Consuming Data

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 thats outside the scope of the lesson

Event Handling
Common Events onclick

onload/onunload
onchange

Triggered when the user clicks the element Triggered when the user enters or leaves the page and only binds to the window object Triggered on input fields when the value changes Triggered when the mouse moves over the element, or leaves the element

onmouseover/onmousemove/onmouseout

Event Handling
Common Events onmousedown/onmouseup onkeydown/onkeypress/onkeyup onfocus/onblur onsubmit
Triggered when the user clicks the mouse button down, and releases it Triggered when the user presses and releases a key on the keyboard Triggered when the control focus is given or taken away from an input field

Triggered when the user submits the form

Event Handling
Just for reference, when you attachEvent or addEventListener, remove the on portion for the events

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

Event Handling
Declarative events <input type=button onclick=myFunction(); /> <script> function myFunction() { alert(Hola Mundo); } </script>

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

Event Handling
Setting event directly el.onEvent = function () { }
Set onEvent to an anonymous function

el.onEvent = null;
Clear the onEvent delegate

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 its passing the method as a reference

el.removeEventListener(click, handlerFunc);
Remove the defined method from the click event

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

Agenda
Overview Variables Objects Functions Arrays

Intro to DOM? Browser Objects Querying DOM Manipulating DOM Event Handling Consuming Data

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

Consuming Data
XMLHTTPRequest According to W3C Schools its the developers 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

Consuming Data
Why? As mentioned above, its really cool but no seriously Its 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

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

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.

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

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)

setRequestHeader(header, value)

Sends the request off to the server. Passes the postdata when the method of open() is post. Adds a key/value pair to the header to be sent

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

Consuming Data
XMLHTTPRequest Properties responseText

responseXML
status

Returns the response data as a string Returns the response data as XML DOM, works for HTML as well

statusText

Returns the status-number (e.g. "404" for "Not Found" or "200" for "OK")
Returns the status-text (e.g. "Not Found" or "OK")

Consuming Data
XMLHTTPRequest Events onerror()* onload()*
Raised when there is an error that prevents the completion of the cross-domain request. Raised when the object has been completely received from the server.
Raised when the browser starts receiving data from the server.

onprogress()*

Consuming Data
XMLHTTPRequest Events onreadystatechanged = (function(){}) ontimeout()*
Stores a function to be called automatically each time the readyState property changes 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

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

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

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

Consuming Data
So now, how do you figure out if its 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

Demo
Lets build a JS One-Page App!

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#

Its really hard to recap everything we discussed, suffice to say, its and awesome language, and we have just hit the tip of this iceberg

askcts.com

Rayne Hoover Recruiter rhoover@askcts.com (404) 419-0856

.NET / GIS Developer SharePoint Developer

2012 Computer Technology Solutions, Inc.

askcts.com

Cory Loriot Senior Consultant cloriot@askts.com 404.419.0842

2012 Computer Technology Solutions, Inc.

Vous aimerez peut-être aussi