You are on page 1of 190

Language Basics

• Reviewing syntax
• Working with data types
• Working with flow-control statements
• Understanding functions
Language Basics
SYNTAX

ECMAScript’s syntax borrows heavily from C and other C-like languages such as
Java and Perl.

Case-sensitivity

The first concept to understand in JavaScript is that everything is case-


sensitive.

Identifiers

An identifier is the name of a variable, function, property, or function


argument.
Language Basics
Identifiers may be one or more characters in the following format:

• The first character must be a letter, an underscore (_), or a dollar sign ($).
• All other characters may be letters, underscores, dollar signs, or numbers.

By convention, ECMAScript identifiers use camel case, meaning that the first letter is
lowercase and each additional word is offset by a capital letter, like this:

firstSecond
myCar
doSomethingImportant

Although this is not strictly enforced, it is considered a best practice to adhere to the
built-in ECMAScript functions and objects that follow this format.
Language Basics
Comments

• ECMAScript uses C-style comments for both single-line and block comments.

//single line comment

• A block comment begins with a forward slash and asterisk (/*) and ends with
the opposite (*/), as in this example:

/*
* This is a multi-line
* Comment
*/
Language Basics
Strict Mode

• ECMAScript 5 introduced the concept of strict mode

What is Strict Mode?


Strict mode is a different parsing and execution model for JavaScript, where some
of the erratic behavior of ECMAScript 3 is addressed and errors are thrown for
unsafe activities.

To enable strict mode for an entire script, include the following at the top:

“use strict”;
Language Basics
Strict Mode

You may also specify just a function to execute in strict mode by including the
pragma at the top of the function body:

function doSomething(){
“use strict”;
//function body
}

Internet Explorer 10+, Firefox 4+, Safari 5.1+, Opera 12+, and
Chrome support strict mode.
Language Basics
Strict Mode

Example:

"use strict";
function testFunction(){
var testvar = 4;
return testvar;
}

testvar = 5; // This causes a syntax error. In strict


mode using a variable without declaring it causes an
error.
Language Basics
Statements

Statements in ECMAScript are terminated by a semicolon

Multiple statements can be combined into a code block by using C-style


syntax, beginning with a left curly brace ({) and ending with a right curly
brace (}):

if (test){ if (test)
test = false; alert(test); //valid, but error-prone and should be avoided
alert(test);
}
if (test){ //preferred
alert(test);
}
Language Basics
VARIABLES
ECMAScript variables are loosely typed, meaning that a variable can hold any
type of data.

Every variable is simply a named placeholder for a value.

To define a variable, use the var operator followed by the variable name

var message;

This code defines a variable named message that can be used to hold any value.

ECMAScript implements variable initialization, so it’s possible to define the


variable and set its value at the same time, as in this example:
Language Basics
VARIABLES
If you need to define more than one variable, you can do it using a single
statement, separating each variable (and optional initialization) with a comma
like this:

var message = “hi”,


found = false,
age = 29;
Language Basics
DATA TYPES

There are five simple data types (also called primitive types) in ECMAScript:
Undefined, Null, Boolean, Number, and String.

There is also one complex data type called Object, which is an


unordered list of name-value pairs.

The typeof Operator

Because ECMAScript is loosely typed, there needs to be a way to determine the data
type of a given variable. The typeof operator provides that information. Using the
typeof operator on a value returns one of the following strings:
Language Basics
DATA TYPES

“undefined” if the value is undefined


“boolean” if the value is a Boolean
“string” if the value is a string
“number” if the value is a number
“object” if the value is an object (other than a function) or null
“function” if the value is a function

The typeof operator is called like this:


var message = “some string”;

alert(typeof message); //”string”


alert(typeof(message)); //”string”
alert(typeof 95); //”number”
Language Basics
The Undefined Type

The Undefined type has only one value, which is the special value undefined.
When a variable is declared using var but not initialized, it is assigned the
value of undefined as follows:

var message;
alert(message == undefined); //true

Note that a variable containing the value of undefined is different from a variable
that hasn’t been defined at all.
Language Basics
The Null Type

The Null type is the second data type that has only one value: the special
value null. Logically, a null value is an empty object pointer, which is why
typeof returns “object” when it’s passed a null value in the following
example:
var car = null;
alert(typeof car); //”object”

When defining a variable that is meant to later hold an object, it is advisable to


initialize the variable to null as opposed to anything else. That way, you can
explicitly check for the value null to determine
if the variable has been filled with an object reference at a later time, such as
in this example:

if (car != null){
//do something with car
}
Language Basics
The Boolean Type

The Boolean type is one of the most frequently used types in ECMAScript and
has only two literal values: true and false.

var found = true;


var lost = false;
Note that the Boolean literals true and false are case-sensitive, so True and False
(and other mixings of uppercase and lowercase) are valid as identifiers but not as
Boolean values.

Though there are just two literal Boolean values, all types of values have Boolean
equivalents in ECMAScript. To convert a value into its Boolean equivalent, the
special Boolean() casting function is called, like this:
Language Basics
The Boolean Type

var message = “Hello world!”;


var messageAsBoolean = Boolean(message);
Language Basics
The Boolean Type
These conversions are important to understand because flow-control statements,
such as the if statement, automatically perform this Boolean conversion, as shown
here:

var message = “Hello world!”;


if (message){
alert(“Value is true”);
}
Language Basics
The Number Type

The most interesting data type in ECMAScript is Number, which uses the IEEE-754
format to represent both integers and floating-point values.

The most basic number literal format is that of a decimal integer

var intNum = 55; //integer


Integers can also be represented as either octal (base 8) or hexadecimal (base 16)
literals.
For an octal literal, the first digit must be a zero (0) followed by a sequence of octal
digits (numbers 0through 7).

If a number out of this range is detected in the literal, then the leading zero is ignored
and the number is treated as a decimal.
Language Basics
The Number Type

var octalNum1 = 070; //


var octalNum2 = 079; //
var octalNum3 = 08; //

Note Octal literals are invalid when running in strict mode and will cause the
JavaScript engine to throw a syntax error.

To create a hexadecimal literal, you must make the first two characters 0x (case
insensitive), followed by any number of hexadecimal digits (0 through 9, and A
through F). Letters may be in uppercase or lowercase.

var hexNum1 = 0xA; //


var hexNum2 = 0x1f; //
Language Basics
Floating-Point Values

To define a floating-point value, you must include a decimal point and at least one
number after the decimal point. Although an integer is not necessary before a
decimal point, it is recommended.

var floatNum1 = 1.1;


var floatNum2 = 0.1;
var floatNum3 = .1; //valid, but not recommended

Because storing floating-point values uses twice as much memory as storing integer
values, ECMAScript always looks for ways to convert values into integers. When
there is no digit after the decimal point, the number becomes an integer. Likewise, if
the number being represented is a whole
number (such as 1.0), it will be converted into an integer, as in this example:
Language Basics
Floating-Point Values
For very large or very small numbers, floating-point values can be represented using
e-notation.

var floatNum = 3.125e7; //equal to 31250000

Range of Values
Not all numbers in the world can be represented in ECMAScript, because of
memory constraints.

The smallest number that can be represented in ECMAScript is stored in


Number.MIN_VALUE and is 5e-324 on most browsers; the largest number is stored
in Number.MAX_VALUE and is 1.7976931348623157e+308 on most browsers.
Language Basics
NaN

There is a special numeric value called NaN, short for Not a Number, which is used
to indicate when an operation intended to return a number has failed (as opposed to
throwing an error).

The value NaN has a couple of unique properties. First, any operation involving
NaN always returns NaN (for instance, NaN /10), which can be problematic in the
case of multistep computations.
Second, NaN is not equal to any value, including NaN. For example, the following
returns false:
alert(NaN == NaN); //false
Language Basics
NaN

alert(isNaN(NaN)); //
alert(isNaN(10)); //
alert(isNaN(“10”)); //
alert(isNaN(“blue”)); //
alert(isNaN(true)); //
Language Basics
Number Conversions

There are three functions to convert non-numeric values into numbers: the
Number() casting function, the parseInt() function, and the parseFloat() function.

The first function, Number(), can be used on any data type; the other two functions
are used specifically for converting strings to numbers. Each of these functions reacts
differently to the same input.

The Number() function performs conversions based on these rules:

• When applied to Boolean values, true and false get converted into 1 and 0,
respectively.

• When applied to numbers, the value is simply passed through and returned.
Language Basics
Number Conversions

• When applied to null, Number() returns 0.

• When applied to strings, the following rules are applied:

• If the string contains only numbers, optionally preceded by a plus or minus sign,
it is always converted to a decimal number, so “1” becomes 1, “123” becomes
123, and “011” becomes 11 (note: leading zeros are ignored).

• If the string contains a valid floating-point format, such as “1.1”, it is converted


into the appropriate floating-point numeric value (once again, leading zeros are
ignored).
• If the string contains a valid hexadecimal format, such as “0xf”, it is converted
into an integer that matches the hexadecimal value.
Language Basics
Number Conversions

• If the string is empty (contains no characters), it is converted to 0.


• If the string contains anything other than these previous formats, it is converted
into NaN.

Converting to numbers from various data types can get complicated, as indicated by
the number of rules there are for Number(). Here are some concrete examples:

var num1 = Number(“Hello world!”); //NaN


var num2 = Number(“”); //0
var num3 = Number(“000011”); //11
var num4 = Number(true); //1
Language Basics
Number Conversions

