Introduction to JavaScript
What
is JavaScript?
-
It is an object-based
scripting language developed by Netscape to add interactivity and power
to Web documents.
-
It is interpreted by the Web browser when the Web Page
is downloaded or when another event occurs.
-
JavaScript can be used to create dynamic effects (live clocks, rollover effects, form validations, etc.)
or fully functional
"Client side" programs (Programs that run on the end-user's computer).
Why
learn JavaScript?
-
With HTML, you are restricted to creating static, non
interactive Web pages. This, in today's Internet standards, is unacceptable.
-
With JavaScript, you can create interactive Web pages.
-
JavaScript differs from most other programming languages
in that it is relatively easy to master, even for people who have no programming
experience.
What's
the difference between Java & JavaScript?
-
Java, C++, C and JavaScript have some basic syntax in common (like
if statements,
for
loops etc.).
-
However, Java is completely different from JavaScript
-
It's a lot more powerful, more complex, and unfortunately,
a lot harder to master.
-
It allows you to create more complex Objects (Object-oriented
vs. Object-based).
-
You need to compile Java programs before you can run them.
In JavaScript, no compilation is needed. Open a text editor, type the code,
save it, and your browser can run it!
Can JavaScript programs run on Netscape & Internet Explorer browsers?
-
Unfortunately, not necessarily. JavaScript was created
by Netscape, and JScript was created by Microsoft (they are both referred
to as "JavaScript").
-
They are very similar but things can run differently in
different browsers.
-
A good rule to follow is to always test your codes using
both browsers before uploading it onto the Internet.
Defining JavaScripts
-
Every script begins with an opening
<SCRIPT>
tag to indicate to the browser that the text that follows is part of a
script.
-
The language attribute specifies the scripting language:
<SCRIPT
LANGUAGE="JavaScript">
-
Both JScript & JavaScript are referred to as "JavaScript".
-
Each script ends with a closing script tag:
-
Scripts can be defined either in the HTML document header
or within the body of the HTML document.
For Example:
<html>
<head>
<title>Sample JavaScript</title>
<script language="JavaScript">
document.writeln('<h1>Hellow World</h1>');
</script>
</head>
<body></body>
</html>
JavaScript Objects
-
JavaScript is "Object based" in much the same way that
VisualBasic is: JavaScript has predefined Objects and uses standard
browser objects.
| Objects |
Properties |
Methods |
| document |
bgcolor, title, lastModified |
write(), writeln() |
| window |
status, location, parent |
alert(),confirm(),prompt() |
| Math |
PI, E |
abs(), max(), sqrt() |
| text |
name, value |
blur(),focus(),select() |
More JavaScript Objects
JavaScript Effects
Status bar messages
-
Using JavaScript, you can display messages in the status
bar of your browser below.
-
This is accomplished by setting a string value to the
"window.status" property.
-
For example you can display a message when the page first
loads:
<script language="JavaScript">
window.status =
"Welcome to ISM 411 & JavaScript"
</script>
-
Status bar messages can also be initiated
only when the user moves the mouse over a link:
Yahoo
<a href="http://www.yahoo.com"
onMouseover="window.status='Click for
Yahoo!';
return true" onMouseout="window.status=''">
Yahoo</a>
<!--Single ' for passing
string to JavaScript-->
-
The mouse's "position" is captured using the onMouseover
and onMouseout event handlers of JavaScript.
-
Event handlers are added directly inside certain HTML
tags allowing code to react to an event.
On-the-fly text
-
Text inside a HTML document is static (the same every time you reload the document)
- JavaScript allows you to generate text on the fly. You
could, for example, have the document greet you "Good morning" in the morning,
and "Good night" at night.
-
The basic way to write out text in JavaScript is by using
the
document.write(), or the document.writeln()
methods, as follows:
<script
language="JavaScript">
document.write('<font color="green">');
document.write('<h3>Some text');
document.writeln('etc...</h3></font>');
</script>
-
The
document.write() method
writes what is in the parentheses directly to the screen.
-
The
document.writeln() method
adds a new line at the end of the statement (in HTML code not in displayed
document).
-
You can create script that writes out
the current date:
<script language="JavaScript">
var today=new Date();
document.write('<h2>'+ today +'</h2>');
</script>
-
The text reflects the date and time your page was downloaded is updated automatically whenever you
refresh your page.
JavaScript:
Dialog Boxes
-
JavaScript dialog boxes are "pop-up" boxes that can be
used to display a message, ask for confirmation, user input etc.
-
The three basic types of dialog boxes in JavaScriptare:
alert, confirm, and prompt:
Alert
<script language="JavaScript">
window.alert('Welcome to ISM411');
</script>
Confirm
<script language="JavaScript">
var answ=confirm('Go to CNN?');
if (answ)
window.location='http://cnn.com';
else
history.back();
</script>
Prompt
<script language="JavaScript">
var answ=window.prompt('Enter name');
window.alert('Hello' + answ);
</script>
Variables
-
A Variable is an Identifier that refers to a chunk of
computer memory.
- Variable names can only consist of letters, numbers, and the underscore ( _
) and must begin with a letter (x3 is a valid name but not 3x).
- Java is case sensitive: Upper and lower case characters are different (Total,
total and TOTAL are considered to be three different variables).
- Java keywords are words that have special meaning in the Java language. You
should not use them as variable names.
-
Variables need to be declared before they can be used.
-
All variables are declared using the
var
command.
- Variables may be given an initial value when they are declared (This is
called initializing the variable).
- General form:
var variable [ = initialization];
var number1, number2;
var string2 = "cow";
Operators
-
Arithmetic
-
Relational
-
Logical
-
Increment and Decrement
-
Assignment
-
Conditional
Arithmetic
| addition |
+ |
| subtraction |
- |
| multiplication |
* |
| division |
/ |
| modulus |
% |
- Examples of arithmetic expressions:
3 + 7 (evaluates to 10)
2.5 + 7.5 (evaluates to 10.0)
12.6 / 2 (evaluates to 6.3)
17 % 3 (evaluates to 2, the remainder after 17 is divided by 3)
"A" + "BC" (evaluates to "ABC")
Relational
| less than |
< |
| less than or equal to |
<= |
| greater than |
> |
| greater than or equal to |
>= |
| equal to |
== |
| not equal to |
!= |
-
A relational expression, such as
a == 10, evaluates
to 0 or 1 depending on the whether it is FALSE or TRUE.
-
Equivalency versus assignment...
Logical
-
The negation operator ! changes an expression's value
from zero to non-zero or vice-versa.
-
Boolean names may be defined using symbolic constants
&& and ||
-
Logical operators combine logical expressions. Evaluation
stops as soon as the truth-value is determined
Increment and Decrement
| increment |
++ |
| decrement |
-- |
-
Pre- and post-increment (decrement) operators perform
the operation before (after) use.
-
a++ is the same as a
= a + 1
Assignment
num += expr;
// is equivalent to
num = num + expr;
Precedence
| Operators
| Associativity
| Type
|
() |
left to right |
parentheses |
* / % |
left to right |
multiplicitive |
+ - |
left to right |
additive |
< <= > >= |
left to right |
relational |
== != |
left to right |
equality |
= += -= *= /= %= |
right to left |
assignment |
Example: + (Addition and String Concatenation!)
- The
+ operator is an addition operator when both of its
operands are numbers. It is a concatenation operator when one of its
operands is a string.
- Every expression including a string operand yields a string.
- JavaScript's interpreter evaluates expressions from left to right, and
only parentheses can change the order of evaluation.
8 + 8
// 16
"8" + 8
// "88"
8 + "8"
// "88"
"8" + "8"
// "88"
8 + 8 + "8"
// "168"
"8" + 8 + 8
// "888"
Why
is it not 816??
- What would the following code output (a=5 & b=10)?
document.write('a + b');
______
document.write(a + b);
______
document.write('a' + b);
______
document.write('a+b = ' + a+b); ______
document.write('a+b = ' + (a+b)); ______
External JavaScript Files
- External JavaScript files allow the use of JavaScript code in many pages at once.
- External JavaScript files are TEXT files ending with the
.js extension. They
contain multiple JavaScript Functions (next week we do functions) that can
be called from any page that references them.
-
To link to an external JavaScript file, you need to add a script tag that
links to the external file inside the head section of your html
document:
<SCRIPT LANGUAGE="JavaScript" SRC="../scripts/sample.js"></script>