Title: CS 482 Web Programming and Scripting
1CS 482 Web Programming and Scripting
2Topics
- JavaScript Basics
- Formatting with Tables
- Formatting with Layers
3What is JavaScript?
- JavaScript is a light-weight, interpreted
programming language or scripting language with
object-oriented capabilities. - An interpreted language is not compiled. The
browser has an interpreter that scans the
JavaScript code and interprets it. If it finds
syntax errors, it flags them and stops executing
the code. - The general-purpose core of the language has been
embedded in Netscape and Internet Explorer (IE),
and other Web browsers. - JavaScript is cross-platform, simple, easy to
comprehend, and powerful.
4Why Use JavaScript?
- The two main reasons that we use JavaScript in
Web pages are - Dynamics
- JavaScripts dynamic and visual effects include
intercepting and processing mouse clicks, opening
pop-up windows upon loading and unloading of Web
pages, and producing animation. - Client-side execution
- Client-side execution includes validating form
input and processing client requests that do not
require server processing. Other examples include
rollover effects, scrollers, and live clocks. - Server-side JavaScript we are not covering
5JavaScript Versus JScript
- JavaScript was developed by Netscape and
successful because of its simplicity and power. - Microsoft has a clone of JavaScript, called
JScript, that is designed to run inside the
Internet Explorer browser. - JScript is almost identical to JavaScript
however, in this course, we cover JavaScript.
With this knowledge, you will be able to easily
pick up JScript.
6ECMAScript Standard
- JavaScript 1.5 version is fully compliant with
the European Computer Manufacturing Association
(ECMA) language specification known as ECMA-262
Edition 3 or ECMAScript. - ECMA is the international standards association
for information and communications systems
(http//www.ecma-international.org). - What can be confusing is the fact that different
versions of Netscape and IE support different
versions of JavaScript. - For this class, we concentrate on the latest
browser versions Netscape 6/Mozilla Firefox 1.5
and higher, and IE 6 and higher. These both
support JavaScript version 1.5.
7JavaScript Myth 1 JavaScript is not Java
- JavaScript is not Java!
- Other than being similar in syntax, and both
providing executable contents in Web browsers,
the two languages are entirely unrelated. - The similarity in names was purely a marketing
ploy by Netscape. - JavaScript contains a much smaller and simpler
command set than does Java. - It is an easier language for most people to learn.
8JavaScript Myth 2 JavaScript is not simple
- JavaScript is touted as a scripting language
instead of a programming language. This implies
that scripting languages are simpler and easier
for non-programmers to pick up. JavaScript at
first glance appears to be a fairly simple
language on the order of BASIC. - JavaScript does have a number of features
designed to make it a more forgiving and easier
to use language for new programmers. - Non-programmers can use JavaScript for limited,
cookbook-style programming tasks. - Beneath the veneer of simplicity, however,
JavaScript is a full-featured programming
language. It is as complex as any and more
complex than some. Programmers who attempt to
use JavaScript for nontrivial tasks often find
the process frustrating if they do not have a
solid understanding of the language.
9JavaScript Resources
- Books
- Powell and Schneider (2004),. JavaScript The
Complete Reference, California
McGraw-Hill/Osborne, ISBN 0-07-225357-6. - Flanagan, David. JavaScript The Definitive
Guide, California OReilley, ISBN 0-596-0048-0.
10What Can JavaScript Do?
- Control Document Appearances and Content
- JavaScript contains a write() method that allows
you to write arbitrary XHTML into a document as
the document is being parsed by the browser. - You can also use the Document object (to be
covered in Week 4) to generate documents entirely
from scratch. - Properties of the Document object allow you to
specify colors for the document background, text,
and hypertext links within it. - Generates dynamic HTML documents which can allow
JavaScript to replace a traditional server-side
script. The latest version of the browsers
supports the capability of manipulating CSS (the
Cascading Style Sheets you learned about last
week) style attributes which opens an unlimited
world of scripting possibilities.
11Interact with HTML Forms
- Capability is provided by the Form object
- Form element objects it can contain which are
Button, Checkbox, Hidden, Password, Radio, Reset,
Select, Submit, Text, and Textarea objects.
These element objects allow you to read and write
the values of the input elements in the forms in
a document. - For example, an online catalog might use an HTML
form to allow the user to enter his order and use
JavaScript to read the input from that form in
order to compute the cost of the order, the sales
tax, and shipping charge. - JavaScript has an obvious advantage over
server-based scripts because the JavaScript is
executed on the client so the forms contents do
not have to be sent to the server for the
computation to be made. - Allows validating form data before it is
submitted . - If client-side JavaScript is able to perform all
necessary error checking of a users input , no
round trip to the server is required to determine
minor user input errors. In some cases,
JavaScript can eliminate the need for scripts on
the server altogether!
12Interact with the User
- An important feature of JavaScript is the ability
to define event handlers. - Event handlers are arbitrary pieces of code to be
executed when a particular event occurs. - You covered the same concept when you did user
interface development using Javas Swing classes
in CS 434. - For example, when a user presses a Submit button,
a button event is generated. - JavaScript can trigger any kind of action in
response to user events.
13Read and Write Client State Cookies
- A cookie in Web-speak is a small amount of state
data stored permanently or temporarily by the
client. - Cookies may be transmitted along with a Web page
by the server to the client, which stores them
locally. Later, when the client requests the
same or related Web page, it passes the relevant
cookies back to the server, which can use their
values to alter the content it sends back to the
client. - For example, when a Web page remembers your
password from a prior visit. The main reason for
cookies is to provide the state information that
is missing from the stateless HTTP protocol of
the Web.
14What JavaScript Cant Do
- The main things that JavaScript cannot do are
related to the fact that the script is on the
client-side which means that it does not have
features that would be required for standalone
languages (such as regular Java). - JavaScript does not have any graphics
capabilities, except for the ability to
dynamically generate HTML (including images,
tables, frames, forms, etc.) for the browser to
display. - For security reasons, client-side JavaScript does
not allow the reading or writing of files.
Obviously, you wouldnt want to allow an
untrusted program from any random Web site to run
on your computer! - JavaScript does not support networking of any
kind, except that it can cause the browser to
download arbitrary URLs and it can send the
contents of HTML forms across the network to
server-side scripts and email addresses.
15JavaScript Development Environment
- The JavaScript development environment is no
different from that of XHTML. - You will still need a HTML editor (Dreamweaver,
FrontPage) - Writing JavaScript does generate syntax errors.
- If you recall when you made an error in XHTML,
the Web page did not display correctly. - In JavaScript, an error results in a blockage of
the rendering of the Web page content. - This can leave you wondering what happened and
without a debugger, it can be time consuming to
find errors. - Do not need a full-fledge debugger because the
JavaScript interpreter does a good job in
reporting syntax errors.
16Debuggers
- Netscape/Mozilla has a built-in JavaScript
debugger (JavaScript Console) - IE does not
- In fact, IE does not recognize the javascript
protocol - Dont forget to test the script in IE!
17Can also use ltscript languagejavascriptgt
18When you press the OK button, the following text
appears in the browser caused by the
document.write() method
19Where Does JavaScript Go?
- You can embed JavaScript code in three places
- In the top section of the page between the ltheadgt
and lt/headgt tags - In the middle section of the page between the
ltbodygt and lt/bodygt tags - In a separate file.
- JavaScript code is placed on the between a pair
of container tags that look like - ltscript type text/javascriptgt
- lt!--
- script goes here
- //--gt
- lt/scriptgt
- The opening tag, ltscript typetext/javascriptgt,
tells the browser - It has encountered a script
- It is in text format and
- It is to be interpreted as JavaScript.
20JavaScript continued...
- lt! and //--gt
- Used to enclose the script code in an XHTML
document so older browsers that do not support
scripting do not try and display as part of the
Web page. - The actual script code starts on the third line.
- Use ltnoscriptgt...lt/noscriptgt for informing users
that the browser does not support JavaScript - If the script is to be placed in an external
file, the opening and closing tags are not
included just the script itself. - The file should have an extension of .js. The
(X)HTML page would then contain a link to the
JavaScript file like this - ltscript typetext/javascript src/javascript/sc
riptfile.jsgtlt/scriptgt
21Some Basics
- JavaScript is a case-sensitive language.
- This means that language keywords, variables,
method names, and any other identifiers must
always be typed with consistent capitalization of
letters. - JavaScript ignores spaces, tabs, and newlines
that appear between tokens in programs, except
those that are a part of a string or regular
expression literals. - You are free to format and indent your programs
for neat and consistent coding style. - Simple statements in JavaScript are generally
followed by semicolons () (as in C and Java) - The semicolon serves to separate the statements
from each other. However, you may omit the
semicolon if each of your statements is placed on
a separate line. This is frowned upon and is not
good programming practice. - You should end all your statements in this class
with a semicolon.
22Some Basics
- JavaScript supports two types of comments (like
C and Java) - // and / /
- In the first case, any text following the // and
the end of the line is treated as a comment. - In the latter, any text between the characters /
and / is also treated as a comment.
23JavaScript Variables
- A variable is a symbolic name that can store a
value. - myVar 5 assigns the value of 5 to the variable
myVar - Identifiers
- JavaScript identifiers must conform to certain
rules (like C and Java) an identifier must
begin with a letter (upper or lower-case), an
underscore (_), or dollar sign (). - It must not begin with a number.
- Subsequent characters can be digits.
- Examples of valid identifiers
- test, Test123, my_test, abc, and a_1234.
- It is recommended because JavaScript is an
object-oriented language to use camel hump
notation. Camel hump notation is where the first
word is in lowercase and the first character of
the remaining words are capitalized. - For example, myFirstVariableName.
24JavaScript Variables - Types
- JavaScript is a dynamically typed language which
means that you do not have to declare variable
data types explicitly. - Data types are converted automatically during
script execution. - The first use of the variable defines the data
type. - JavaScript recognizes data types of number,
logical (Boolean), and string. - JavaScript numbers can be integers (3,10) or
floating point numbers (3.10). - Unlike Java, JavaScript does not differentiate
between integer or long and float or double data
types.
25JavaScript Variables Logical String Types
- Logical data types are used to represent true and
false Boolean values. - They are typically used to check logical
expressions or control statements. - if (flag ! true) tests for the variable flag not
equal to Boolean 1. - Strings are sets of characters enclosed in a
single or double quotes. - John Doe is a string.
- Strings are one or more characters.
- XHTML elements can also be used inside of
strings. Doing so will help you to create more
dynamic pages. - document.write(This is ltstronggtreallylt/stronggt
fantastic!)
26Var Keyword
- JavaScript keyword var used to declare a variable
but not assign a value to it. - var myVar does not assign a type or value to a
variable but simply flags it as a variable that
will be assigned a value at a later time. - This is a technique that is used to group
variables at the top of a program together for
easy readability.
27Using JavaScript Variables
28(No Transcript)
29Scope
- The scope of a variable is defined as the code
block within which the variable is visible, or,
in other words, available for use. - JavaScript variables can be global or local.
- A global variable is available everywhere within
the ltscriptgt tag. - A variable that is declared without var is a
global variable. - A local variable is visible only inside a code
block such as a function (method).
30Constants
- Constants are read-only variables and are defined
with the const keyword. - const x 35, means that x is assigned the value
35 and it cannot be changed. - JavaScript ignores any reassignment of a constant
in a script and reassignment does not cause an
error. - All variable and scope rules apply to constants.
- Note, only Netscape (Firefox) recognizes the
const keyword. IE produces errors and does not
render the Web page.
31Literals
- Literals are fixed values in JavaScript (not
variables) - Known as hard-coded values.
- Examples are number (3.5) , Boolean (false) and
string literals (Hello). - Nesting string literals requires extra care to
avoid creating syntax errors when we run a
script. - Must toggle the types of quotations we use from
double to single quotes or vice versa. - str Our facilitator said, We must study for
the exam last week
32Data-Type Conversion
- JavaScript converts data types automatically as
needed during script execution. - This is because JavaScript is dynamically typed.
- Can write answer true and then change it to
answer 35 - converts the variable answer from Boolean to
number. - Practically, however, we should not do this so as
to avoid confusion and increase program
maintainability.
33Escaping Characters
- JavaScript uses the backslash (\) as an escaping
character. - An escaping character is an instruction to the
JavaScript interpreter to ignore what follows the
character, and not to execute it according to the
JavaScript syntax rules. - Can insert a quotation mark inside a string by
preceding the quotation mark by a backslash. - str Our facilitator said \We must study for
the exam\ last week
34The Alert, Confirm, and Prompt Windows
- Browsers often use three small windows to send
information to or request information from the
user. - The JavaScript window object contains three
methods (alert, confirm, prompt) that create
these tiny pop-up windows.
35The Alert Window
36Alert Output
37The Confirm Window
38Confirm Output
39(No Transcript)
40The Prompt Window
41Prompt Output
42Parsing Numbers
- For integers (whole numbers), we use the
parseInt() method. - This method requires a string parameter and it
returns the integer equivalent. - For example, the following statement asks the
user to enter the total questions, parsing this
to an integer, and places the result in the
variable total. - var total parseInt (prompt (Total questions
, )) - For floating-point numbers, we use the
parseFloat() method. - For example, if a facilitator assigns partial
credit for answers, we could use this method to
obtain the answer - var correct parseFloat (prompt(Correct
answers , ))
43JavaScript Statements
- A statement is a line of JavaScript code that
uses the assignment operator, the equal sign ().
- The assignment operator has two operands, one on
each side. The value of the right operand is
assigned to the left one. - JavaScript does not allow a statement to be
broken into two lines. - Each statement must be one line long, not matter
how long it is. - Breaking a statement by entering a carriage
return ltEntergt results in a syntax error. - A statement may end with a semicolon().
- The purpose of whitespace in statements has no
effect on the statements results. - We use it for the purpose of code readability.
The only time that whitespace matters is when we
use it in literal strings.
44JavaScript Expressions and Operators
- An expression is any valid set of variables,
literals, operators, and other expressions that
evaluates to a single value. - That value could be a number, Boolean, or a
string.
45The Rules of Precedence
- Rule 1 Operators are evaluated in the order of
their precedence higher-order operators are
evaluated before lower order operators. - Rule 2 Operators of the same precedence are
evaluated according to their associatively.
Left-associative operators (addition,
subtraction, multiplication, division, and
modulus) evaluate from left to right.
Right-associative operators (assignment) evaluate
operators from right to left. - Rule 3 Parentheses are used to override
precedence. - Rule 4 Parenthesized expressions are evaluated
from the innermost to the outermost set of
parenthesis. - Bottom line USE PARENTHESIS FOR CLARITY AND
MAINTAINABILITY!!
46Assignment Operators
- The equal sign () is the main assignment
operator. - Other assignment operators are shorthand for
certain operators. - x x y or use x y (the shorthand version).
Here, we add y x and store the result back in
x. - Other shorthand operators include x - y (x x
y), x y (x x y), and x / y (x x/y).
47Comparison Operators
48Arithmetic Operators
49Logical Operators
50(No Transcript)
51(No Transcript)
52JavaScript Control Structures
- A control structure is defined as a group (block)
of statements that control code execution
according to certain criteria. - JavaScript provides conditional (if and switch)
and loop (for, while, and do while) statements.
53The if Statement
The if statement uses an expression to select
between alternative code segments. First
form if (condition)
Second form if (condition)
else
Note In JavaScript, an expression is false if it
produces a value of zero and an expression is
true if it produces a value that is not zero. It
does not evaluate like other languages to a
Boolean true or false. This is a source of
confusion for beginning JavaScript developers.
54The switch Statement
- The switch has this form
- switch (expression)
-
- case label1
- statements.
- break
- case labelN
- statements
- break
- default
- statements
-
55(No Transcript)
56JavaScript Loops
- Loops
- A loop statement executes repeatedly until a
specific condition is met. - Looping can be achieved via a for, while, or do
while statement. - The break and continue statements can be used
with loops to control the flow of program
execution. - To review, a break statement exits the loop all
together while the continue skips the current
iteration.
57for Loop
for Loop The syntax of a for loop is as
follows for (initial value of a counter ending
value increment) for block (body) for
example for (i 0 i lt 10 i) alert
(Value of i is i ltbr /gt)
58while Loop
- The while statement has this syntax
- while (condition)
-
- statements
-
- The condition evaluates to a Boolean true or
false. - The while loop executes as long as it evaluates
to true. - The execution stops the first time it evaluates
to false. -
- i 0
- sum 0
- while (i lt 3)
-
- sum sum 3i
- document.write (Sum is sum)
- i
- while (i lt 3)
- The above while loop has three passes until the
condition evaluates to true.
59do while Loop
- The do while statement has this syntax
- do
- statements.
- while (condition)
- The condition evaluates to a Boolean true or
false. - The do while loop executes as long as it
evaluates to true. - The execution stops the first time it evaluates
to false. - i 0
- sum 0
- do
- sum sum 3i
- document.write (Sum is sum)
- i
- while (i lt 3)
- This do while statement executes in the same way
as the while loop
60Loop Example
- Remember the Fibonacci sequence? This refers to
the algorithm where any element in the sequence
is the sum of two immediate previous elements - Therefore, we must provide the first two elements
of the sequence in order to jump-start the
algorithm. - These elements are defined as 0 and 1. The
following screen capture shows the results.
Take, for example, the last element, 89. It is
equal to 34 55. - We can extend the for loop counter, i, to any
number we want to in order to increase the number
of elements provided.
61(No Transcript)
62Formatting with Tables
63(No Transcript)
64(No Transcript)
65(No Transcript)
66(No Transcript)
67Formatting via Layers
68Layer Positioning
- Layers exist in 3D space
- Can be stacked on top of one another
- Can be on top of pages content
- Appearance depends on order in which layers are
stacked
69Layer Positioning
70Properties of Layers
71ltdivgt Tags for Layers
- XHTML provides the ltdivgt tag to create layers
- ltlayergt and ltilayergt no longer supported
72(No Transcript)
73(No Transcript)
74(No Transcript)
75(No Transcript)