Because of the complexities and oddities of the Number() function when converting
strings, the parseInt() function is usually a better option when you are dealing with
integers. The parseInt() function examines the string much more closely to see if it
matches a number pattern.
Language Basics
The String Type

The String data type represents a sequence of zero or more characters. Strings can be
delineated by either double quotes (“) or single quotes (‘), so both of the following are
legal:
var firstName = “Suman”;
var lastName = ‘Mishra’;

Note, that a string beginning with a double quote must end


with a double quote, and a string beginning with a single quote must end with a single
quote. For example, the following will cause a syntax error:

var firstName = ‘Suman”; //syntax error - quotes must match


Language Basics
Converting to a String

There are two ways to convert a value into a string. The first is to use the toString()
method that almost every value has.

var age = 11;


var ageAsString = age.toString(); //the string “11”
var found = true;
var foundAsString = found.toString(); //the string “true”

The toString() method is available on values that are numbers, Booleans, objects, and
strings.(Yes, each string has a toString() method that simply returns a copy of itself.) If
a value is null or undefined, this method is not available.
Language Basics
Converting to a String

There are two ways to convert a value into a string. The first is to use the toString()
method that almost every value has.

var num = 10;


alert(num.toString()); //”10”
alert(num.toString(2)); //”1010”
alert(num.toString(8)); //”12”
alert(num.toString(10)); //”10”
alert(num.toString(16)); //”a”
Language Basics
Operators

ECMA-262 describes a set of operators that can be used to manipulate data values.

The operators range from mathematical operations (such as addition and subtraction)
and bitwise operators to relational operators and equality operators.

Operators are unique in ECMAScript in that they can be used on a wide range of
values, including strings, numbers, Booleans, and even objects.
Language Basics
Unary Operators

Operators that work on only one value are called unary operators. They are the simplest
operators in ECMAScript.

Increment/Decrement
The increment and decrement operators are taken directly from C and come in two
versions: prefix and postfix.

The prefix versions of the operators are placed before the variable they work on; the
postfix ones are placed after the variable.

To use a prefix increment, which adds 1 to a numeric


value, you place two plus signs (++) in front of a variable like this:

var age = 29;


++age;
Language Basics
The prefix decrement acts in a similar manner, subtracting 1 from a numeric value. To
use a prefix decrement, place two minus signs (--) before a variable, as shown here:

var age = 29;


--age;

When using either a prefix increment or a prefix decrement, the variable’s value is
changed before the statement is evaluated. (In computer science, this is usually referred
to as having a side effect.)
Consider the following:

var age = 29;


var anotherAge = --age + 2;
alert(age); //outputs 28
alert(anotherAge); //outputs 30
Language Basics
The prefi x increment and decrement are equal in terms of order of precedence in a
statement and are therefore evaluated left to right. Consider this example:

var num1 = 2;
var num2 = 20;
var num3 = --num1 + num2; //
var num4 = num1 + num2; //

The postfix versions of increment and decrement use the same syntax (++ and --,
respectively) but are placed after the variable instead of before it.

Postfix increment and decrement differ from the prefix versions in one important way:
the increment or decrement doesn’t occur until after the
containing statement has been evaluated.
Language Basics
In certain circumstances, this difference doesn’t matter, as
in this example:
var age = 29;
age++;

Moving the increment operator after the variable doesn’t change what these statements
do, because the increment is the only operation occurring. However, when mixed
together with other operations, the difference becomes apparent, as in the following
example:

var num1 = 2;
var num2 = 20;
var num3 = num1-- + num2; //equals 22
var num4 = num1 + num2; //equals 21
Language Basics
Boolean Operators

Logical NOT
• The logical NOT operator is represented by an exclamation point (!) and may be
applied to any value in ECMAScript.

• This operator always returns a Boolean value, regardless of the data type it’s used
on.

• The logical NOT operator first converts the operand to a Boolean value and then
negates it,

• If the operand is an object, false is returned.


• If the operand is an empty string, true is returned.
• If the operand is a nonempty string, false is returned.
Language Basics
Boolean Operators

• If the operand is the number 0, true is returned.


• If the operand is any number other than 0 (including Infinity), false is
returned.
• If the operand is null, true is returned.
• If the operand is NaN, true is returned.
• If the operand is undefined, true is returned.

Logical AND

The logical AND operator is represented by the double ampersand (&&) and is
applied to two values, such as in this example:
Language Basics
var result = true && false;

Logical AND can be used with any type of operand, not just Boolean values.

The logical AND operator is a short-circuited operation, meaning that if the first
operand determines the result, the second operand is never evaluated.

In the case of logical AND, if the first operand is false, no matter what the value of the
second operand, the result can’t be equal to true.

Logical OR

The logical OR operator is represented by the double pipe (||) in ECMAScript, like this:

var result = true || false;


Language Basics
Relational Operators

<, >, <=, >=

Equality Operators

Equal and Not Equal


Identically Equal and Not Identically Equal

Conditional Operator

The conditional operator is one of the most versatile in ECMAScript, and it


takes on the same form as in Java, which is as follows:

variable = boolean_expression ? true_value : false_value;


Language Basics
Assignment Operators

Simple assignment is done with the equal sign (=) and simply assigns the value on the
right to the variable on the left, as shown in the following example:

var num = 10;


num = num + 10;// num += 10;

Comma Operator

The comma operator allows execution of more than one operation in a single statement,
as illustrated here:
var num1=1, num2=2, num3=3;
Language Basics
The with Statement

The with statement sets the scope of the code within a particular object. The syntax is as
follows:

with (expression) statement;

The with statement was created as a convenience for times when a single object was
being coded to over and over again, such as in this example:
var qs = location.search.substring(1);
var hostName = location.hostname;
var url = location.href;
with(location){
var qs = search.substring(1);
var hostName = hostname;
var url = href;
}
Events
• Understanding event flow

• Working with event handlers

• Examining the different types of events

JavaScript’s interaction with HTML is handled through events.


Events first appeared in Internet Explorer 3 and Netscape Navigator 2 as a way to
offload some form processing from the server onto the browser.

By the time Internet Explorer 4 and Netscape 4 were released, each browser delivered
similar but different APIs that continued for several generations.

DOM Level 2 was the first attempt to standardize the DOM events API in
a logical way.
Events
Event Flow

Event flow describes the order in which events are received on the page, and interestingly,
the Internet Explorer and Netscape development teams came up with an almost exactly
opposite concept of event flow.

Internet Explorer would support an event bubbling flow, whereas Netscape


Communicator would support an event capturing flow.

Event Bubbling

The Internet Explorer event flow is called event bubbling, because an event is said
to start at the most specific element and then flow upward
toward the least specific node. Consider the following HTML page:
Events
Event Bubbling
<!DOCTYPE html>
<html>
<head>
<title>Event Bubbling Example</title>
</head>
<body>
<div id=”myDiv”>Click Me</div>
</body>
</html>
When you click the <div> element in the page, the click event occurs in the following
order:

Div, Body, HTML, Document


Events
Event Bubbling

All modern browsers support event bubbling, although there are some
variations on how it is implemented.

Internet Explorer 5.5 and earlier skip bubbling to the <html> element
(going from <body> directly to document).

Internet Explorer 9, Firefox, Chrome, and Safari continue event bubbling up to


the window object.
Events
Event Capturing

The theory of event capturing is that the least specific node should receive the
event first and the most specific node should receive the event last.

If the previous example is used with event capturing, clicking


the <div> element fires the click event in the following order:

Document, <HTML>, <Body>, <div>

Event capturing is currently supported in Internet Explorer 9, Safari,


Chrome, Opera, and Firefox.

Event capturing is generally not used because of a lack of support in older


browsers. The general advice is to use event bubbling freely while retaining event
capturing for special circumstances.
Events
DOM Event Flow

The event flow specified by DOM Level 2 Events has three phases: the event
capturing phase, at the target, and the event bubbling phase.

Event capturing occurs first, providing the opportunity to intercept events if


necessary. Next, the actual target receives the event.

The final phase is bubbling which allows a final response to the event.
In the DOM event flow, the actual target (the <div> element) does not receive the
event during the capturing phase.

This means that the capturing phase moves from document to <html> to <body> and
stops. The next phase is “at target,” which fires on the <div> and is considered to be
part of the bubbling phase in terms of event handling .Then, the bubbling phase
occurs and the event travels back up to the document.
Events
Event Handlers

Events are certain actions performed either by the user or by the browser
itself. These events have names like click, load, and mouseover.

A function that is called in response to an event is called


an event handler (or an event listener).

Event handlers have names beginning with “on”, so an event


handler for the click event is called onclick and an event handler for the load
event is called onload.

Assigning event handlers can be accomplished in a number of different ways.


Events
HTML Event Handlers

Each event supported by a particular element can be assigned using an


HTML attribute with the name of the event handler. The value of the
attribute should be some JavaScript code to execute.

For example, to execute some JavaScript when a button is clicked, you can
use the following:

<input type=”button” value=”Click Me” onclick=”alert(‘Clicked’)” />

An event handler defined in HTML may contain the precise action to take or it
can call a script defined elsewhere on the page, as in this example:
Events
HTML Event Handlers

<script type=”text/javascript”>
function showMessage(){
alert(“Hello world!”);
}
</script>

<input type=”button” value=”Click Me” onclick=”showMessage()” />


