175
JavaScript: Second Look What you might be missing… Deliver Solutions, Deliver Careers, Deliver Results 

JavaScript - A Second Look

Embed Size (px)

Citation preview

Page 1: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 1/184

JavaScript: Second

LookWhat you might be missing… 

Deliver Solutions, Deliver Careers, Deliver Results 

Page 2: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 2/184

Agenda

Overview• Variables

• Objects

• Functions• Arrays

Intro to DOM?• Browser Objects

• Querying DOM

• ManipulatingDOM

• Event Handling

• Consuming Data

Page 3: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 3/184

Who I am … • MCPD, SharePoint 2010

• MCITP, SharePoint 2010

• Certified Master Candidate, SharePoint

• Passionate about writing code

… in all forms 

• Passionate about SharePoint…

Page 5: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 5/184

Who is CTS?• IT professional services firm•

Established in 1993• 200+ employees• 33 active clients in various industries• $27M Revenue – 2012

Mobile

Page 6: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 6/184

clients 

Page 7: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 7/184

awards

Page 8: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 8/184© 2012 Computer Technology Solutions, Inc.

askcts.com

Rayne [email protected](404) 419-0856

• .NET / GIS Developer

• SharePoint Developer

Page 9: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 9/184

Lets Start Learning JavaScript

Page 10: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 10/184

Overview – Brief History

1995 – Browser Client Scripting Langua• 1997 – Formalized to ECMAScript

• 2009 – Node.js moves JavaScript to Ser

Processing• 2012 – Microsoft moves JavaScript to C

Application Development – out of the b

Page 11: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 11/184

Overview - Characteristics• Not Object Oriented

Though it does have characteristics, you could never implemof OOP Design Principles• Prototype-based language

