JavaScript - zone0ne.com

Download Report

Transcript JavaScript - zone0ne.com

JavaScript
Todd Schacherl
What is JavaScript?
•
•
•
•
Scripting vs Programming
Advantages
Disadvantages
Integrating into HTML
Scripting vs Programming
• Not Compiled
• Higher Level Language
Advantages
•
•
•
•
Quick Development
Easy to Learn
Platform Independence
Small Overhead
Disadvantages
• No Code Hiding
• Lack of Debugging and Development Tools
• Not Fully Extensible (limited base of
objects, properties, methods, and data types)
Integrating into HTML
•
•
•
•
<script> and <noscript> Tags
Where to Put JavaScript Code
Command Block Structure
Output Functions
<script> and <noscript> Tags
<script src=“url” language=“javascript”>
Commands...
</script>
<noscript>
HTML...
</noscript>
Where to Put JavaScript Code
• Between <head></head> tags
• Anywhere in between the <body>...</body>
tags
Command Block Structure
• Multiple commands combined into
command blocks with curly braces ({ and })
{
document.writeln(“Hello World”);
document.writeln(“This is neat<br>”);
}
• Embedded blocks
{
JavaScript Code
{
More code
}
}
Output Functions
• document.write()
– Writes text and HTML to document
• document.writeln()
– Writes text and HTML followed by a newline
character to document
document.write(“Hello World\n”);
document.writeln(“Hello World”);
The JavaScript Object Model
•
•
•
•
•
Object Methods
Object Properties
Navigator Objects
Internal or Built-in Objects
HTML-Reflected Objects
Object Methods
• Objects have methods associated with them
that allow objects to be manipulated and
interrogated and in some cases, allow object
values to be changed.
• document.write(“Hello World”);
Object Properties
• Another term used in context to an objectdriven environment is a property. A
property is a value that belongs to an object.
All of the standard JavaScript objects have
such properties.
• object-name.property-name
document.url
document.body.bgcolor
Navigator Objects
• window -- Top-level object in JavaScript object
hierarchy.
• document -- Contains properties that relate to the
current HTML document.
• location -- Contains properties relating to the
current document’s location
• navigator -- Details about the current version of
Navigator
• history -- Contains details of all URLs the user has
visited in the current Navigator session
Internal or Built-in Objects
•
•
•
•
•
Array -- Array structure
Date -- Internal date and time manipulation
Math -- Mathematical object and properties
Object -- Generic object type
String -- Text string object
HTML-Reflected Objects
•
•
•
•
•
•
•
•
•
•
•
•
anchor (anchors array) -- Array of <a name> tags in current document
button -- A hypertext button created with <input type=button>
checkbox -- A checkbox created with <input type=checkbox>
elements -- All of the elements within a <form> container
form (forms array) -- An array of HTML <form> container objects
frames (frames array) -- A frameset-docuement object (window)
hidden -- A hidden text field created with <input type=hidden>
images (images array) -- an array of images, that is, <img> tags in the
current document
link -- An array of hyperlinks in the current document
navigator -- Version and client information object
password -- An <input type=password> field
radio -- A radio box created with <input type=radio>
HTML-Reflected Objects (cont.)
•
•
•
•
•
reset -- A reset button created with <input type=reset>
select (options array) -- A <select> objects <option> elements
submit -- A submit button created with <input type=submit>
text -- A text-field created with <input type=text>
textarea -- A textarea field created with a <textarea> container
Working with Data and
Information
•
•
•
•
Data Types
Using Variables
Assignment Expressions
Operators
Data Types
• Numbers -- Any number, such as 1, 23,
34.5, or 34e9
• Strings -- “Hello!” or ‘Goodbye’
• Boolean -- Either true or false
• Null -- a special keyword for exactly that the null value (that is, nothing)
Using Variables
• Creating Variables
• Using Variables
Creating Variables
• var variableName
– var answer;
• Use in a “variable” context
– answer=100;
Using Variables
• Use by name
var message=“Hello World!”;
document.write(message);
Assignment Expressions
• = Assigns value of right operand to the left operand
• += Adds the left and right operands and assigns the result to the left
operand
• -= Subtracts the right operand from the left operand and assigns the
result to the left operand
• *= Multiplies the two operands and assigns the result to the left
operand
• /= Divides the left operand by the right operand and assigns the value
to the left operand
• %= Divides the left operand by the right operand and assigns the
remainder to the left operand
Operators
• Arithmetic Operators
• Logical Operators
• Comparison Operators
Arithmetic Operators
•
•
•
•
•
•
•
•
+ Addition -- 3 + 8;
- Subtraction -- 31.5 - 12.8;
* Multiplication -- 34 * 12;
/ Division -- 45 / 5
% Modulus 12 % 5
++ Increment -- var++ or ++var
-- Decrement -- var-- or --var
- Unary negation -- x = -x;
Logical Operators
• && Logical “and” -- returns true when both
operands are true; otherwise it returns false
• || Logical “or” -- returns true if either operand is
true. It only returns false when both operands are
false
• ! Logical “not” -- returns true if the operand is
false and fase if the operand is true. This is a
unary operator and precedes the operand
Comparison Operator
• == Returns true if the operands are equal
• != Returns true if the operands are not equal
• > Returns true if the left operand is greater than the right
operand
• < Returns true if the left operand is less than the right
operand
• >= Returns true if the left operand is greater than or equal
to the right operand
• <= Returns true if the left operand is less than or equal to
the right operand
Functions and Objects
•
•
•
•
•
•
•
Defining Functions
Creating New Objects,
Defining Properties
Adding Methods
Passing Parameters
Variable Scope
Returning Results
Defining Functions
• Function command
function dosomething(parameters, values)
{
commands;
}
Creating New Objects
Function item(price, partNumber, description)
{
this.price = price;
this.partNumber = partNumber;
this.description = description;
}
item1 = new item(“2.95”, “100134-001”, “Widget”);
Adding Methods
function methodName()
{
some code;
}
Function item(price, partNumber, description)
{
this.price = price;
this.partNumber = partNumber;
this.description = description;
this.methodName = methodName;
}
Passing Parameters
function printName(name)
{
document.write(name);
}
printName(“Bob”);
var userName=“John”;
printName(userName);
Variable Scope
• Variables Come Into Existance Within a
Function
• Variables Cease to Exist When Function
Ends
Returning Results
function cube(number)
{
var cube= number * number * number;
return cube;
}
Using JavaScript Events
•
•
•
•
Document Events
Form Events
Image Events
Mouse Events
Document Events
• Document Loading and Unloading
– onLoad
• When a document is loaded
– onUnLoad
• Allows an event to be associated with the unloading
of a document or frameset-document.
<body onLoad=“expr | function()”>…</body>
Form Events
• Click Events: buttons, radio buttons,
checkboxes, submit, and reset buttons
• Focus, Blur, and Change Events: text-areas,
and selection-lists;
• Select Events: text-fields, and text areas.
Form Elements
• onBlur
– removes input focus from form element
• onChange
– Changes value of text, textarea, or select
element
• onFocus
– Gives a form element input focus
Form Elements
• onSelect
– Selects form element’s input field
• onSubmit
– Submits a form
Image Events
• Image Loading
– onLoad - The image is loaded onto the page. Animated DIG images
will throw an onLoad event every time the image repeats from the first
animation-frame
• Image Loading Error
– onError - An error occurs when loading the image, that is, the image
des not exist, or the image is corrupted, or the server providing the image
hanges, i.e., crashes or dies, etc.
• Image Load Abort
– onAbort -The user clicks on a link or presses Stop or ESC
when the current image is being loaded
Mouse Events
• mouseOver
– Mouse pointer moves onto a hyperlink
• mouseOut
– Mouse pointer moves away from a hyperlink
• onClick
– Clicks on form element or link
Creating Interactive Forms
• The Form Object
• Working with Form Elements
The Form Object
• The form object reflects an HTML form in
JavaScript. Each HTML form in a
document is reflected by a distinct instance
of the from object.
Working with Form Elements
• Properties
– Action -- A string value specifying the URL to which the form data
is submitted.
– Elements -- Array of objects for each form element n the order in
which they appear in the form.
– Encoding -- String containing the MIME encoding of the form as
specified in the ENCTYPE attribute.
– Method -- A string value containing the method of submission of
form data to the server.
– Target -- A string value containing the name of the window that
responses to formsubmissions are directed to.
Working with Form Elements
• Methods
– Submit() -- Submits the form.
• Event Handlers
– onSubmit -- specifies JavaScript code to
execute when the form is submitted. The code
should return a true value to allow the form to
be submitted. A false value prevents for form
from being submitted.
onSubmit
• Use to validate forms prior to submission
• Don’t use the submit button type
<input type=button onSubmit=“doSomething(this);”>
Loops
•
•
•
•
For
For in
While
Break and Continue
For
• The condition is evaluated at the start of
each pass through the loop
for(i=8; i<5; i++)
{
some commands;
}
For In
• Used to step through all the properties in an
object
for (k in testObject)
{
commands
}
While
• Proccess commands until a condition no
longer exists (becomes false)
while (condition)
{
some commands;
}
Break and Continue
• Break is used to break out of a loop, such as
a for or while loop, terminating it at the
point the statement is reached and then
passing control to the next statement
immediately after the loop.
• Continue is used to terminate the executoin
of a block of statements that exist within a
for, for…in, or while loop, continuing
execution of the loop at the next iteration.
Conditional Statements
• if…else
• The ? Statement
if…else
• Conditional statement that allows one or
more JavaScript statements to be executed,
depending on a user-defined condition.
If (some condition) {
then some commands;
} else {
Some other commands;
}
The ? Statement
• (condition) ? val1: val2
(day == “Saturday”) ? “Weekend!” : “Not Saturday!”;
Frames, Documents, and
Windows
•
•
•
•
The Document Object
The Window Object
Opening and Closing Windows
Cross-Frame Communication
The Document Object
• Provides properties and methods to work
with the numerous aspects of the current
document
– Anchors, forms, links, the title, current location
and URL, and current colors
The Window Object
• Parent object of each loaded document
Opening and Closing Windows
• var newWindow = window.open(“URL”,
“windowName”, [“windowFeatures, …”]);
• winName.close();
Window Features
Attribute
Values
Description
copyhistory
directories
height
location
menubar
resizable
scrollbars
toolbar
width
[=yes|no] | [=1|0]
[=yes|no] | [=1|0]
= pixelheight
[=yes|no] | [=1|0]
[=yes|no] | [=1|0]
[=yes|no] | [=1|0]
[=yes|no] | [=1|0]
[=yes|no] | [=1|0]
= pixelwidth
Copy the history? (yes/no)
Directory buttons (on/off)
Window height (pixels)
Location bar (on/off)
Menu-bar (on/off)
Resizable window? (yes/no)
Scroll-bars? (yes/no)
Toolbar mode (on/off)
Window width (pixels)
Cross-Frame Communication
• _blank
– Always load this link into a new, unnamed window. A
new window is actually treated as a single frame.
• _self
– Always load this link over the current frame
• _parent
– Always load this link over the parent frame. This
becomes _self if not parent exists.
• _top
– Always load this link at the top level. If you are
already at the top level, this becomes _self.
Cookies
• Cookies & CGI
– Processed by Server
• Cookies in JavaScript
– Processed by Client (Browser)
Cookies in JavaScript
• name=NAME
– The name of the cookie
• value=VALUE
– The value(s) being stored by the cookie
• expires=DATE
– The expiry date of a cookie. After this date the cookie will no longer be
stored by the client or sent to the server (DATE takes the form Wdy, DDMon-YY HH:MM:SS GMT -- dates are only stored in Greenwich Mean
Time). By default, the value of expires is set to the end of the current
Navigator session. A negative date or date prior to current date effectively
“deletes” the cookie.
Cookies in JavaScript
• path=PATH
– Specifies the path portion of URLs for which the cookie is valid. If the
URL matches both the path and domain, then the cookie is sent to the
server in the request header. (If left unset, the value of path is the same as
the document that set the cookie.)
• domain=DOMAIN
– Specifies the domain portion of URLs for which the cookie is valid. The
default value for this attribute is the domain of the current document
setting the cookie.
• secure
– Specifies that the cookie should only be transmitted over a secure link (i.e.
To HTTP servers using the SSL protocol--known as HTTPS servers).
String Manipulation
• Manipulate Appearance
• Find Substrings, Characters, etc.
Manipulate Appearance
• big() -- Returns string object surrounded by
BIG container tag
• italics() -- Returns string object surrounded
by I container tag
• sub() -- Returns string object surrounded by
SUB tag
• fontSize(size) -- Returns string object
surrounded by FONTSIZE tag
Find Substrings, Characters, etc.
• lastIndexOf(findString, startingIndex) -Returns index of the last occurrence of
findString
• indexOf(findString, startingIndex) -Returns the index of the first occurrence of
findString
• charAt(index) -- Returns the character at the
location specified by index
Netscape vs. Explorer
•
•
•
•
•
•
•
Case Sensitivity
Form Values and String Conversion
Object Model Differences
Security
Communication with Java
Supported but Nonfunctional Properties
Miscellaneous Differences
Case Sensitivity
• One major difference between Navigator and Internet
Explorer is that the "object model" (as Microsoft calls
it) in Internet Explorer is not case-sensitive. Because
IE can also be scripted with the non-case-sensitive
VBScript language, all the HTML and browser objects
such as Window, Document and Form are not case
sensitive. Thus, in IE, you could write code that
invoked DOCUMENT.WRITE() instead of
document.write(). Don't expect code like this to work
in navigator, however!
Form Values and String
Conversion
•
The JavaScript interpreter in Internet Explorer 3.0 does not always convert objects to strings
when they are used in a "string context". This happens most notably when objects are
assigned to the value field of form elements. To make this work correctly, you have to
explicitly convert the object to a string, either by invoking its toString() method or by adding
the empty string to it. To display the date and time in a form, for example, you'd have to use
code like this:
•
•
today = new Date();
document.forms[0].dateandtime.value = today.toString()
•
or like this:
•
•
today = new Date();
document.forms[0].dateandtime.value = today + "";
•
If you encounter this conversion problem in other contexts, the workaround is the same.
Object Model Differences
•
•
•
•
•
•
There are a few other differences in support for HTML and browser objects in
Navigator and Internet Explorer 3.0:
The Window.open() method does not correctly load the argument specified in
the first argument in IE 3.0. This same bug exists for some platforms in
Navigator 2.0. The workaround is to first open a new window and then load the
desired document by setting the location property. Also, the Window.name
property is read-only in IE 3.0.
The Document.open() method in IE 3.0 ignores the MIME type argument, if any
is passed. It assumes that all documents are of type "text/html".
IE 3.0 records cookies only when the document is loaded via the http: protocol.
Documents loaded from the local disk (as they commonly are when being
developed or tested) cannot use cookies.
The blur() method of form elements behaves differently (and probably more
sensibly) in IE 3.0 that it does in Navigator. The difference is detailed in the
"Element.blur()" reference entry.
The History.go() method can only move backward or forward a single step at a
time in IE 3.0, and the History.length property always returns 0.
Security
• Navigator 2.0.2 and Navigator 3.0 implement
a very restrictive "hobble" in the interests of
security: a script running in one window
cannot read the properties of another window
unless the contents of that window were
loaded from the same server as the script.
Internet Explorer 3.0 implements security
measures, but this is not one of them. This
means that users of IE 3.0 may be vulnerable
to malicious scripts that steal information.
Communication with Java
• In Navigator 3.0, JavaScript can communicate with
Java in a very full-featured way through LiveConnect.
Internet Explorer 3.0 does not support LiveConnect,
and future versions of this browser probably won't
either. Instead, IE 3.0 allows JavaScript programs to
treat applets as ActiveX objects, and read and write
fields and invoke methods of those applets. Note
however that IE 3.0 does not suport the applets[]
array of the Document object--applets must be
referred to by name. Also, note that IE 3.0
mechanism for communication with Java is not nearly
so full-featured as LiveConnect.
Supported but Nonfunctional
Properties
•
•
In Internet Explorer 3.0, a number of the properties supported by
Navigator 2.0 and 3.0 are "supported" only in the sense that they can
be used without causing errors. These properties may not return
meaningful values when read and/or do not cause any changes when
set. Some properties, like Document.alinkColor are non-functional
simply because the browser as a whole does not support the feature
(special colors for activated links, in this case). Others are simply not
supported presumably because the engineers at Microsoft did not have
the time to implement them. These include the action, encoding,
method and target properties of the Form object and the length
property of the History object.
The isNaN() function also falls into the category of "supported but
nonfunctional." Because IE 3.0 does not support NaN values, the
isNaN() function always returns false.
Miscellaneous Differences
•
•
•
Other differences between Navigator and Internet Explorer 3.0 are small details about
the way values are computed and printed:
The for/in statement in IE 3.0 does not always enumerate the same object properties that
Navigator does. It does enumerate all user-defined properties, which is its primary
function. But predefined properties of built-in objects are not always listed.
The && and || operators behave somewhat differently in Navigator and Internet
Explorer, although, since JavaScript is an untyped langauge, the difference is usually
irrelevant. When the first operand of the && operator evaluates to true, then the operator
returns the value of the second operand in Navigator. In Internet Explorer, this second
operand is first converted to a Boolean value, and that value is returned. Thus the
expression true && 10 evaluates to 10 in Navigator but to true in Internet Explorer. This
may seem like a major difference, but because JavaScript is an untyped langauge, it
rarely matters. The && operator is almost always used in a Boolean context, such as the
expression of an if statement, so even when Navigator returns a value like 10, that value
will be immediately converted to the Boolean value true within that context. The same
evaluation difference occurs when the first operand of the || operator evaluates to false.
Miscellaneous Differences
• In Internet Explorer 3.0, Boolean values implicitly are converted to
strings differently than they are in Navigator. The value true is
converted to the string -1, and the value false is converted to the string
0. If you actually want them to be converted to the strings "true" and
"false", you must convert them explicitly by adding them to the empty
string.
• User-defined function values are also converted to strings differently in
IE 3.0. In Navigator, functions are converted to a string that includes
the complete body of the function. In fact, you can even use eval()
function to define the function in some other window. This does not
work in Internet Explorer, which omits the function body from its
string representation of functions.