Events
DOM Level 0 Event Handlers

To assign an event handler using JavaScript, you must first retrieve a


reference to the object to act on.

Each element (as well as window and document) has event handler properties that
are typically all lowercase, such as onclick. An event handler is assigned by setting
the property equal to a function, as in this example:

var btn = document.getElementById(“myBtn”);


btn.onclick = function(){
alert(“Clicked”);
};
Events
DOM Level 2 Event Handlers

DOM Level 2 Events define two methods to deal with the assignment and removal
of event handlers: addEventListener() and removeEventListener().

These methods exist on all DOM nodes and accept three arguments: the event
name to handle, the event handler function, and a
Boolean value indicating whether to call the event handler during the capture
phase (true) or during the bubble phase (false).

To add an event handler for the click event on a button, you can use the
following code:
Events
DOM Level 2 Event Handlers
var btn = document.getElementById(“myBtn”);
btn.addEventListener(“click”, function(){
alert(this.id);
}, false);

The major advantage to using the DOM Level 2 method for adding event handlers is
that multiple event handlers can be added. Consider the following example:

var btn = document.getElementById(“myBtn”);


btn.addEventListener(“click”, function(){
alert(this.id);
}, false);
btn.addEventListener(“click”, function(){
alert(“Hello world!”);
},false);
Events
DOM Level 2 Event Handlers
Event handlers added via addEventListener() can be removed only by using
removeEventListener() and passing in the same arguments as were used when
the handler was added.

var btn = document.getElementById(“myBtn”);


btn.addEventListener(“click”, function(){
alert(this.id);
}, false);

//other code here

btn.removeEventListener(“click”, function(){ //won’t work!


alert(this.id);
}, false);
Events
DOM Level 2 Event Handlers

var btn = document.getElementById(“myBtn”);


var handler = function(){
alert(this.id);
};

btn.addEventListener(“click”, handler, false);

//other code here


btn.removeEventListener(“click”, handler, false); //works!
Events
Internet Explorer Event Handlers

Internet Explorer implements methods similar to the DOM called attachEvent() and
detachEvent(). These methods accept the same two arguments: the event handler name
and the event handler function.

Since Internet Explorer 8 and earlier support only event bubbling, event handlers
added using attachEvent() are attached on the bubbling phase.

To add an event handler for the click event on a button using attachEvent(), you can use
the following code:

var btn = document.getElementById(“myBtn”);


btn.attachEvent(“onclick”, function(){
alert(“Clicked”);
});
Events
Internet Explorer Event Handlers

The attachEvent() method, similar to addEventListener(), can be used to add multiple


event handlers to a single element. Consider the following example:

var btn = document.getElementById(“myBtn”);


btn.attachEvent(“onclick”, function(){
alert(“Clicked”);
});

btn.attachEvent(“onclick”, function(){
alert(“Hello world!”);
});

Unlike the DOM method, though, the event handlers fire in reverse of the order they
were added. When the button in this example is clicked, the first alert says “Hello
world!” and the second says “Clicked”.
Events
Internet Explorer Event Handlers

Events added using attachEvent() are removed using detachEvent() as long as the same
arguments are provided.

As with the DOM methods, this means that anonymous functions cannot be removed
once they have been added.

var btn = document.getElementById(“myBtn”);


var handler = function(){
alert(“Clicked”);
};

btn.attachEvent(“onclick”, handler);
//other code here
btn.detachEvent(“onclick”, handler);
Events
Cross-Browser Event Handlers
To make sure that the event-handling code works in the most compatible way possible,
you will need it to work only on the bubbling phase.
var EventUtil = {
addHandler: function(element, type, handler){
if (element.addEventListener){
element.addEventListener(type, handler, false);
} else if (element.attachEvent){
element.attachEvent(“on” + type, handler);
} else {
element[“on” + type] = handler;
}
},

removeHandler: function(element, type, handler){


if (element.removeEventListener){
element.removeEventListener(type, handler, false);
} else if (element.detachEvent){
element.detachEvent(“on” + type, handler);
} else {
element[“on” + type] = null;
}
}
};
Events
Cross-Browser Event Handlers

var btn = document.getElementById(“myBtn”);


var handler = function(){
alert(“Clicked”);
};

EventUtil.addHandler(btn, “click”, handler);

//other code here

EventUtil.removeHandler(btn, “click”, handler);


Events
THE EVENT OBJECT

When an event related to the DOM is fired, all of the relevant information is gathered and
stored on an object called event.

This object contains basic information such as the element that caused
the event, the type of event that occurred, and any other data that may be relevant to the
particular event.

For example, an event caused by a mouse action generates information about the mouse’s
position, whereas an event caused by a keyboard action generates information about the
keys that were pressed. All browsers support the event object, though not in the same way.
Events

In DOM-compliant browsers, the event object is passed in as the sole argument to an event
handler.

Regardless of the method used to assign the event handler, DOM Level 0 or DOM Level 2,
the event object is passed in.

var btn = document.getElementById(“myBtn”);


btn.onclick = function(event){
alert(event.type); //”click”
};

btn.addEventListener(“click”, function(event){
alert(event.type); //”click”
}, false);

<input type=”button” value=”Click Me” onclick=”alert(event.type)”>


Events
The DOM Event Object

The event object contains properties and methods related to the specific event that caused its
creation.
Events
Events

The preventDefault() method is used to prevent the default action of a particular


event.

var link = document.getElementById(“myLink”);


link.onclick = function(event){
event.preventDefault();
};

The stopPropagation() method stops the flow of an event through the DOM structure
immediately, canceling any further event capturing or bubbling before it occurs.

For example, an event handler added directly to a button can call stopPropagation()
to prevent an event handler on document
.body from being fired, as shown in the following example:
Events

var btn = document.getElementById(“myBtn”);


btn.onclick = function(event){
alert(“Clicked”);
event.stopPropagation();
};

document.body.onclick = function(event){
alert(“Body clicked”);
};
Events

The eventPhase property aids in determining what phase of event flow is


currently active. If the event handler is called during the capture phase,
eventPhase is 1; if the event handler is at the target, eventPhase is 2; if the event
handler is during the bubble phase, eventPhase is 3.

var btn = document.getElementById(“myBtn”);

btn.onclick = function(event){
alert(event.eventPhase); //2
};
document.body.addEventListener(“click”, function(event){
alert(event.eventPhase); //1
}, true);
document.body.onclick = function(event){
alert(event.eventPhase); //3
};
Events
The Internet Explorer Event Object

Unlike the DOM event object, the Internet Explorer event object is accessible in
different ways based on the way in which the event handler was assigned. When
an event handler is assigned using
the DOM Level 0 approach, the event object exists only as a property of the
window object. Here is an example:

var btn = document.getElementById(“myBtn”);


btn.onclick = function(){
var event = window.event;
alert(event.type); //”click”
};

If the event handler is assigned using attachEvent(), the event object is passed in
as the sole argument to the function, as shown here:
Events
The Internet Explorer Event Object

var btn = document.getElementById(“myBtn”);


btn.attachEvent(“onclick”, function(event){
alert(event.type); //”click”
});

If the event handler is assigned by an HTML attribute, the event object is


available as a variable called event. Here’s an example:

<input type=”button” value=”Click Me” onclick=”alert(event.type)”>


Events
The Internet Explorer Event Object

The Internet Explorer event object also contains properties and methods related to
the specific event that caused its creation.
Events
The Cross-Browser Event Object
Although the event objects for the DOM and Internet Explorer are different, there
are enough similarities to allow cross-browser solutions.

var EventUtil = {
addHandler: function(element, type, handler){
//code removed for printing
},
getEvent: function(event){
return event ? event : window.event;
},
getTarget: function(event){
return event.target || event.srcElement;
},
preventDefault: function(event){
if (event.preventDefault){
event.preventDefault();
} else {
event.returnValue = false;
}
},
removeHandler: function(element, type, handler){
//code removed for printing
},
Events
The Cross-Browser Event Object

stopPropagation: function(event){
if (event.stopPropagation){
event.stopPropagation();
} else {
event.cancelBubble = true;
}
}
};
btn.onclick = function(event){
event = EventUtil.getEvent(event);
};
Events
EVENT TYPES

User interface (UI) events are general browser events that may have some interaction with the BOM.

Focus events are fi red when an element gains or loses focus.


Mouse events are fi red when the mouse is used to perform an action on the page.

Wheel events are fi red when a mouse wheel (or similar device) is used.

Text events are fi red when text is input into the document.

Keyboard events are fi red when the keyboard is used to perform an action on the page.

Composition events are fi red when inputting characters for an Input Method Editor (IME).

Mutation events are fi red when a change occurs to the underlying DOM structure.
RegExp
Regular expressions provide a powerful way to search and manipulate text.

Different languages have different implementations of the regular expressions syntax.


JavaScript uses the Perl 5 syntax.

Instead of saying "regular expression", people often shorten it to "regex" or


"regexp".

A regular expression consists of:


• A pattern you use to match text
• Zero or more modifiers (also called flags) that provide more instructions on
how the pattern should be applied

In this session you'll see what JavaScript provides in terms of syntax, objects and
methods in order to support the use of regular expressions.
RegExp
JavaScript provides the RegExp() constructor which allows you to create regular
expression objects.

var re = new RegExp("j.*t");

There is also the more convenient regexp literal .

var re = /j.*t/;