• Object Emulation, no Inheritance (more on this in a few slide• Dynamic

• You can append properties to any object, because there is nobject declaration

• Weakly-Typed• You initialize variables as the “Variant” or “var” type, which is

base for all type.• Context determines the type and applicability of operators t

Page 12: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 12/184

Overview - Characteristics• First Class functions

• All functions operate as pointers on a stack, just object, and follow the same rules as any object iJavaScript

• For instance, you can add a property to a functiothere can be good reasons for doing so  

• K&R style syntax, with many of the same construct• if … else • try { } catch {}• switch { case: }

Page 13: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 13/184

What the heck?• Prototype-based programming is a style of object-oriented pro

which classes are not present, and behavior reuse (known as inclass-based languages) is performed via a process of cloning eobjects that serve as prototypes. This model can also be knownprototype-oriented or instance-based programming. Delegatiolanguage feature that supports prototype-based programming

• The first prototype-oriented programming language was Self dDavid Ungar and Randall Smith in the mid-1980s to research toobject-oriented language design. Since the late 1990s, the clasparadigm has grown increasingly popular. Some current prototlanguages are ECMAScript (and its implementations JavaScript,Flash's ActionScript 1.0), Cecil, NewtonScript, Io, MOO, REBOL,

Page 14: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 14/184

Why?• Advocates of prototype-based programming often argue

based languages encourage a model of development thafirst on the taxonomy and relationships between classes.• In contrast, prototype-based programming is seen as enc

the programmer to focus on the behavior of some set of and only later worry about classifying these objects into aobjects that are later used in a fashion similar to classes.

• As such, many prototype-based systems encourage the aprototypes during run-time, whereas only very few class-object-oriented systems allow classes to be altered duringexecution of a program.

Page 15: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 15/184

Code First …

JavaScript lets you build as you go… • A nice modular design may include JS f

build on each other, adding properties methods to “base” or prototype classesneeded to extend the functionality and changing needs

Page 16: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 16/184

Agenda

• Overview

• Variables

• Objects

Functions• Arrays

• Intro to DOM?

• Browser Objects

• Querying DOM

ManipulatingDOM

• Event Handling

• Consuming Data

Page 17: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 17/184

Variables• As mentioned… they are weakly typed 

• Store information for the duration of thlife in the browser, or in Windows Apps,the “screen” 

• Common types:• String, number, Boolean, array, object

undefined

Page 18: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 18/184

If Programming is the “Force” …

Page 19: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 19/184

Strongly Typed Languages

• C

• C++

• Java

C#• … etc. 

Page 20: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 20/184

Weakly-Typed Languages

• JavaScript

• VBScript

• … etc. 

• … C#? 

Page 21: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 21/184

Variable Declaration

• var myVar;

• var myVar = “”; 

• var myVar = 1;

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

Page 22: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 22/184

Variable Naming Rules1. Cannot start with numbers2. 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 undefined  

4. Must not contain spaces5. Cannot use JS keywords (window document string )6. Case Sensitive …

• Once you make myVar, don‟t assign to MyVar or myVAR … they arething

• And no … there is no Option Explicit on the web … but there is “useECMAScript 5 specification

• Simply add “use strict” as a string at the top of your code, or in you

Page 23: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 23/184

A moment for “Implicit Globals• An implicit global is a variable that is used, but not declar

current scope• Var x = 10; function f () { x++; }• f() assumes the existence of x because it is not declare

• Dangers?• Yes, large projects with many code files can share impli

without realizing• If the implicit global is not declared, you get a reference

• Is it ok to use?• Yes. Just dangerous.

Page 24: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 24/184

And… back to Variables 

• Variables can be anything at any time

• Be careful how you use them

• If you are concerned with making mista

strict

Page 25: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 25/184

Agenda

• Overview

• Variables

• Objects

Functions• Arrays

• Intro to DOM?

• Browser Objects

• Querying DOM

ManipulatingDOM

• Event Handling

Consuming Data

Page 26: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 26/184

Objects

• Most of the advanced functionality in JSrequires an understanding of how classdefinitions work

Page 27: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 27/184

Objects

• A few concepts

• Dynamic property creation

• Object Initializer Syntax

JSON – JavaScript Object Notation

Page 28: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 28/184

Objects

• Dynamic property creation

• If you have an object, and you want ita new property, just add the propertygive it a value

• Not a structured approach

b

Page 29: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 29/184

Objects

• Dynamic property creation

var obj = { };

obj.newProp = “my new prop”; 

Ob

Page 30: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 30/184

Objects• Object Initializer Syntax

• Provide properties during the initializathe object

• Allows quotes on the property names

• Allows for methods (anonymous funcassigned to a property)

• This is a structured approach

Obj

Page 31: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 31/184

Objects• Object Initializer Syntax

var obj = {

prop: “my prop”, 

func: function () { … } }; 

obj.prop = “z”; 

obj.func();

Obj JSON

Page 32: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 32/184

Objects - JSON

• JSON

• Same concept as Object Initializer

• Does not allow for methods in the de

Requires quotes around the property • Structured and standards compliant

Obj t JSON

Page 33: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 33/184

Objects - JSON

• JSON

var obj = {

“prop”: “my prop” 

}; 

obj.prop = “z”; 

Obj t JSON

Page 34: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 34/184

Objects - JSON• Commonly used as a return value to se

information from a web service call orasynchronous post back

• You would assign this to an object to us

modifying the DOM

{ “prop”: “my prop”; }; 

Obj t

Page 35: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 35/184

Objects

• So… JSON isn‟t really scary after all. 

• But learning how to use it effectively is gmake more sense in the session on DOManipulation

A d

Page 36: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 36/184

Agenda

• Overview

• Variables

• Objects

Functions• Arrays

• Intro to DOM?

• Browser Objects

• Querying DOM

ManipulatingDOM

• Event Handling

Consuming Data

F ti

Page 37: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 37/184

Functions

• Function are objects, so they can be stovariables

• First class citizens in JavaScript

F ti B i Ch t i ti

Page 38: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 38/184

Functions – Basic Characteristic• Callable behaviors

• They can be declared in one place, containfunctionality, and be invoked in multiple plac• Implemented as objects

• Everything is an object in JS, but function is t

object that can be invoked (which gets interewhen we get to classes)• Pass as pointers to variables, or as argument

functions

F nctions A fe t pes

Page 39: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 39/184

Functions – A few types• Declared (static) functions are the tradition

format• function x () { alert(„Hello World‟); };

• Anonymous functions are nice for single umethods, or for event handling• var y = function () { alert(„Hello World‟);

• Immediate functions are self executing anofunctions

Functions Arguments

Page 40: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 40/184

Functions – Arguments

• Arguments are not only defined by the sig

of the function, but by the function call• This is the nature of a prototype language

have to assume the calling point could giv

anything• “arguments” is a keyword/object that cont

array of all the arguments passed to the fu

Passing functions as paramete

Page 41: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 41/184

Passing functions as paramete

• Remember the order of execution

• If you pass a function using the (), it will exthe function, and pass the return value as argument

• If you don‟t add the (), it passes the functiowhich can then be executed by reference

• This follows the Dependency Injection p

Functions vs Methods

Page 42: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 42/184

Functions vs. Methods• Standard Definition, a function does something

returns a value, a method does something but return a value• In JS, that definition is wrong. There are only fu

and they may or may not implicitly return anyt(although technically there is always a return va

• So… what is a method? • A method is an anonymous or declared func

is the property of an object … it may or may return something

Extension Functions/Properties

Page 43: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 43/184

Extension Functions/Properties• Modifying objects to include new function

all existing “instances” of the object • Remember, there are no class definitions

classes that are cloned.

So you have to modify the definition of tcloned object

• If you just add a property to the base, it not affect existing instances, or future in

Extension Properties

Page 44: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 44/184

Extension Properties

• We can extend our own objects

• We can extend objects that belong to tsystem, such as Window and Documen

• We can extend type based objects, suchstring and number

Extension Functions/Properties

Page 45: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 45/184

Extension Functions/Properties• Why?

What if you needed a means to perform a unifooperation on a type, such as reversing the contestring.

• You would normally write a method, and pass th• What if you could add the reverse method to ev

• var myString = “Hello, World”; • myString.reverse();

• Wouldn‟t that be easier? 

Extension Functions/Properties

Page 46: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 46/184

Extension Functions/Properties• How?

The prototype object is implicit to every objelanguage, and everything in the language is object.

• Example:• string.prototype.reverse = function () { };

• Call the prototype object on the object you wmodify, then use the „.‟ operator to append thproperty/method name. use the gets operatdefine the functionality or default value.

Function Scoping

Page 47: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 47/184

Function Scoping

• Closest thing to encapsulation that Java

has available

• Basic guideline, variables created insidemethod cannot be utilized outside that

• Use this as a means to manage accessibvariables and functions

Function Scoping

Page 48: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 48/184

Function Scoping• Different scopes

Global Scope• Objects declared outside any other scopes are

accessible to the tighter scopes

• Function scope• Objects declared within or passed as argument

treated as global to all child scopes• Block scope

• Objects declared within a block are only accessthat block

Function Scoping

Page 49: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 49/184

Function Scoping

• Don‟t confuse scope with the following ke

in C#• public, private, protected

• There is no way to grant outside entities a

objects that are internally scoped• Well, almost no way, you can return it

• This grants access to the value, not to th

Function Scoping

Page 50: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 50/184

Function Scoping

• Functions within functions are scoped o

that function• Functions still follow the rules though, a

immediate function will still execute

immediately when it is reached in the fucall.

Function Scoping

Page 51: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 51/184

Function Scoping• Why?

• Function scoping is the closest thing JavaScriencapsulation.

• If you are building a very large program, utilscoping can simplify your code so that you d

bombard developers with the complexity of y• For instance jQuery does a lot more under th

than we see through the available functions.

Function Scoping

Page 52: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 52/184

Function Scoping

• How?

• Simply add properties and methods infunction

• Anything declared inside the functioninaccessible outside the function

Function Scoping

Page 53: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 53/184

Function Scopingvar x = 2000;

function get_value() {

var y = 13; // y is inacces

// outside this

return y;

}

var z = x + y; // y is undefin

var z = x + get_value(); // z == 2013

Function Scoping

Page 54: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 54/184

Function Scoping• Why this is cool… 

• The contents of the initial function don‟t be empty, and has access to members oprototype (yes, even before the prototypdefined)

• Works like a constructor  and doesn‟t “miscellaneous” variables out there as paobject

Module Pattern

Page 55: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 55/184

Module Pattern

• Setting a var to the return value of an imm

function.• Interesting pattern, allows you to define an

immediate function that returns an object

functionality from the immediate function• Basically a constructor and object definitio

Module Pattern

Page 56: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 56/184

Module Patternvar obj = (function() {

var a = 1, b = 2, c = 3;

return {x: a,y: b,

product: function() {

return a*b*c;

}};

})();

// all of these will workalert(obj.x);

alert(obj.y);

alert(obj.product());

Agenda

Page 57: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 57/184

Agenda

• Overview

• Variables

• Objects

• Functions

• Arrays

• Intro to DOM?

• Browser Objects

• Querying DOM

• ManipulatingDOM

• Event Handling

C i D t

Arrays

Page 58: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 58/184

Arrays• What is an array?

• An object that has multiple values thaaccessible through an indexer

• In JS, arrays are always arrays of objec

of a single type necessarily• Because everything is an object in JS,

anything can go in an array, even func

Arrays

Page 59: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 59/184

Arrays• Important Notes:

• JS Arrays use a zero-base indexer, therefore, ary[0] is thelement, and ary[1] is the second.

• However … the length() method returns arrays using nocounting practice, so an array with 5 elements will retuthe length(), but the last element will be ary[4].

• If you overflow the boundaries of the array, you will get

• If you are iterating through the array, don‟t use the <= to the length, use the < operator

Arrays

Page 60: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 60/184

Arrays• How to declare an array:

var ary = [ 1, 2, 3, 4 ];

• How to use the array:for (var i = 0; i < ary.length{

alert(ary[i]);

}

Multi-Dimensional Arrays

Page 61: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 61/184

Multi Dimensional Arrays

• An “Array of Arrays” is the best way to t

• You create an array which has elementsare arrays

• If the child elements do not all have the

length, this is called a Jagged Array

Multi-Dimensional Arrays

Page 62: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 62/184

u t e s o a ays• 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

Page 63: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 63/184

y

• The latest version of ECMAScript has ne

features for arrays, to make them develfriendly

• Everyone say it… Thank you ECMA …

Arrays

Page 64: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 64/184

y• Three kinds of methods on an array:

• Mutators–

modify the contents and structure of• pop, push, reverse, shift, sort, splice, unshift

• Accessors – do not modify the array, and return representation of the array• concat, join, slice, indexOf, lastIndexOf 

Iterators – provide a method as an argument to executed against every element in the array (as it is called)• forEach, every, some, filter, map, reduce, reduceRigh

Arrays

Page 65: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 65/184

y• Methods are either mutable or immutable

Mutable methods will modify the contents ofin place• Immutable methods will not modify the array

but return a new instance of the array• Mutators – Mutable• Accessors – Immutable• Iterators – Mutable to the Elements of the array

to the array itself 

Array methods

Page 66: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 66/184

y• Mutators

pop• push• reverse• shift• sort• splice• unshift

pop()

Page 67: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 67/184

p p()• 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()

Page 68: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 68/184

p ()

• Adds new elements to the end of an ar

• Returns the new length of the array

• Works to make the array into a stack or

var fib = [ 0, 1, 1, 2, 3, 5, 8, 13

alert(fib.push(21)); // returns 9

reverse()

Page 69: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 69/184

• Reverse the items in the array in the exa

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

Page 70: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 70/184

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

Page 71: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 71/184

• Sorts the items in alphabetical order asc

var people = [“John”,“Aaron”,“Zoe”,“Ca

alert(people.sort().reverse());

// people == [“Aaron”,“Carol”,“John”,“

sort().reverse()

Page 72: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 72/184

• Sorts the items in alphabetical order

descending

var people = [“John”,“Aaron”,“Zoe”,“Ca

alert(people.sort().reverse());// people == [“Zoe”,“John”,“Carol”,“Aa

sort (fn(a, b))

Page 73: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 73/184

• Numbers sorted alphabetically don‟t work well, sincomes before 5, but alphabetically 40 would also c

before 5• Because it‟s literally comparing the ASCII numbe

first character• You can resolve this, by passing a function to the s

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

Page 74: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 74/184

• What about descending?

• Simply reverse a and b in the calculatio

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 , […]) 

Page 75: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 75/184

• Inserts elements into the array starting at the index provid• If remove is > 0, then it will overwrite that many elements

increasing the size of the array• The return value is an array of items removed from the ar

length of remove  • Last arguments are the items to insert into the array, as m

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,

// numbers == [ 10, 4, 7, 8, 12, 66, 0 ];

unshift()

Page 76: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 76/184

• Adds an element to the beginning of the a•

Kind of like the reverse of shift that pops frfront• 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

Page 77: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 77/184

• Accessors• concat•  join

• slice

• indexOf 

• lastIndexOf 

concat()

Page 78: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 78/184

• Merges the contents of multiple arrays, taking array objecparameters

• Arrays are appended into the calling array in the order thas 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()

Page 79: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 79/184

• Joins all of the elements in the array into astring, comma separated

• Important to remember, it does not add thtogether, it concatenates them. Even whenare numbers

var fib = [ 0, 1, 1, 2, 3, 5, 8, 13 ];

alert(fib.join()); // == 0,1,1,2,3,5,8,1

alert(fib.toString()); // == 0,1,1,2,3,5

indexOf()

Page 80: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 80/184

• Search the array for an element and ret

index location (zero-based) of the first iin the array

• Great for finding that lost element …

var fib = [ 0, 1, 1, 2, 3, 5, 8, 13

alert(fib.indexOf(1)); // == 1 (seco

lastIndexOf()

Page 81: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 81/184

• Search the array backwards for an elem

return the index location (zero-based) olast instance in the array

var fib = [ 0, 1, 1, 2, 3, 5, 8, 13 alert(fib.lastIndexOf(1)); // == 2 (

slice(start, end)

Page 82: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 82/184

• Extracts selected elements in a sequence f

array• Note: it will go from the start index to the

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

Page 83: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 83/184

• Iterators•

forEach• every• some• filter• map• reduce• reduceRight

To start

Page 84: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 84/184

• The typical method signature for an iter

as follows:function(element, index, array){}

• But that doesn‟t mean we have to use athem, as long as we know how to use thright. (and we can use arguments to picthe other two if we need them)

function(e){}

forEach()

Page 85: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 85/184

• Calls a function for every element in the a

Possible to change the contents of the elethe array in place

function doIt (element, index, array){

alert(element + “ @ “ + index); }

ary.forEach(doIt);

every()

Page 86: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 86/184

• Returns true value to specify if all conte

the array meet a given condition in the function, otherwise false

function checkIt (el){

return el >= 10;

}

ary.every(checkIt);

some()

Page 87: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 87/184

• Returns true value to specify if any cont

the array meet a given condition in the function, otherwise false

function checkIt (el){

return el >= 10;

}

ary.some(checkIt); 

filter()

Page 88: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 88/184

• Returns a new array containing all of the e

that meet the specified criteria• Like the select keyword in Linq

function checkIt (el){

return el >= 10;}

ary.filter(checkIt); 

map()

Page 89: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 89/184

• Projects a new list of whatever return type is specified out from the res• 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()

Page 90: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 90/184

• Iterate the elements of the array, performing an operationprevious and next elements, returning a value that is com

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

Page 91: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 91/184

• Iterate the elements of the array, performing an opon the previous and next elements, returning a val

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

ary.reduceRight(function (a, b) {

return a.concat(b);

});

Agenda

Page 92: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 92/184

• Overview

• Variables• Objects

• Functions

• Arrays

• Intro to DOM?

• Browser Objects• Querying DOM

• Manipulating

DOM• Event Handling

• Consuming Data

What is the DOM?

Page 93: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 93/184

• Document Object Model

• A model, representing the HTML Doc• Similar to XML DOM?

• No… exactly the same, pretty much 

• C# .Net XPath is a congruent topic

What is the DOM?

Page 94: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 94/184

• Time for a good question, and an impo

note• What is the difference between HTML

XML?

What is the DOM?HTML

Page 95: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 95/184

• HTML• HyperText Markup Language

• The language of the web, interpreted by browsers• Static pre-defined elements with very few rules for stru

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

Page 96: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 96/184

• XHTML

• eXtensible HyperText Markup Languag• Follows more rigid rules for documen

components

• Capable of parsing with an XML DOM

What is the DOM?

Page 97: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 97/184

• Important Note:

• You should always structure your docuas XHTML because they will be easierparse and find information using Java

and the DOM

What is the DOM?O l t thi

Page 98: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 98/184

• One last thing …

You might hear the term DHTML• This stands for Dynamic HTML

• Literally: JavaScript DOM Manipulation to adremove elements from the DOM which may

not have existed in the Response from the se• We will learn more about this concept in this

Agenda

Page 99: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 99/184

• Overview

• Variables• Objects

• Functions

• Arrays

• Intro to DOM?

• Browser Objects• Querying DOM

• Manipulating

DOM• Event Handling

• Consuming Data

Browser Objectsd

Page 100: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 100/184

• window

• document• location

• navigator

• history

• screen

Browser Objects• window

Page 101: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 101/184

• 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 <iframelements, the browser has one window objeceach  

Page 102: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 102/184

Browser Objects• window: Common properties

Page 103: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 103/184

• window: Common properties• pageXOffset/pageYOffset

• Get or set the number of pixels the scrollbars hin the horizontal or vertical direction from the sdocument

• screenLeft/screen && screenTop/screen•

Get or set the number of pixels that the browserelation to the left and top edges of the primar

• status• Get or set the status bar text on the browser

Browser Objects• window: Common functions

Page 104: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 104/184

window: Common functions• alert(s)

Provides a modal dialog to the screen with a message anbutton

• blur()/focus()• Remove or Set focus on the window (bring the browser w

the front or send it to the back

• clearInterval(id)/setInterval(f, n)• set () specifies a function that will execute every N millise

no defined end• clear () stops the interval defined by set()

Browser Objects• window: Common functions

Page 105: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 105/184

window: Common functions• clearTimeOut(id)/setTimeOut(f, n)

set () specifies a function that will execute only once aftemilliseconds have passed• clear() stops the set() from execution if before the N milli

• close()• Closes the window object it‟s called on 

• confirm(s)• Displays a dialog box with OK and Cancel options• Returns the result of true if OK or false if Cancel

Browser Objects• window: Common functions

Page 106: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 106/184

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

location)

• open(url, name, specs, replace)• Creates a new browser window, allowing arguments to s

functionality available in the window, and the URL for tha

• print()• Calls the print function on the browser

Browser Objects• window: Common functions

Page 107: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 107/184

window: Common functions• prompt(s)

Displays a dialog with a message and an field to retrieve returns the value provided by the user

• resizeBy(w, h)/resizeTo(w, h)• Resizes the browser window to the specified width and h• By: will only move the bottom right to change the size of

• scrollBy(x, y)/scrollTo(x, y)• By: will move the scroll bar the specified number of pixel

the current scroll location in the document• To: will move the scroll bar to the specified point in the d

directly, regardless of the current position

Browser Objects• document

Page 108: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 108/184

• document

• JS representation of the HTML documloaded into the browser

• Provides access to all HTML elements

page• All the properties of node included

Browser Objects• document: Common properties

Page 109: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 109/184

p p• 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 documen

• forms• Collection of <form> elements in the document

Browser Objects• document: Common properties

Page 110: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 110/184

p p• images

Collection of <img> elements in the document• links

• Collection of <a href =“*”> and <area> elements in the d

• referrer• The url of the document that loaded the current docume

title• Gets or sets the title of the document from the <title /> e

• url• Returns the full url of the document from the address ba

Browser Objects• document.readyState

Page 111: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 111/184

document.readyState• Returns a value based on the current status o

document• uninitialized - Has not started loading yet• loading - Is loading• interactive - Has loaded enough and the user c

with it• complete - Fully loaded

• Not W3C Compliant, but supported by all mbrowsers

Browser Objects• document: Common functions

Page 112: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 112/184

document: Common functions• close()/open(mimetype, replace)

• Open or close an output stream to collect ofrom .write() or .writeln()

• write(s)/writeln(s)• Provide new content for output to the docu

specified by the most recent .open() comma• writeln() adds a newline character at the and

string

Browser Objects• location

Page 113: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 113/184

• location

• Contains information about the curren• Not W3C compliant, but supported in

major browsers

Browser Objects• location: Common properties

h h

Page 114: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 114/184

• hash• Returns the anchor portion of a URL

• host/hostname/port• host: returns the host and port of the URL• hostname: only returns the host• port: only returns the port

• href • Returns the entire URL with query string

• protocol• Returns the protocol, HTTP/HTTPS

• search• Returns the query string of the URL

Browser Objects• location: Common functions

Page 115: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 115/184

• assign(url)•

Loads a new document in place of the current one• Updates history by appending the new document

• reload(force)• Causes the browser to reload the document with the init• force == true: performs a get operation on the current U

• replace(url)• Loads a new document in place of the current one• Replaces the current document in the history (can‟t hit th

button)

Browser Objects• navigator

Page 116: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 116/184

navigator

•Contains information about the browsas current state and platform

• Not W3C compliant, but supported b

major browsers

Browser Objects• navigator: Common properties

Page 117: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 117/184

g p p• appCodeName

• The class id (namespace) name of the browser• appName

• The common name of the browser

• appVersion• The version number of the browser

• cookieEnabled• Determines if cookies are enabled in the brows

Browser Objects• navigator: Common properties

Page 118: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 118/184

g p p• onLine

• Returns true if the browser is online or false• platform

• Returns the platform for which the browser compiled

• userAgent• Returns the user-agent string sent by the br

the server

Browser Objects• navigator: functions

Page 119: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 119/184

navigator: functions

 javaEnabled()• Returns true if the browser allows Java ex

or false if not

taintEnabled()• Returns true if the browser allows data ta

false if not

Browser Objects• history

Page 120: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 120/184

history

Accesses the browser history• Allows you to move backward and fo

the history

• Not W3C compliant, but supported bmajor browsers

Browser Objects• history: Properties and Functions

l h

Page 121: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 121/184

• length•

Total number of items in the browser history• back()

• Loads the previous URL in the history

• forward()• Loads the next (if any) URL in the history

• go(n)• Loads a specific URL in the history based on the N i

provided

Browser Objects• screen

Page 122: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 122/184

screen

Provides information about the user dworkspace

• Not W3C Compliant, but supported b

major browsers

Page 123: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 123/184

Agenda• Overview • Intro to DOM?

Page 124: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 124/184

Variables• Objects

• Functions

• Arrays

Browser Objects• Querying DOM

• Manipulating

DOM• Event Handling

• Consuming Data

Querying the DOM• Kind of like CSS Selectors:

Page 125: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 125/184

Select by ID• Select by Type (tag name)

• Select by Class

• Select by Attribute

Querying the DOM• Why Query the DOM?

Page 126: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 126/184

• The information provided in HTML is essa document

• Forms provide users with the ability to ainformation to this document

• It can be useful to retrieve values from thto provide immediate feedback or changdocument dynamically

Querying the DOM• In order to manipulate the DOM with

Page 127: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 127/184

p

JavaScript, you have to find what you alooking for… 

Querying the DOM• getElementById( id )

S l t i l l t i th DOM th t h

Page 128: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 128/184

• Selects a single element in the DOM that has

provided ID• Every element in the DOM must have a unique

• Returns an object with attributes relative to telement

For instance:• <div id=“myElement” /> • var el = document.getElementById(“myEleme

Querying the DOM• getElementsByTagName( type )

Page 129: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 129/184

g y g yp

Selects all elements of a type in the D• Returns a NodeList of the objects mee

criteria

•For instance:• var paragraphs = document.getElementsByTagNa

Querying the DOM• querySelector( query )

S l t th fi t i t f l t th t

Page 130: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 130/184

• Selects the first instance of element that

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

Querying the DOM• querySelectorAll( query )

Page 131: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 131/184

Selects all instances of items that matcquery

• Returns staticNodeList meeting the cr

Page 132: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 132/184

Querying the DOM• staticNodeList

Page 133: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 133/184

Array of HTML/XML Nodes in the DO• Static content, only contains nodes as

last query

Items are listed in the order they appethe DOM

Agenda• Overview • Intro to DOM?

Page 134: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 134/184

Variables• Objects

• Functions

• Arrays

Browser Objects• Querying DOM

• Manipulating

DOM• Event Handling

• Consuming Data

DOM Manipulation• What is it?

Page 135: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 135/184

Now that we have found what we wanhave to decide what to do with it.

• Allows us to add and remove elementthe DOM dynamically (DHTML)

• Allows us to modify elements and chastyles

DOM Manipulation• Why?

Ultimatel beca se e can right?

Page 136: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 136/184

• Ultimately, because we can… right? 

• Simple idea:• Add the value of two input boxes and place the

div … so that they can‟t modify it directly 

• Complex:• Iterate over the <tr> of a <table> summing the

multiple columns, then add a new <tfoot> elemrow showing the totals in the correct columns

DOM Manipulation• Before we can manipulate the DOM we ha

know a few more properties but to start le

Page 137: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 137/184

know a few more properties, but to start le

some terminology (sorry)• Node - Everything in the document is a

• Attribute Node – inside of an element node

Element Node – in HTML, these are tags <h• Text Node – any text inside of an element n

• Comment Node - <!-- Comment Node -->

DOM Manipulation• Node Relationships

• Root Node outermost element node <htm

Page 138: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 138/184

• Root Node – outermost element node <htm

• Parent Node – element node that contains oelement nodes

• Child Node – element node that has a parenevery node except the Root

• Sibling Node – element nodes that exist at thlevel, like <head> and <body> in the <html

DOM Manipulation• Properties

• className

Page 139: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 139/184

• className• Gets or sets the class attribute directly

• innerHTML• Gets or sets the contents of an element nod

including all child elements

• innerText• Gets or sets the Text Node Contents of an e

node

DOM Manipulation• Properties

t l *

Page 140: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 140/184

• style.*• Very nearly every single CSS property th

applied to an Element or Text Node has corresponding property on the Style Obj

In order words, it won‟t fit on the slide • http://www.w3schools.com/jsref/dom_ob

DOM Manipulation• Methods

• el.appendChild (el)

Page 141: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 141/184

• 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

DOM Manipulation• Methods

• el.createElement (s)C t l t d f th DOM t b t d t d

Page 142: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 142/184

• Creates an element node for the DOM to use, but does not ad

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

• el.getAttribute (s)• Gets the value of the specified attribute node for the element n

its called• el.setAttribute (s, v)

• Sets the attribute to the specified value for the element node ocalled

DOM Manipulation• Changing the DOM can mean many different t

• Changing HTML content

Page 143: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 143/184

• Changing HTML content

• Changing CSS styles• Changing HTML attributes

• Creating new HTML elements

Removing existing HTML elements• Changing event(handlers) – this happens in t

section

Page 144: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 144/184

DOM Manipulation• Changing HTML Content<div id=“dynamic”>I am Static</div>

Page 145: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 145/184

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

Page 146: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 146/184

We saw the className property, and the fastest, simplest way to change it

• Don‟t forget about transitions and animawhen you do this!

• You can also use the .style.property tomore granular control

Page 147: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 147/184

Page 148: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 148/184

DOM Manipulation• Changing or Adding HTML Attributes<input type=“text” id=“dynamic” value=

Page 149: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 149/184

<input type= text id= dynamic value=

textbox” /> 

<script>

var el = document.getElementById(“dyna

el.setAttribute(“type”, “button”); 

</script>

DOM Manipulation• Creating new HTML Elements

• Create the element using createElement

Page 150: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 150/184

g

createTextNode(s)• Use the appendChild (el) to add it into a

element node• It‟s important to note that you can add a

nodes as you like, and nest them, but evyou have to add the parent to a node elthat is structured into the DOM

DOM Manipulation• Creating new HTML Elements<div id=“dynamic” />

Page 151: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 151/184

<script>var el = document.getElementById(“dynamic”); 

var p = document.createElement(“p”); 

var txt = document.createTextNode(“Hola, Mund

p.appendChild(txt);el.appendChild(p)

</script>

DOM Manipulation• Removing HTML Elements

Page 152: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 152/184

Use the removeChild(el) on the parento remove the element

Page 153: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 153/184

Agenda• Overview

• Intro to DOM?

Page 154: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 154/184

Variables• Objects

• Functions

•Arrays

Browser Objects• Querying DOM

• Manipulating

DOM• Event Handling

• Consuming Data

Page 155: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 155/184

Event Handling• Common Events

• onclick• Triggered when the user clicks the element

Page 156: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 156/184

Triggered when the user clicks the element

• onload/onunload• Triggered when the user enters or leaves the page and o

the window object

• onchange• Triggered on input fields when the value changes

onmouseover/onmousemove/onmouseout• Triggered when the mouse moves over the element, or l

element

Event Handling• Common Events

• onmousedown/onmouseup• Triggered when the user clicks the mouse button down, a

Page 157: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 157/184

Triggered when the user clicks the mouse button down, a

it• onkeydown/onkeypress/onkeyup

• Triggered when the user presses and releases a key on th

• onfocus/onblur• Triggered when the control focus is given or taken away

input field• onsubmit

• Triggered when the user submits the form

Event Handling• Just for reference, when you attachEven

addEventListener, remove the “on” port

Page 158: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 158/184

addEventListener, remove the on port

the events

Event Handling• Declarative events

Page 159: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 159/184

Defined by the element node as an atas part of the original response

• Programmatic/Dynamic Events

Added to the element node to defineadditional or new functionality

Page 160: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 160/184

Event Handling• Programmatic/Dynamic Events

• Different ways to add events

Page 161: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 161/184

y• 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 () { }

Page 162: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 162/184

el.onEvent function () { }

• Set onEvent to an anonymous function

• el.onEvent = null;

• Clear the onEvent delegate

Page 163: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 163/184

Event Handling• Adding an event listener

• Allows you to add multiple events into

Page 164: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 164/184

y p

array of functions that execute in ordethe event triggers

• Using anonymous functions does not

you to remove the event, you have tothe element

Agenda• Overview

• Variables

• Intro to DOM?

• Browser Objects

Page 165: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 165/184

Variables

• Objects

• Functions

Arrays

Browser Objects

• Querying DOM

• Manipulating

DOM• Event Handling

• Consuming Data

Consuming Data• This is a very big topic, and I want to do justice, but … I need to just hit the highl

Page 166: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 166/184

• Implications of Consuming data• Retrieving it from somewhere

(XMLHTTPRequest)

• Recognizing the type of data (JSON, X• Parsing and using the data

Consuming Data• XMLHTTPRequest

• According to W3C Schools it‟s “the develope

Page 167: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 167/184

dream” • Update a web page without reloading the pa

• Request data from a server after the page ha

• Receive data from a server after the page ha

• Send data to a server in the background

Page 168: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 168/184

Consuming Data• XDomainRequest

• Similar to the XMLHTTPRequest

Page 169: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 169/184

• All the same properties and methods will see below

• Only available in IE 8+, not in any oth

browsers• Attempts cross-domain async web ca

Consuming Data• Why are cross-domain calls such a big deal?

• In computing, the same origin policy is animportant security concept for a number of brow

Page 170: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 170/184

programming languages, such as JavaScript. Thepermits scripts running on pages originating fromsame site – a combination of scheme, hostnamenumber – to access each other's methods and pwith no specific restrictions, but prevents access

methods and properties across pages on differesites. Same origin policy also appliesto XMLHttpRequest and to robots.txt.

Consuming Data• XMLHTTPRequest Methods

• abort()

Page 171: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 171/184

• Cancel the current request for the object• getAllResponseHeaders()

• Returns all header information as a string, dby 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

Page 172: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 172/184

handled asynchronously or not, and other optional a request

• send(postdata)• Sends the request off to the server.• Passes the postdata when the method of open() is p

• setRequestHeader(header, value)• Adds a key/value pair to the header to be sent

Consuming Data• XMLHTTPRequest Properties

• readyState

Page 173: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 173/184

• Holds the status of the XMLHttpRequest. Chfrom 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• Returns the response data as a string

Page 174: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 174/184

responseXML• Returns the response data as XML DOM, works for HTM

• status• Returns the status-number (e.g. "404" for "Not Found" o

"OK")

statusText• Returns the status-text (e.g. "Not Found" or "OK") 

Page 175: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 175/184

Consuming Data• XMLHTTPRequest Events

• onreadystatechanged = (function(){})• Stores a function to be called automatically eac

Page 176: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 176/184

yreadyState property changes

• ontimeout()*• Raised when there is an error that prevents the

completion of the request.

The stars mean you need to use the addEventLismethod to handle these events

Consuming Data• How does this fit together?

• Create an instance of XMLHTTPRequest

var xhr = new XMLHTTPRequest();

Page 177: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 177/184

• If you are going to work asynchronously, set a function for thonreadystatechanged that checks the readyState property asomething with the result

xhr.onreadystatechanged(function() {

if (xhr.readyState == 4 && xhr.status == 200) {document.getElementById(“mygooglediv”).innerHMTL = xhr.resp

}

});

Consuming Data• How does this fit together?

• Open (prep) the connection to the server.

Page 178: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 178/184

xhr.open(“get”, “https://www.google.com/search?q=xmlhttprequest”,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 onreadystatechan

Page 179: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 179/184

the response from the server as text, and appenthe inside of a div

Consuming Data• So now, how do you figure out if it‟s HTML

JSON?• Check the “Content-Type” header: 

Page 180: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 180/184

• application/json• application/xml• text/html• text/xml• text/plain this one is evil because it means nothing and e

Trust the source to be the right type (if you own it, yoknow what to expect)• Use jQuery or other to determine the type for you

Demo• Let‟s build a JS One-Page App!

Page 181: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 181/184

Conclusion• JavaScript is a first class citizen in the Application Dev

world

Page 182: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 182/184

Has the power an functionality of a language like C#• Syntactically similar to C#

• It‟s really hard to recap everything we discussed, suff

it‟s and awesome language, and we have just hit the iceberg

Page 183: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 183/184

© 2012 Computer Technology Solutions, Inc.

askcts.com

Rayne Hoover

[email protected](404) 419-0856

• .NET / GIS Developer• SharePoint Developer

Page 184: JavaScript - A Second Look

7/28/2019 JavaScript - A Second Look

http://slidepdf.com/reader/full/javascript-a-second-look 184/184