Professional Documents
Culture Documents
Javascript
Javascript
• 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
Identifiers
• 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.
• 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
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;
}
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.
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.
There are five simple data types (also called primitive types) in ECMAScript:
Undefined, Null, Boolean, Number, and String.
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
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”
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.
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
The most interesting data type in ECMAScript is Number, which uses the IEEE-754
format to represent both integers and floating-point values.
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
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.
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.
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.
Range of Values
Not all numbers in the world can be represented in ECMAScript, because of
memory constraints.
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.
• 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
• 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).
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:
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’;
There are two ways to convert a value into a string. The first is to use the toString()
method that almost every value has.
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.
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.
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 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,
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:
Equality Operators
Conditional Operator
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:
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:
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
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.
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:
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).
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.
The event flow specified by DOM Level 2 Events has three phases: the event
capturing phase, at the target, and the event bubbling phase.
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.
For example, to execute some JavaScript when a button is clicked, you can
use the following:
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>
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:
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:
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:
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.
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;
}
},
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.
btn.addEventListener(“click”, function(event){
alert(event.type); //”click”
}, false);
The event object contains properties and methods related to the specific event that caused its
creation.
Events
Events
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
document.body.onclick = function(event){
alert(“Body clicked”);
};
Events
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:
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
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.
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.
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 = /j.*t/;
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.
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.
multiline: Search matches that may span over more than one line, defaults to false.
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:
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
Form Basics
Web forms are represented by the <form> element in HTML and by the
HTMLFormElement type in JavaScript.
action — The URL to send the request to; equivalent to the HTML action attribute.
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.
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:
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”>
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:
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”>
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.
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
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
form — A pointer to the form that the field belongs to. This property is read only.
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 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.
All form fields support the following three events in addition to mouse, keyboard, and
HTML events:
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.
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.
if (target.style.backgroundColor != “red”){
target.style.backgroundColor = “yellow”;
}
});
FORMS
Common Form-Field Events
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:
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
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:
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:
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
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.
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.
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 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:
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>.
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:
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
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().
location.replace('http://www.yahoo.com')
window.history.length
window.history allows limited access to the previously-visited pages in the same browser
session.
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);
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.
Name of the new window, which can be used as the value of a form's target attribute
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()
console.log(answer);
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.
function boo(){
alert('Boo!');
}
setTimeout(boo, 2000);
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
• HTML documents are XML documents but they are more specific
• 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
document.nodeType // 9
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>
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
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
var bd = document.documentElement.childNodes[1];
document.documentElement.hasChildNodes(); // true
bd.childNodes.length
Document Object Model (DOM)
Attributes
bd.childNodes[1].hasAttributes(); // true
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.
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).
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”
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.
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.
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:
para.nextSibling // “\n”
document.body.nextSibling //
document.body. previousSibling //
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
The new element automatically gets all the default properties, such as style, which you
can modify:
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.
• 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:
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
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
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
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.
The keys (names of the properties) can optionally be placed in quotation marks. For
example these are all the same:
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:
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
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
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.
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
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"
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:
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:
>>> 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)
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'};
You can create a new variable mydog and assign one of the objects to it, this way
mydog actually points to the same object.
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…
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.
• 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 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..)
• 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();
ajaxRequest.onreadystatechange = ajaxResponse;
ajaxRequest.open("GET", "search.php?query=Bob");
ajaxRequest.send(null);
}
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.
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.
• 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.
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.
Array.prototype.inArray = function(needle) {
for (var i = 0, len = this.length; i < len; i++) {
if (this[i] === needle) {
return true;
}
}
return false;
}