In the example above, j.*t is the regular expression pattern.


It means, "Match any string that starts with j, ends with t and has zero or more
characters in between".

The asterisk * means "zero or more of the preceding"; the dot (.) means "any
character".
RegExp
The pattern needs to be placed in quotation marks when used in a RegExp()
constructor.

Properties of the RegExp Objects


The regular expression objects have the following properties:

global: If this property is false, which is the default, the search stops when the first match is found. Set
this to true if you want all matches.

ignoreCase: Case sensitive match or not, defaults to false.

multiline: Search matches that may span over more than one line, defaults to false.

lastIndex: The position at which to start the search, defaults to 0.

source: Contains the regexp pattern.


RegExp
None of these properties, except for lastIndex, can be changed once the object has
created.
The first three parameters represent the regex modifiers. If you create a regex object
using the constructor, you can pass any combination of the following characters as a
second parameter:
"g" for global
"i" for ignoreCase
"m" for multiline

These letters can be in any order. If a letter is passed, the corresponding modifier is set to
true. In the following example, all modifiers are set to true:

var re = new RegExp('j.*t', 'gmi');

Let's verify:

re.global; // true
RegExp
Once set, the modifier cannot be changed:

re.global = false;
re.global // true

To set any modifiers using the regex literal, you add them after the closing slash.

var re = /j.*t/ig;

re.global
RegExp
Methods of the RegExp Objects

The regex objects provide two methods you can use to find matches: test() and exec().

They both accept a string parameter. test() returns a Boolean (true when there's a
match, false otherwise), while exec() returns an array of matched strings.

Obviously exec() is doing more work, so use test() unless you really need to do
something with the matches. People often use regular expressions for validation
purposes, in this case test() would probably be enough.
/j.*t/.test("Javascript") //

/j.*t/i.test("Javascript") //
RegExp
The same test using exec() returns an array and you can access the first element as
shown below:

/j.*t/i.exec("Javascript")[0]
FORMS
Understanding Form Basics

Text box validation and interaction

Working with other form controls

Form Basics
Web forms are represented by the <form> element in HTML and by the
HTMLFormElement type in JavaScript.

The HTMLFormElement type inherits from HTMLElement and therefore has


all of the same default properties as other HTML elements.

However, HTMLFormElement also has the following additional properties and


methods:
FORMS
acceptCharset — The character sets that the server can process; equivalent to the
HTML accept-charset attribute.

action — The URL to send the request to; equivalent to the HTML action attribute.

elements — An HTMLCollection of all controls in the form.


enctype — The encoding type of the request; equivalent to the HTML enctype
attribute.

length — The number of controls in the form.

method — The type of HTTP request to send, typically “get” or “post”; equivalent to
the HTML method attribute.

name — The name of the form; equivalent to the HTML name attribute.
FORMS
reset() — Resets all form fields to their default values.

submit() — Submits the form.


target — The name of the window to use for sending the request and receiving the
response; equivalent to the HTML target attribute.

var form = document.getElementById(“form1”);

All forms on the page can also be retrieved from document.forms collection. Each form
can be accessed in this collection by numeric index and by name, as shown in the
following examples:

var firstForm = document.forms[0]; //get the first form in the page

var myForm = document.forms[“form2”]; //get the form with a name of


“form2”
FORMS
Note that forms can have both an id and a name and that these values need not be the
same.

Submitting Forms

Forms are submitted when a user interacts with a submit button or an image button.

Submit buttons are defined using either the <input> element or the <button> element
with a type attribute of “submit“, and image buttons are defined using the <input>
element with a type attribute of “image“.

All of the following, when clicked, will submit a form in which the button resides:
FORMS
<!-- generic submit button -->
<input type=”submit” value=”Submit Form”>

<!-- custom submit button -->


<button type=”submit”>Submit Form</button>

<!-- image button -->


<input type=”image” src=”graphic.gif”>

If any one of these types of buttons is within a form that has a submit button, pressing
Enter on the keyboard while a form control has focus will also submit the form.

Note that forms without a submit button will not be submitted when Enter is pressed.
FORMS
When a form is submitted in this manner, the submit event fires right before the
request is sent to the server.

This gives you the opportunity to validate the form data and decide whether to allow
the form submission to occur.
Preventing the event’s default behavior cancels the form submission.

It’s possible to submit a form programmatically by calling the submit() method from
JavaScript.

This method can be called at any time to submit a form and does not require a submit
button to be present in the form to function appropriately. Here’s an example:

var form = document.getElementById(“myForm”);


//submit the form
form.submit();
FORMS
When a form is submitted via submit(), the submit event does not fire, so be sure to
do data validation before calling the method.

One of the biggest issues with form submission is the possibility of submitting the
form twice.

Reset Forms
Forms are reset when the user clicks a reset button. Reset buttons are created using
either the<input> or the <button> element with a type attribute of “reset“, as in these
examples:
<!-- generic reset button -->
<input type=”reset” value=”Reset Form”>

<!-- custom reset button -->


<button type=”reset”>Reset Form</button>
FORMS
Reset Forms

Either of these buttons will reset a form. When a form is reset, all of the form
fields are set back to the values they had when the page was first rendered. If a
field was originally blank, it becomes blank again, whereas a field with a default
value reverts to that value.

When a form is reset by the user clicking a reset button, the reset event fi res.
This event gives you the opportunity to cancel the reset if necessary.

As with form submission, resetting a form can be accomplished via JavaScript


using the reset() method, as in this example:
FORMS
Reset Forms
var form = document.getElementById(“myForm”);
//reset the form
form.reset();

Unlike the submit() method’s functionality, reset() fi res the reset event the
same as if a reset button were clicked.

Form Fields
Form elements can be accessed in the same ways as any other elements on
the page using native DOM methods.
FORMS
Form Fields

Additionally, all form elements are parts of an elements collection that is a


property of each form.

The elements collection is an ordered list of references to all form fields in the
form and includes all <input>, <textarea>, <button>, <select>, and <fieldset>
elements.

Each form field appears in the elements collection in the order in which it
appears in the markup, indexed by both position and name.
FORMS
Form Fields

var form = document.getElementById(“form1”);

//get the first field in the form


var field1 = form.elements[0];

//get the field named ”textbox1”


var field2 = form.elements[”textbox1”];

//get the number of fields


var fieldCount = form.elements.length;
FORMS
Common Form-Field Properties

The common form-field properties and methods are as follows:

disabled — A Boolean indicating if the field is disabled.

form — A pointer to the form that the field belongs to. This property is read only.

name — The name of the field.

readOnly — A Boolean indicating if the field is read only.

tabIndex — Indicates the tab order for the field.

type — The type of the field: “checkbox”, “radio”, and so on.

value — The value of the field that will be submitted to the server.
FORMS
Common Form-Field Properties
var form = document.getElementById(“myForm”);
var field = form.elements[0];

//change the value


field.value = ”Another value”;

//check the value of form


alert(field.form === form); //true

//set focus to the field


field.focus();

//disable the field


field.disabled = true;

//change the type of field (not recommended, but possible for <input>)
field.type = ”checkbox”;
FORMS
Common Form-Field Methods

Each form field has two methods in common: focus() and blur().

The focus() method sets the browser’s focus to the form field, meaning that the field
becomes active and will respond to keyboard events.
For example, a text box that receives focus displays its caret and is ready to accept
input.
For example, a text box that receives focus displays its caret and is ready to accept
input.

EventUtil.addHandler(window, “load”, function(event){


document.forms[0].elements[0].focus();
});
FORMS
Common Form-Field Events

All form fields support the following three events in addition to mouse, keyboard, and
HTML events:

blur — Fires when the field loses focus.

change — Fires when the field loses focus and the value has changed for <input> and<textarea>
elements; also fi res when the selected option changes for <select> elements.

focus — Fires when the field gets focus.

Both the blur and the focus events fire because of users manually changing the field’s focus,
as well as by calling the blur() and focus() methods, respectively.
FORMS
Common Form-Field Events
For <input> and <textarea> elements, the change event fires when the field loses focus and the
value has changed since the time the control got focus.

For <select> elements, however, the change event fires whenever the user changes the selected
option; the control need not lose focus for change to fire.

The focus event may be used to change the background color to more clearly indicate that the
field has focus, the blur event can be used to remove that background color, and the change
event can change the background color to
red if nonnumeric characters are entered.

The following code accomplishes this:


FORMS
Common Form-Field Events

var textbox = document.forms[0].elements[0];

EventUtil.addHandler(textbox, “focus”, function(event){


event = EventUtil.getEvent(event);
var target = EventUtil.getTarget(event);

if (target.style.backgroundColor != “red”){
target.style.backgroundColor = “yellow”;
}
});
FORMS
Common Form-Field Events

EventUtil.addHandler(textbox, “blur”, function(event){


event = EventUtil.getEvent(event);
var target = EventUtil.getTarget(event);
if (/[^\d]/.test(target.value)){
target.style.backgroundColor = “red”;
} else {
target.style.backgroundColor = “”;
}
});
FORMS
Common Form-Field Events

EventUtil.addHandler(textbox, “change”, function(event){


event = EventUtil.getEvent(event);
var target = EventUtil.getTarget(event);
if (/[^\d]/.test(target.value)){target.style.backgroundColor = “red”;
} else {
target.style.backgroundColor = “”;
}
});
FORMS
SCRIPTING TEXT BOXES
There are two ways to represent text boxes in HTML: a single-line version using the <input>
element and a multiline version using <textarea>.

