Cpan240 - Humber College

Download Report

Transcript Cpan240 - Humber College

Cpan240
JavaScript
Guest Lecture 1
Objectives
•
•
•
•
•
•
•
•
•
•
JavaScript is not Java
JavaScript is an object-based scripting language
Placing the script on the Page
Why placing in external file?
JavaScript terminology and syntax
Primitive data types
Object hierarchy
Objects, properties, events, event handlers
Programming rules
Script Samples
JavaScript is not Java
• JavaScript - language developed by
Netscape.
• Primary purpose is for "client-end"
processing of HTML documents
– Extension of HTML
– An interpreter not a compiler
• In an interpreter, the instructions are
parsed (divided into small components
that can be analyzed and translated).
JavaScript can either be client-side
or server-side
• This refers to the place where the script is
processed.
• We will be dealing with client-side scripts.
• Most JavaScripts are client-side.
What Can JavaScript Do?
• Accept Input
– Text fields, check boxes, buttons, etc.
• Process Data
– Make decisions, manipulate variables
• Produce Output
– Messages, status lines, windows…
• Why?
– HTML doesn’t do much
What Can JavaScript Do?
• Modify Pages on the Fly
– Change text, replace images, special effects
• Offer Selections to the User
– Drop down menus, check boxes, buttons
• Manipulate Windows
– Open windows, write to them, close them
• BUT: no reading or writing to user’s disk
JavaScript is an object-based
scripting language
• Object-based means that JavaScript sees
the existing data structures as objects.
• A JavaScript object is a thing with its
properties and methods.
• The code will run on a wide variety of
computer platforms.
Why Use JavaScript?
• JavaScript enhances Web pages with dynamic
and interactive features.
• JavaScript enables:
–
–
–
–
–
–
–
–
shopping carts
form validation
calculations
special graphic and text effects
image swapping
image mapping
clocks
and more.
Dynamism takes three forms:
1. Events: Allows you to change
positioning or content based on events.
2. Dynamic positioning: Can tell the
browser where to place content without
using tables.
3. Dynamic content: Allows dynamic
updating of data at specified time intervals.
Where Does the Script Go?
• Direct Insertion
– Inside <head> tags (deferred script)
– Within <body> (immediate script)
• Embedded inline
– Inside other HTML tags (as attribute values)
• External references
– In external .js files (as deferred functions)
Placing the Script on the Page
• On the page, it is located between a set of
container tags that look like:
<script type="text/JavaScript">
<!–
... The script is placed here ...
//-->
</script>
The opening tag
<script type="text/JavaScript">, tells the
browser:
– it has encountered a script
– it is in text format
– it is to be interpreted as JavaScript.
Comment Tag
• The next line, <!--, is the opening
comment tag.
• The actual script starts on the third line.
• After the script ends, the comment tag is
closed, //--> and the </script> tag tells the
browser that the code is finished.
• They are used to hide JavaScript from
older browsers.
Placing the Script in an External Page
• When the script is located in an external
file ".js", the opening and closing tags are
not included.
• Only the script itself is included in the file.
Placing the Script in an External Page
• The HTML page would then contain a link
to the JavaScript file at the given URL:
<script type="text/JavaScript"
src="/JavaScript/scriptfile.js"></script>
If the script is small and otherwise
• If the script is small and used only once,
it's usually best to put it in the actual
HTML document.
• Otherwise, it's preferable to place the
script in an external file.
Why placing in external file?
• By placing the script in an external file, it
can be used on other pages.
• The browser caches the script and uses it
on the other pages, making them to load
faster.
• One file to make changes.
JavaScript Terminology
• Objects
– Things on a page
• Attributes
– Properties of objects
• Methods
– Actions taken by objects
• Statements
– Lines of assembled components
• Functions
– Reusable groups of statements
JavaScript Terminology
• Objects
Img, form, checkbox, button, textarea
• Attributes
Height, width, src, href, bgcolor, name
• Methods
onClick, focus, alert, getDate, scroll
• Statements
Document.myimage.src=“somepic.jpg”
• Functions
function doSomething()
{
…… statements …..
}
Object Hierarchy
• Fully-qualified location of an Object.
• Allows multiple instances of similar objects.
• Avoids duplication of object names.
Window
Document
Form
Object
Property or method
Value or action
Document.form1.button3.value=“Click me”
JavaScript Syntax
• Dot Syntax is used to combine terms.
document.write("Hello World")
• Certain characters and terms are
reserved.
• JavaScript is simple text (ASCII).
Script Hello_World.htm
<html>
<head>
<script type = "text/javascript">
<!-document.write("<h1 style=\"color: red\">");
document.write(" Hello world");
document.write("</h1>");
// -->
</script>
</head>
<body> <p>And here is more text</p> </body>
</html>
<html>
<head></head>
<body>
<h1 style="color: red">Hello world</h1>
<p>And here is more text</p> </body>
</html>
Script Calculation.htm
<html>
<head>
<script type = "text/javascript">
document.write("Here are a few of my favorite numbers:");
document.write("<ul>");
for (i=0; i<10; i++) {
n = Math.random();
j = i+1;
document.write("<li>My number " + j + " favorite is “
+ n + "</li>");
}
document.write("</ul>");
</script>
</head>
<body></body>
</html>
<ul> - unordered list
<li> - list items
Direct access to the browser window
Window.htm
<html>
<head>
<script type = "text/javascript">
window.alert("Pay attention!");
</script>
</head>
<body>
<p>And here is more text</p> </body>
</html>
Properties
• Properties are object attributes.
• Background color is expressed by:
document.bgcolor .
– document is the object.
– bgcolor is the property.
Methods
• Methods are actions applied to particular
objects.
• Methods are what objects can do.
document.write(”Hello World")
– document is the object.
– write is the method.
Events
• Events associate an object with actions.
– the OnMouseover event handler action can
change an image or do something else.
– the onSubmit event handler sends a form.
• Users trigger events, and event handlers
execute actions in response on the trigger.
Event Handlers
• Special methods associated with certain
objects.
• Called automatically when events occur.
• You specify what happens in the bodies of
event handlers.
onClick, onMouseDown, onMouseUp
onFocus, onBlur, onKeyPress
onLoad, onUnload, onSubmit
JavaScript’s event handler: onClick.htm
<html>
<head></head>
<body>
<form>
<input type="button"
value="click here"
onClick="alert('You clicked')" />
</form>
</body>
</html>
Values
• Values are bits of information.
• Values types and some examples include:
– Number: 1, 2, 3, etc.
– String: characters enclosed in quotes.
– Boolean: true or false.
– Object: image, form
– Function: validate, doWhatever
JavaScript is a "loosely typed"
language
• JavaScript is a "loosely typed" language,
meaning you don't need to specify the type
of data in a variable declaration.
• The type of data can be changed later in
the script without causing an error
message.
Example: Loosing_types.htm
<script type = "text/javascript">
a = "a string";
b = "1.25";
c = 1;
var d;
e = function (x) {return x;};
f = [0, "1", [2]];
document.write('a: ', a, ' (' + typeof(a) + ')<br>');
document.write('b: ', b, ' (' + typeof(b) + ')<br>');
document.write('c: ', c, ' (' + typeof(c) + ')<br>');
document.write('d: ', d, ' (' + typeof(d) + ')<br>');
document.write('e: ', e, ' (' + typeof(e) + ')<br>');
document.write('f: ', f, ' (' + typeof(f) + ')<br>');
</script>
What’s the value and type of
a = 1.25;
b = "1";
var c;
d = [0, 1, "two"];
function e(x) { return x;}
function f(x) { return x * 2 }
g = true;
document.write(d[0] , "<br>");
document.write( b + d[2] , "<br>");
document.write( a + b , "<br>");
document.write( a + c , "<br>");
document.write( e(c) , "<br>");
document.write( f(c) , "<br>");
document.write( a + c , "<br>");
document.write( a +f , "<br>");
document.write( a * c , "<br>");
document.write( a + d , "<br>");
document.write( a * d , "<br>");
document.write( g * d , "<br>");
document.write( g || c , "<br>");
document.write( g && c , "<br>");
Losing_types_1.htm
Summary of loose typing
• (All objects have a data type)
• The data type of a variable need not be declared
– determined at run time
• System will try to cast operands to make an operation
work
– anything can be cast to a string
– some strings can be cast to a number
– anything can be cast to a boolean
– nothing but a function can be cast to a function
• The operator will often imply a context, dictating the data
types of its argument:
a * b => numeric context
e(x) => function context (for e)
a + b => ambiguous (string or numeric)
Programming JavaScript
• Variables
– Named elements that can change value
• Primitive Data types
– Integer, floating-point, boolean, string
• Operators
– Assignment, comparison, boolean, string
• Control statements
– Conditions, loops
• Keywords
– Reserved words with special meaning
Programming JavaScript
• Variables
– Howdy, numberRight, score, Ralph
• Data types
– 12, 987.654, true/false, “Texas Tech”
• Operators
– >=, ==, +=, ||, <, >, etc.
• Control statements
– if, if….else, for, etc.
• Keywords
– var, true, false, int, const, new, return
Reserved Words
• There are 59 "reserved" words.
• These are words that are used to give
instructions to the JavaScript interpreter.
• They cannot be used for anything else.
abstract
boolean
break
byte
case
catch
char
class
const
continue
debugger
default
delete
do
double
else
enum
export
extends
false
final
finally
float
for
function
goto
if
implements
import
in
instanceof
int
interface
long
native
new
null
package
private
protected
public
return
short
static
super
switch
synchronized
this
throw
throws
transient
true
try
typeof
var
void
volatile
while
with
More about string data type
String Examples
"cheeseburger"
"123 Main Street, Anytown, FL 32714"
"His e-mail address is:
[email protected]"
Double or single quotes?
• Either single or double quotes can be used but
you must be consistent.
• If you start the string with a double quote, it must
end with a double quote.
• While there is no actual limit on the number of
characters but many older browsers have a limit
of 255 characters.
Escape Sequence
• In order to use a double quote within another
double quote (or a single within a single)
precede it with a backslash, "\".
• This is called an "escape sequence".
• It would then look like this:
document.write("<a
href=\"http://www.domain.com\">Check this out!</a>");
Several special characters can be
used in the escape sequence
Sequence
Name
Sequence Name
\b
Backspace
\f
Form feed
\n
New line
\r
\t
Tab
\'
Carriage
return
Single quote
\”
Double
quote
\\
Backslash
\xNN
Latin-1
\uNNNN
character set
Unicode
character set
You could also combine single and
double quotes
• It doesn't matter which set of quotes is used on
the outside or the inside. You just need to be
consistent.
document.write("<a
href='http://www.domain.com'>Check this
out!</a>");
document.write('<a
href="http://www.domain.com">Check this
out!</a>');
HTML elements
• HTML elements can also be used inside of
strings.
• Doing so will help you to create more dynamic
pages.
document.write("This is <strong>really</strong>
fantastic!");
Numbers
• JavaScripts recognizes two types of numbers:
integers and floating point numbers.
• Integers are whole numbers (e.g., 1, 20, 546)
and floating point numbers are numbers that
have a decimal point (e.g., 23.8, 23.890).
Numbers
• Unless otherwise specified, JavaScript treats all
numbers as floating point numbers.
• But if a calculation is performed using integers,
the answer will be an integer unless the
calculation itself changes it (e.g., the number is
divided unevenly).
boolean
• A boolean data type is used for true or
false statements.
• It's mostly used in if() statements:
var myCar=Chevy;
if (myCar==Chevy)
{ ... task to be performed if statement is true }
else
{... task to be performed if statement is false }
null built-in variable
• A null variable has no value.
• The variable does not return a space or a
zero.
• It just means nothing.
• A null variable is useful for testing input in
scripts.
• Since null is a keyword, it doesn't need to
be enclosed in quotation marks:
var nothingNow=null;
Programming Rules
•
•
•
•
Case matters
Quotes matter
Matching braces matter
Use indenting and semicolons
<script language=“javascript”>
Function msgBox(boxText)
{
Alert(boxText);
}
</script>
Variables
are conceptually the same as in
any other programming language
Variables
• Variables are created by declaration using
the var command with or without an initial
value assigned.
var month;
var month = April;
• Undefined
– the value of an uninitialized variable
– one instance, undefined
Declaration and Initialization
• A variable can be declared and initialized
using one of two methods.
var myName;
myName="Lee";
Or
var myName="Lee";
Declaration and Initialization
• Variable identifiers are similar to those in
other languages
– Cannot use a keyword
– Must begin with a letter, $, or _
• Followed by any sequence of letters, $, _ or digits
– Case sensitive
WhiteSpaces
• Since JavaScript, for the most part,
ignores whitespace, you can write either
way:
var TheFirst="This string is stored in a
variable.";
or
var TheFirst = "This string is stored in a
variable.";
Alert_Script.htm
Alert_Script.htm
<script type="text/javascript">
<!-var ans=prompt("Are you sure you want to do
that?","")
if (ans) {
alert("You said "+ans)
}
else {
alert("You refused to answer")
}
Alert_Script.htm
• The ans variable is initialized using the
prompt() method and two parameters ("Are
you sure you want to do that?" and "").
• The second parameter, "", is the default
answer, which is null.
Alert_Script.htm
• If you entered something in the prompt box (even
a space), an alert box will be displayed with "You
said" followed by your answer.
• If you pressed "OK" without answering the
question or if you pressed "Cancel," then it will
skip to the next part of the statement that will
open a prompt box with the words "You refused
to answer."
Alert_Script.htm
• If the variable ans does not contain any
data, then open an alert box and print 'You
refused to answer.'
Review Questions
Multiple Choice Questions
1. JavaScript is:
a. an interpreted language
b. a compiled language
2. JavaScript is:
a. subjective
b. object based
c. objective
3. To comment out a line:
a. Precede it with an asterisk, i.e. "*"
b. Precede it with an asterisk and a forward slash, i.e.
"*/"
c. Precede it with two forward slashes, i.e. "//"
True / False Questions
1. JavaScript can only run on Windows.
2. Semicolons are optional at the end of a
statement.
3. JavaScripts should not be formatted.
4. It is best to place the JavaScript on each
separate page.
Essay Questions
1. What is the purpose of the <script
type="text/JavaScript"> tag? How it works.
2. What is the purpose of the <script
type="text/JavaScript"
src="/JavaScript/scriptfile.js"> tag? How it works.
3. What extension should be used for an external
JavaScript file?
4. What are "reserved words" used for?
Summary: What was done?
•
•
•
•
•
•
•
•
•
•
JavaScript is not Java
JavaScript is an object-based scripting language
Placing the script on the Page
Why placing in external file?
JavaScript terminology and syntax
Primitive data types
Object hierarchy
Objects, properties, events, event handlers
Programming rules
Simple script examples