These two controls are very similar and behave in similar ways most of the time. There are,
however, some important differences.

By default, the <input> element displays a text box, even when the type attribute is omitted(the
default value is “text”).

The size attribute can then be used to specify how wide the text box should be in terms of visible
characters.

The value attribute specifies the initial value of the text box, and the maxlength attribute
specifies the maximum number of characters allowed in the text box.
FORMS
SCRIPTING TEXT BOXES
So to create a text box that can display 25 characters at a time but has a maximum
length of 50, you can use the following code:

<input type=”text” size=”25” maxlength=”50” value=”initial value”>

The <textarea> element always renders a multiline text box.

To specify how large the text box should be, you can use the rows attribute, which specifies the
height of the text box in number of characters, and the cols attribute, which specifies the width in
number of characters, similar to size for an <input> element.

Unlike <input>, the initial value of a <textarea> must be enclosed between <textarea> and
</textarea>, as shown here:
FORMS
SCRIPTING TEXT BOXES

<textarea rows=”25” cols=”5”>initial value</textarea>

Also unlike the <input> element, a <textarea> cannot specify the maximum number of
characters allowed using HTML.

Despite the differences in markup, both types of text boxes store their contents in the value
property. The value can be used to read the text box value and to set the text box value, as in this
example:

var textbox = document.forms[0].elements[“textbox1”];


alert(textbox.value);
textbox.value = “Some new value”;
FORMS
SCRIPTING TEXT BOXES
Text Selection

Both types of text boxes support a method called select(), which selects all of the text in a text
box.

Most browsers automatically set focus to the text box when the select() method is called (Opera
does not). The method accepts no arguments and can be called at any time. Here’s an example:

var textbox = document.forms[0].elements[“textbox1”];


textbox.select();

It’s quite common to select all of the text in a text box when it gets focus, especially if the text
box has a default value. The thinking is that it makes life easier for users when they don’t have
to delete text separately.
FORMS
SCRIPTING TEXT BOXES
Text Selection

This pattern is accomplished with the following code:

EventUtil.addHandler(textbox, “focus”, function(event){


event = EventUtil.getEvent(event);
var target = EventUtil.getTarget(event);
target.select();
});
FORMS
SCRIPTING TEXT BOXES
The select Event

To accompany the select() method, there is a select event.

The select event fires when text is selected in the text box.

Exactly when the event fi res differs from browser to browser. In Internet
Explorer 9+, Opera, Firefox, Chrome, and Safari, the select event fi res once the user has
finished selecting text, whereas in Internet Explorer 8 and earlier it fi res as soon as one letter
is selected. The select event also fi res when the select() method is called.

var textbox = document.forms[0].elements[“textbox1”];

EventUtil.addHandler(textbox, “select”, function(event){


var alert(“Text selected: “ + textbox.value);
});
FORMS
SCRIPTING SELECT BOXES
Select boxes are created using the <select> and <option> elements.

add(newOption, relOption) — Adds a new <option> element to the control before the related option.

multiple — A Boolean value indicating if multiple selections are allowed; equivalent to the HTML multiple
attribute.

options — An HTMLCollection of <option> elements in the control.

remove(index) — Removes the option in the given position.

selectedIndex — The zero-based index of the selected option or –1 if no options are


selected. For select boxes that allow multiple selections, this is always the first option in the selection.

size — The number of rows visible in the select box; equivalent to the HTML size attribute.
FORMS
SCRIPTING SELECT BOXES
The option that is currently selected determines a select box’s value property according to
the following rules:

• If there is no option selected, the value of a select box is an empty string.

• If an option is selected and it has a value attribute specified, then the select
box’s value is the value attribute of the selected option. This is true even if the
value attribute is an empty string.

• If an option is selected and it doesn’t have a value attribute specified, then the
select box’s value is the text of the option.

• If multiple options are selected, then the select box’s value is taken from the
first selected option according to the previous two rules.
FORMS
SCRIPTING SELECT BOXES
Consider the following select box:

<select name=”location” id=”selLocation”>


<option value=”Sunnyvale, CA”>Sunnyvale</option>
<option value=”Los Angeles, CA”>Los Angeles</option>
<option value=”Mountain View, CA”>Mountain View</option>
<option value=””>China</option>
<option>Australia</option>
</select>

If the first option in this select box is selected, the value of the field is “Sunnyvale, CA”.

If the first option in this select box is selected, the value of the field is “Sunnyvale, CA”.
FORMS
SCRIPTING SELECT BOXES
If the option with the text “China” is selected, then the field’s value is an empty string because
the value attribute is empty.

If the last option is selected, then the value is “Australia” because there is no
value attribute specified on the <option>.

Each <option> element is represented in the DOM by an HTMLOptionElement object. The


HTMLOptionElement type adds the following properties for easier data access:

index — The option’s index inside the options collection.


label — The option’s label
selected — A Boolean value used to indicate if the option is selected. Set this property to
true to select an option.
text — The option’s text.
value — The option’s value
FORMS
SCRIPTING SELECT BOXES
This code gets the text and value of the first option in the select box using standard DOM
techniques. Compare this to using the special option properties:

var selectbox = document.forms[0].elements[“location”];


var text = selectbox.options[0].text; //option text
var value = selectbox.options[0].value; //option value

Options Selection
For a select box that allows only one option to be selected, the easiest way to access the selected
option is by using the select box’s selectedIndex property to retrieve the option, as shown in the
following example:

var selectedOption = selectbox.options[selectbox.selectedIndex];


The BOM (Browser
The Browser Environment
Object Model) The
Browser is the most popular and natural host environment for JavaScript
DOM
programs. In today’s (Document
class you will learn about:

Object Model)
Listening to
browser events
BOM and DOM Overview
The
Objects that have to do with the currently loaded page (the page is also called the
document), andXMLHttpRequest
screen)
object
Objects that deal with things outside the page (the browser window and the desktop
Browser Object Model
These objects are accessible
Is a collection of objects that gives you access to browser and computer
screen

through the global objects window


and window.screen.
The Window object
Window.somevar = 1;
Somevar // output will be 1

All global variables become properties of Window object


All of the core JavaScript functions are methods of Window object.(parseint())
Window.navigator
These objects are accessible
The navigator is an object that has some information about the browser
and its capabilities.

through the global objects window


and window.screen.
In Firefox if we use window.navigator.userAgent will give following result

"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.12) Gecko/20080201 Firefox/2.0.0.12"

In Internet explorer if we use window.navigator.userAgent will give following


result
Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR
3.0.04506.30)
Window.navigator
if (navigator.userAgent.indexOf('MSIE') !== -1) {
// this is IE
}
else {
// not IE
}

Don’t rely on user agent string, rather use feature sniffing.

if (typeof window.addEventListener === 'function') {


// feature is supported, let's use it
} else {
// hmm, this feature is not supported, will have to
// think of another way
}
Window.location
The location property points to an object that contains information about the URL of the
currently loaded page.

Imagine you're on a page with a URL like this:

http://search.phpied.com:8080/search?p=javascript#results

for(var i in location) {
console.log(i + ' = "' + location[i] + '"')
}
href = "http://search.phpied.com:8080/search?p=javascript#results"
hash = "#results"
host = "search.phpied.com:8080"
hostname = "search.phpied.com“
pathname = "/search"
port = "8080"
protocol = "http:"
search = "?p=javascript"
Window.location
There are also three methods that location provides—reload(), assign(), and replace().

You can navigate to another page in following formats:


window.location.href = 'http://www.google.com'
location.href = 'http://www.google.com'
location = 'http://www.google.com'
location.assign('http://www.google.com')
replace() is almost the same as assign(). The difference is that it doesn't create
an entry in the browser's history list:

location.replace('http://www.yahoo.com')

To reload a page you can use:


location.reload()

Alternatively, you can use location.href to point it to itself:


window.location.href = window.location.href
Or simply: location = location
Window.history
window.history allows limited access to the previously-visited pages in the same browser
session.

window.history.length

window.history allows limited access to the previously-visited pages in the same browser
session.

window.history[0]; // You won’t see the actual url’s


You can, however, navigate back and forth through the user's session as if the user had clicked the Back/Forward
browser buttons:

history.forward()
history.back()

You can also skip pages back and forth with history.go(). This is same as calling history.back():
history.go(-1);

Two pages back:


history.go(-2);

Reload the current page:


history.go(0);
Window.screen
screen provides information about the desktop outside the browser.

You can also check the available screen real estate (the resolution):

screen.width
Screen.height
Screen.availHeight

The difference between height and availHeight is that the height is the total resolution, while
availHeight subtracts any operating system menus such as the Windows task bar. The same is
the case for width and availWidth.
Window.open()/close()
Window.open() allows you to open new browser windows(popups)

• Various browser policies and user settings may prevent you from opening a popup

• you should be able to open a new window if it was initiated by the user.

window.open() accepts the following parameters:

URL to load in the new window

Name of the new window, which can be used as the value of a form's target attribute

Comma-separated list of features, such as:

resizable—should the user be able to resize the new window

width, height of the popup

status—should the status bar be visible and so on


Window.open()/close()
var win = window.open('http://www.google.com', ‘google', 'width=300,height=300,resizable=yes');

win.close() closes the new window.


window.moveTo(), window.resizeTo()
window.moveTo(100, 100) will move the browser window to screen location x = 100 and y = 100 (counted from
the top left corner).

window.moveBy(10, -10) will move the window 10 pixels to the right and 10 pixels up from its current location.

window.resizeTo(x, y) and window.resizeBy(x, y) accept the same parameters as the move methods but they resize
the window as opposed to moving it.
window.alert(), window.prompt(), window.confirm()

confirm() gives the user two options—OK and Cancel, and

prompt() collects textual input

var answer = confirm('Are you cool?');

console.log(answer);

window.prompt() presents the user with a dialog to enter text.

var answer = prompt('And your name was?');

console.log(answer);
window.setTimeout(), window.setInterval()
setTimeout() and setInterval() allow for scheduling the execution of a piece of code.

setTimeout() executes the given code once after a specified number of milliseconds.

This will show an alert after 2 seconds (2000 milliseconds):

function boo(){
alert('Boo!');
}

setTimeout(boo, 2000);

setInterval() executes it repeatedly after a specified number of milliseconds has passed.

using setInterval() you can schedule boo() to execute every two seconds, until you cancel the scheduled
execution with clearInterval().
window.document

window.document is a BOM object that refers to the currently loaded document (page). Its methods and
properties fall into the DOM category of objects.
Document Object Model (DOM)
The DOM is a way to represent an XML or an HTML document as a tree of nodes.
Using DOM methods and properties, you can:
• Access elements on the page
• Modify or remove elements or
• Add new elements

DOM is language independent API


Take a look at this example HTML page:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>My page</title>
</head>
<body>
<p class="opener">first paragraph</p>
<p><em>second</em> paragraph</p>
<p id="closer">final</p>
<!-- and that's about it -->
</body>
</html>
Document Object Model (DOM)
Document Object Model (DOM)
Core DOM and HTML DOM

• DOM represents both XML documents and HTML documents

• HTML documents are XML documents but they are more specific

• Core DOM is applicable to all the XML documents

• HTML DOM is built upon the core DOM

• HTML DOM doesn't apply to all XML documents, but only to HTML documents
Document Object Model (DOM)
Document Object Model (DOM)
Accessing DOM Nodes

Navigating around traversing the DOM tree or by using a shortcut.

The document Node


document gives you access to the current document

Type document and hit enter


Document Object Model (DOM)
This takes you to the DOM tab where you can browse all of the properties and methods of the document
object.
Document Object Model (DOM)
All nodes (this also includes the document node, text nodes, element nodes, and attribute nodes) have
nodeType, nodeName, and nodeValue properties.

document.nodeType // 9

• There are 12 node types, represented by integers.

• The most useful are 1 (element), 2 (attribute), and 3 (text).

• Nodes also have names

• For HTML tags the node name is the tag name

• For text nodes, it is #text

• For document nodes. It is #document

• Nodes can also have node values


Document Object Model (DOM)
documentElement

XML documents always have one root node that wraps the rest of the document.
For HTML documents, the root is the <html> tag. To access the root, you use the documentElement
property of the document object

document.documentElement // <html>

nodeType is 1 (an element node):

document.documentElement.nodeType // 1

For element nodes, both nodeName and tagName properties contain the name of the tag.

document.documentElement.nodeName // “HTML”

document.documentElement.tagName // “HTML”
Document Object Model (DOM)
Child Nodes

In order to tell if a node has any children you use hasChildNodes():

document.documentElement.hasChildNodes(); // true

The HTML element has two children—the head and the body elements.

document.documentElement.childNodes.length// 2

Any child has access to its parent through the parentNode property:

document.documentElement.childNodes[1].parentNode

Let's assign a reference to body to a variable:


Document Object Model (DOM)
Child Nodes

var bd = document.documentElement.childNodes[1];

document.documentElement.hasChildNodes(); // true

bd.childNodes.length
Document Object Model (DOM)
Attributes

You can check whether an element has attributes using hasAttributes():

bd.childNodes[1].hasAttributes(); // true

How many attributes? In this example?

bd.childNodes[1].attributes.length// 1

bd.childNodes[1].attributes[0].nodeName //

bd.childNodes[1].attributes[0].nodeValue //

bd.childNodes[1].attributes[‘class’].nodeValue //

bd.childNodes[1]. getAttribute('class') //
Document Object Model (DOM)
Accessing the Content Inside a Tag

bd.childNodes[1].nodeName // P

You can get the text contained in the paragraph by using the textContent property.

bg.childNodes[1].textContent // “first paragraph”

textContent doesn't exist in IE, but another property called innerText does and it returns the same
value.
bg.childNodes[1]. innerText // “first paragraph”

There is also the innerHTML property. It's not part of the DOM standard, but exists in all major
browsers. It returns any HTML code contained in the node.
Document Object Model (DOM)
bd.childNodes[1].innerHTML // “first paragraph”

The first paragraph only has text, so innerHTML is the same as textContent (or innerText in IE).

bd.childNodes[3].innerHTML // "<em>second</em> paragraph"

bd.childNodes[3].textContent // “second paragraph”

Another way to get the text contained in the first paragraph is by using the nodeValue of the text
node contain inside the p node:

bd.childNodes[1].childNodes.length// 1

bd.childNodes[1].childNodes[0].nodeName // “#text”

bd.childNodes[1].childNodes[0].nodeValue // “first paragraph”


Document Object Model (DOM)
DOM Access Shortcuts

By using childNodes, parentNode, nodeName, nodeValue, and attributes, you can


navigate up and down the tree and pretty much do anything with the document.

But the fact that white space is a text node makes this a slightly fragile way of working
with the DOM.

If the page changes slightly, your script may no longer work correctly. Also, if you want
to get to a node deeper in the tree, it might take a bit of code before you get there.

That's why we have the shortcut methods—getElementsByTagName(),


getElementsByName(), and getElementById().
Document Object Model (DOM)
DOM Access Shortcuts

getElementsByTagName() takes a tag name (the name of an element node) and returns
an HTML collection (array-like object) of nodes with the matching tag name:

document.getElementsByTagName('p').length // 3

You can access an item in the list, by using the brackets notation, or the method item(),
and passing the index (0 for the first element). Using item() is discouraged, as array
brackets are more consistent and also shorter to type.

document.getElementsByTagName('p')[0] // <p class=“opener”>

document.getElementsByTagName('p').item(0) // <p class=“opener”>


Document Object Model (DOM)
Getting the contents of the first p:

document.getElementsByTagName('p')[0].innerHTML // “first paragraph”

Accessing the last p:

document.getElementsByTagName('p')[2] // <p id=“closer”>

In order to access element's attributes, you can use the attributes collection, or getAttribute() as
shown in previous slides. But a shorter way is to use the attribute name as a property of the
element you're working with. So to get the value of the id attribute, you just use id as a property:

document.getElementsByTagName('p')[2].id // “closer”

Getting the class attribute of the first paragraph won't work though. It's an exception, because it
just happens so that "class" is a reserved word in ECMAScript. You can use className instead:
Document Object Model (DOM)
Getting the contents of the first p:

document.getElementsByTagName('p')[0].className // “Opener”

Using getElementsByTagName() you can get all of the elements on the page:

document.getElementsByTagName('*').length // 9

In earlier versions of IE, '*' is not acceptable as a tag name. In order to get all elements you can
use IE's proprietary document.all collection, although selecting every element is rarely useful.

The other shortcut mentioned above is getElementById(). This is probably the most common way
of accessing an element.
Document Object Model (DOM)
Siblings, Body, First, and Last Child

nextSibling and previousSibling are two other convenient properties to navigate the DOM
tree, once you have a reference to one element:

var para = document.getElementById('closer’);

para.nextSibling // “\n”

document.body.nextSibling //

document.body. previousSibling //

Creating New Nodes

In order to create new nodes, you can use the methods createElement() and
createTextNode(). Once you have the new nodes, you add them to the DOM tree with
appendChild().
Document Object Model (DOM)
Creating New Nodes

Creating a new p element and setting its innerHTML:

var myp = document.createElement('p');


myp.innerHTML = 'yet another';

The new element automatically gets all the default properties, such as style, which you
can modify:

myp.style.border = '2px dotted blue' ;

Using appendChild() you can add the new node to the DOM tree. Calling this method on the
document.body node means creating one more child node right after the last child:

document.body.appendChild(myp)
What are Cookies?
• Cookies are data, stored in small text files, on your computer.

• Cookies were invented to solve the problem "how to remember information about the
user":

• When a user visits a web page, his name can be stored in a cookie.

• Next time the user visits the page, the cookie "remembers" his name.

• When a browser request a web page from a server, cookies belonging to the page is
added to the request. This way the server gets the necessary data to "remember"
information about users.

Create a Cookie with JavaScript

• JavaScript can create cookies, read cookies, and delete cookies with the property
document.cookie
What are Cookies?
Create a Cookie with JavaScript

document.cookie="username=John Doe";

You can also add an expiry date (in UTC or GMT time). By default, the cookie is
deleted when the browser is closed:

document.cookie="username=John Doe; expires=Thu, 18 Dec 2013


12:00:00 GMT";

Read a Cookie with JavaScript

var x = document.cookie;

document.cookie will return all cookies in one string much like: cookie1=value;
cookie2=value; cookie3=value;
What are Cookies?
JavaScript Cookie Example

For the example we will create 3 JavaScript functions:

• A function to set a cookie value


• A function to get a cookie value

A Function to Set a Cookie

function setCookie(cname,cvalue,exdays)
{
var d = new Date();
d.setTime(d.getTime()+(exdays*24*60*60*1000));
var expires = "expires="+d.toGMTString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
What are Cookies?
JavaScript Cookie Example

A Function to Get a Cookie

function getCookie(cname)
{
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++)
{
var c = ca[i].trim();
if (c.indexOf(name)==0) return c.substring(name.length,c.length);
}
return "";
}
What are Cookies?
JavaScript Cookie Example

A Function to Get a Cookie

function getCookie(cname)
{
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++)
{
var c = ca[i].trim();
if (c.indexOf(name)==0) return c.substring(name.length,c.length);
}
return "";
}
Objects
• How to create and use objects
• What are the constructor functions
• What types of built-in JavaScript objects exist and what they can do for you

An object is very similar to an array but with the difference that you define the keys
yourself.

You're not limited to using only numeric indexes but can use friendlier keys, such as
first_name, age, and so on.

Let's take a look at a simple object and examine its parts:


var hero = {
 breed: 'Turtle',
occupation: 'Ninja'
};
Objects
• The name of the variable that contains the object is hero
• Instead of [ and ] which you use to define an array, you use { and } for objects
• You separate the elements (called properties) contained in the object with commas
• The key/value pairs are divided by colons, as key: value

The keys (names of the properties) can optionally be placed in quotation marks. For
example these are all the same:

var o = {prop: 1};


var o = {"prop": 1};
var o = {'prop': 1};
Objects

It's recommended that you don't quote the names of the properties (it is also less typing!),
but there are some cases when you have must use quotes:

• If the property name is one of the reserved words in JavaScript


• If it contains spaces or special characters (anything other than letters, numbers,
and the underscore character)
• If it starts with a number

var o = {
something: 1,
'yes or no': 'yes',
'!@#$%^&*': true
};
Objects
Elements, Properties, Methods

When talking about arrays, you say that they contain elements. When talking about
objects, you say that they contain properties.

A property of an object can contain a function, because functions are just data. In this
case, you say that this property is a method.

var dog = {
 name: 'Benji',
talk: function(){
   alert('Woof, woof!');
}
};
Objects
Hashes, Associative Arrays

In some programming languages, there is distinction between:

A normal array, also called indexed or enumerated (the keys are numbers) and An
associative array, also called a hash (the keys are strings)

JavaScript uses arrays to represent indexed arrays and objects to represent associative
arrays. If you want a hash in JavaScript, you use an object.
Objects
Accessing Object's Properties

There are two ways to access a property of an object:

• Using square bracket notation, for example hero['occupation']


• Using the dot notation, for example hero.occupation

The dot notation is easier to read and write but it cannot always be used. The same
rules apply as for quoting property names: if the name of the property is not a valid
variable name, you cannot use the dot notation.

Let's take this object:


var hero = {
 breed: 'Turtle',
occupation: 'Ninja'
};
Objects
Accessing Object's Properties

Accessing a non-existing property returns undefined:


'Hair color is ' + hero.hair_color;
"Hair color is undefined"

Objects can contain any data, including other objects.


var book = {
name: 'Catch-22',
published: 1961,
author: {
   firstname: 'Joseph',
lastname: 'Heller'
}
};
Objects
Calling an Object's Methods

Because a method is just a property that happens to be a function, you can access
methods in the same way as you would access properties: using the dot notation or
using square brackets.

Calling (invoking) a method is the same as calling any other function: just add
parentheses after the method name, which effectively say "Execute!".

var hero = {
 breed: 'Turtle',
occupation: 'Ninja',
say: function() {
   return 'I am ' + hero.occupation;
}
}
hero.say();
Objects
Altering Properties/Methods

JavaScript is a dynamic language; it allows you to alter properties and methods of


existing objects at any time. This includes adding new properties or deleting them.

You can start with a blank object and add properties later. Let's see how you can go
about doing this.

An empty object:
var hero = {};
Accessing a non-existing property:
typeof hero.breed // "undefined"

Adding some properties and a method:


>>> hero.breed = 'turtle';
>>> hero.name = 'Leonardo';
>>> hero.sayName = function() {return hero.name;};
Objects
Altering Properties/Methods

Deleting a property:
>>> delete hero.name;
true
Calling the method again will no longer work:
>>> hero.sayName();
reference to undefined property hero.name

In the previous example, the method sayName() used hero.name to access the name
property of the hero object. When you're inside a method though, there is another way to
access the object this method belongs to: by using the special value this.
var hero = {
 name: 'Rafaelo',
sayName: function() {
   return this.name;
}
}
Objects
Constructor Functions

There is another way to create objects: by using constructor functions. Let's see an
example:

function Hero() {
this.occupation = 'Ninja';
}

In order to create an object using this function, you use the new operator, like this:

>>> var hero = new Hero();


>>> hero.occupation;
"Ninja"
Objects
Constructor Functions

The benefit of using constructor functions is that they accept parameters, which can
be used when creating new objects. Let's modify the constructor to accept one
parameter and assign it to the name property.

function Hero(name) {
 this.name = name;
this.occupation = 'Ninja';
this.whoAreYou = function() {
   return "I'm " + this.name + " and I'm a " + this.occupation;
}
}
Objects
Constructor Functions

Now you can create different objects using the same constructor:

>>> var h1 = new Hero('Michelangelo');


>>> var h2 = new Hero('Donatello');

>>> h1.whoAreYou();
'"I'm Michelangelo and I'm a Ninja“

>>> h2.whoAreYou();
''"I'm Donatello and I'm a Ninja"
Objects
constructor Property
When an object is created, a special property is assigned to it behind the scenes—the
constructor property. It contains a reference to the constructor function used to
create this object.

function Hero(name) {
this.name = name;
}
var h = new Hero('Leonardo');
h.constructor // Hero(name)

Because the constructor property contains a reference to a function, you might as


well call this function to produce a new object. The following code is like saying, "I
don't care how object h2 was created, but I want another one just like it".

var h3 = new h.constructor('Rafaello');


>>> h3.name;
Objects
instanceof Operator
Using the instanceof operator, you can test if an object was created with a specific
constructor function:
>>> function Hero(){}
>>> var h = new Hero();
>>> var o = {};
>>> h instanceof Hero;
true
>>> h instanceof Object;
false
>>> o instanceof Object;
True

Note that you don't put parentheses after the function name (don't
use h instanceof Hero()). This is because you're not invoking this
function, but just referring to it by name, as for any other variable.
Objects
Comparing Objects

When you compare objects, you'll get true only if you compare two references to the
same object. Comparing two distinct objects that happen to have the exact same
methods and properties will return false.
Let's create two objects that look the same:
>>> var fido = {breed: 'dog'};
>>> var benji = {breed: 'dog'};

Comparing them will return false:


>>> benji === fido
False

You can create a new variable mydog and assign one of the objects to it, this way
mydog actually points to the same object.

>>> var mydog = benji;


Objects
Comparing Objects
In this case benji is mydog because they are the same object (changing mydog's
properties will change benji's). The comparison returns true.

>>> mydog === benji


True

And because fido is a different object, it does not compare to mydog:


>>> mydog === fido
false
AJAX
• Basic objects necessary
• Setting up the XMLHttpRequest object
• Making the call
• How the server responds
• Using the reply
The usual way we operate in the Web
Typical browsing behaviour consists of loading a web page, then selecting some action that we
want to do, filling out a form, submitting the information, etc.

We work in this sequential manner, requesting one page at a time, and have to wait for the
server to respond, loading a whole new web page before we continue.

This is also one of the limitations of web pages, where transmitting information between a
client and server generally requires a new page to be loaded.

JavaScript is one way to cut down on (some of) the client-server response time, by using it to
verify form (or other) information before it’s submitted to a server.

One of the limitations of JavaScript is (or used to be) that there was no way to communicate
directly with a web server.

Another drawback to this usual sequential access method is that there are many situations
where you load a new page that shares lots of the same parts as the old (consider the case
where you have a “menu bar” on the top or side of the page that doesn’t change from page to
page).
Things change…

Until recently, we didn’t have any alternative to this load/wait/respond method of


web browsing.

Ajax (sometimes written AJAX) is a means of using JavaScript to communicate with


a web server without submitting a form or loading a new page.

Ajax makes use of a built-in object, XMLHttpRequest, to perform this function.

This object is not yet part of the DOM (Document Object Model) standard, but is
supported (in different fashions) by Firefox, Internet Explorer, Safari, Opera, and
other popular browsers.

The term “Ajax” was coined in 2005, but the XMLHttpRequest object was first
supported by Internet Explorer several years before this.
Ajax
Ajax stands for “Asynchronous JavaScript and XML”.
The word “asynchronous” means that the user isn’t left waiting for the server the
respond to a request, but can continue using the web page.

The typical method for using Ajax is the following:

1) A JavaScript creates an XMLHttpRequest object, initializes it with


relevant information as necessary, and sends it to the server. The
script (or web page) can continue after sending it to the server.

2) The server responds by sending the contents of a file or the output of a


server side program (written, for example, in PHP).

3) When the response arrives from the server, a JavaScript function is


triggered to act on the data supplied by the server.

4) This JavaScript response function typically refreshes the display using


the DOM, avoiding the requirement to reload or refresh the entire page.
The Back End
• The part of the Ajax application that resides on the web server is referred to as
the “back end”.

• This back end could be simply a file that the server passes back to the client,
which is then displayed for the user.

• Alternatively, the back end could be a program, written in PHP, Perl, Ruby,
Python, C, or some other language that performs an operation and sends results
back to the client browser.

• An XMLHttpRequest object can send information using the GET and POST
methods to the server in the same way that an HTML form sends information.

• Recall from our previous discussions that the GET request encodes the
information inside of the URL, while a POST request sends its data separately
(and can contain more information than a GET request can).
Writing an Ajax application
• We have to write the “front end” of the application in JavaScript to initiate the request.

• The back end, as mentioned, processes the request and sends it’s response back to the client.
The back end is typically a short program we write for performing some dedicated task.
This could be scripted in any language that is capable of sending back communication to
the browser, like PHP or Perl.

• We also need to write the JavaScript response function for processing the response and
displaying any results (or alterations to the web page).

• The “x” in Ajax stands for XML, the extensible markup language. XML looks like HTML,
which is no mistake as the latest versions of HTML are built upon XML. The back end
could send data back in XML format and the JavaScript response function can process it
using built-in functions for working with XML. The back end could also send plain text,
HTML, or even data in the JavaScript format.

• We will discuss some of these methods for sending data back to the requesting client and
how it can be processed.
The XMLHttpRequest object

The XMLHttpRequest object is the backbone of every Ajax method. Each application
requires the creation of one of these objects. So how do we do it?

As with most things in web programming, this depends upon the web browser that the
client is using because of the different ways in which the object has been implemented
in the browsers.

Firefox, Safari, Opera, and some other browsers can create one of these objects simply
using the “new” keyword.

<script type="text/javascript">
ajaxRequest = new XMLHttpRequest();
</script>
The XMLHttpRequest object (cont..)

Microsoft Internet Explorer implements this object using its proprietary ActiveX
technology. This requires a different syntax for creating the object (and can also
depend upon the particular version of Internet Explorer being used).

To handle different types of browsers, we use the


try { . . . } catch (error) { . . . }
format. The “try” section attempts to execute some JavaScript code. If an error
occurs, the “catch” section is used to intervene before the error crashes the JavaScript
(either to indicate an error has happened, or to attempt something else).

To create one of these objects we can use a sequence of try. . . catch blocks, attempting
different ways to create an XMLHttpRequest object.
The XMLHttpRequest object (cont..)
function getXMLHttpRequest()
/* This function attempts to get an Ajax request object by trying
a few different methods for different browsers. */
{
var request, err;
try {
request = new XMLHttpRequest(); // Firefox, Safari, Opera, etc.
}
catch(err) {
try { // first attempt for Internet Explorer
request = new ActiveXObject("MSXML2.XMLHttp.6.0");
}
catch (err) {
try { // second attempt for Internet Explorer
request = new ActiveXObject("MSXML2.XMLHttp.3.0");
}
catch (err) {
request = false; // oops, can’t create one!
}
}
}
return request;
}
If this function doesn’t return “false” then we were successful in creating an XMLHttpRequest object.
The XMLHttpRequest object (cont..)

• As with any object in JavaScript (and other programming languages), the


XMLHttpRequest object contains various properties and methods.

• We list the most important of these properties and methods on the next pages.

• The main idea is that the properties are set after the object is created to specify
information to be sent to the server, as well as how to handle the response received
from the server. Some properties will be updated to hold status information about
whether the request finished successfully.

• The methods are used to send the request to the server, and to monitor the progress
of the request as it is executed (and to determine if it was completed successfully).
XMLHttpRequest object properties
Property Description
readyState An integer from 0. . .4. (0 means the call
is uninitialized, 4 means that the call is
complete.)
onreadystatechange Determines the function called when the
objects readyState changes.
responseText Data returned from the server as a text
string (read-only).
responseXML Data returned from the server as an XML
document object (read-only).
status HTTP status code returned by the server
statusText HTTP status phrase returned by the server

We use the readyState to determine when the request has been completed, and then
check the status to see if it executed without an error. (We’ll see how to do this
shortly.)
XMLHttpRequest object properties
Property Description
open('method', 'URL', asyn) Specifies the HTTP method to be used (GET
or POST as a string, the target URL, and
whether or not the request should be
handled asynchronously (asyn should be
true or false, if omitted, true is assumed).
send(content) Sends the data for a POST request and
starts the request, if GET is used you should call
send(null).
setRequestHeader('x','y') Sets a parameter and value pair x=y and
assigns it to the header to be sent with
the request.
getAllResponseHeaders() Returns all headers as a string.
getResponseHeader(x) Returns header x as a string.
abort() Stops the current operation.

The open object method is used to set up the request, and the send method starts the request by
sending it to the server (with data for the server if the POST method is used).
A general skeleton for an Ajax application
<script type="text/javascript">
// ***** include the getXMLHttpRequest function defined before
var ajaxRequest = getXMLHttpRequest();

if (ajaxRequest) { // if the object was created successfully

ajaxRequest.onreadystatechange = ajaxResponse;

ajaxRequest.open("GET", "search.php?query=Bob");
ajaxRequest.send(null);
}

function ajaxResponse() //This gets called when the readyState changes.


{
if (ajaxRequest.readyState != 4) // check to see if we’re done
{ return; }
else {
if (ajaxRequest.status == 200) // check to see if successful
{ // process server data here. . . }
else {
alert("Request failed: " + ajaxRequest.statusText);
}
}
}
</script>
Prototype
• Every function has a prototype property and it contains an object

• Adding properties to the prototype object

• Using the properties added to the prototype

• How to enhance built-in objects, such as arrays or strings


Prototype
• prototype is a property that gets created as soon as you define the function. Its
initial value is an empty object.

function foo(a, b){


return a * b;
}

foo.length // 2
foo.constructor // function()
typeof foo.prototype // object

• You can augment this empty object with properties and methods. They won't have
any effect of the foo() function itself; they'll only be used when you use foo() as a
constructor.
Adding Methods and Properties Using the
Prototype
• Let's take a look at the constructor function Gadget() which uses this to add two
properties and one method to the objects it creates.

function Gadget(name, color) {


this.name = name;
this.color = color;
this.whatAreYou = function(){
return 'I am a ' + this.color + ' ' + this.name;
}
}

• Adding methods and properties to the prototype property of the constructor


function is another way to add functionality to the objects this constructor produces.
Adding Methods and Properties Using the
Prototype
• Let's add two more properties, price and rating, and a getInfo() method. Since
prototype contains an object, you can just keep adding to it like this:

Gadget.prototype.price = 100;
Gadget.prototype.rating = 3;
Gadget.prototype.getInfo = function() {
return 'Rating: ' + this.rating + ', price: ' + this.price;
};

• Instead of adding to the prototype object, another way to achieve the above result is
to overwrite the prototype completely, replacing it with an object of your choice:
Adding Methods and Properties Using the
Prototype
Gadget.prototype = {
price: 100,
rating: 3,
getInfo: function() {
return 'Rating: ' + this.rating + ', price: ' + this.price;
}
};
Using the Prototype's Methods and Properties
• All the methods and properties you have added to the prototype are directly available
as soon as you create a new object using the constructor.

• If you create a newtoy object using the Gadget() constructor, you can access all the
methods and properties already defined.

var newtoy = new Gadget('webcam', 'black');


>>> newtoy.name;
"webcam"
>>> newtoy.color;
"black"
>>> newtoy.whatAreYou();
"I am a black webcam"
>>> newtoy.price; // 100
Using the Prototype's Methods and Properties
>>> newtoy.rating;
3
>>> newtoy.getInfo();
"Rating: 3, price: 100"

• It's important to note that the prototype is "live". Objects are passed by reference in
JavaScript, and therefore the prototype is not copied with every new object instance.
What does this mean in practice? It means that you can modify the prototype at any
time and all objects (even those created before the modification) will inherit the
changes.

Let's continue the example, adding a new method to the prototype:


Gadget.prototype.get = function(what) {
return this[what];
};
Using the Prototype's Methods and Properties
Even though newtoy was created before the get() method was defined, newtoy will still
have access to the new method:
>>> newtoy.get('price');
100
>>> newtoy.get('color');
"black"
isPrototypeOf()
Every object also gets the isPrototypeOf() method. This method tells you whether
that specific object is used as a prototype of another object.
Let's take a simple object monkey.

var monkey = {
hair: true,
feeds: 'bananas',
breathes: 'air'
};
Now let's create a Human() constructor function and set its prototype property to
point to monkey.

function Human(name) {
this.name = name;
}
Human.prototype = monkey;
isPrototypeOf()
Now if you create a new Human object called george and ask: "Is monkey george's
prototype?", you'll get true.

>>> var george = new Human('George');


>>> monkey.isPrototypeOf(george)
Augmenting Built-in Objects
The built-in objects such as the constructor functions Array, String, and even Object,
and Function can be augmented through their prototypes, which means that you can,
for example, add new methods to the Array prototype and in this way make them
available to all arrays. Let's do this.

Array.prototype.inArray = function(needle) {
for (var i = 0, len = this.length; i < len; i++) {
if (this[i] === needle) {
return true;
}
}
return false;
}

>>> var a = ['red', 'green', 'blue'];


>>> a.inArray('red');
true
>>> a.inArray('yellow'); // False
Thank You

You might also like