JavaScript - BILLnSARA.com

advertisement
JavaScript
An Introduction
What is JavaScript?
• JavaScript adds “dynamic” behavior to
HTML pages, adding programming
capabilities.
• JavaScript is a predominantly "client side"
scripting language used for a large variety
of tasks, such as form validation, image
rollovers and fly-out menus.
• JavaScript was created by Netscape, and
is now the “official” client side language.
Where Does JavaScript Go?
• JavaScript code belongs inside HTML
<script> tags.
• Inside the <script> tags, the rules of
JavaScript apply. No HTML can go
directly inside the script tag.
• JavaScript is embedded directly into the
HTML page, usually in the <head> tag.
What Does JavaScript Look Like?
The format of a typical JavaScript looks like this:
<script type=“text/javascript”>
//Code goes here
</script>
Notice the comment tag (//Code goes here)
inserted in the text. The double slashes indicate
no code will be executed beyond that point on
the line.
Client Side vs. Server Side
• Server side scripting is used for interaction with
the user, and is frequently used to create
dynamic pages by interacting with a database.
• Client side scripting is designed to run on the
user's machine, and as such is cut off from the
server while it is running.
• Any work that can be done on the client is best
done there, as any processing there takes a
load off a busy server.
JavaScript Statements
• JavaScript expects us to speak to it in
lines of code it understands, called
“statements”
• Each JavaScript statement should go on
the same “line” of text, and most end with
a semi-colon:
var myAnswer = 2 + 2;
Browser Differences
• There are differences in how browsers are
designed, and therefore differences in how
JavaScript is processed.
• One such difference appears in how the
document object model (DOM) is handled.
• The DOM allows us to navigate an HTML
document, and make changes to the page,
without reloading the page.
No Errors Shown, By Design
• Because JavaScript errors are so common
and disruptive to a user’s experience,
most browsers elect NOT to display any
JavaScript errors, by default
• In order to troubleshoot scripting errors,
we use a browser like Firefox, which gives
feedback on errors by selecting:
Tools >> Error Console
Overly Sensitive
• JavaScript is case sensitive, some say
“overly” so.
• If you use a JavaScript function or variable
and get even one letter in the wrong case,
JavaScript will either show you an error, or
will give you unexpected results
Data Types
• Numerical data is entered in JavaScript without
quotations around it, while alphanumeric data
(hereafter called string data) needs to be
inserted with quotes.
• There are 3 basic types of data in JavaScript,
strings, numbers and booleans.
• While the JavaScript engine is processing, it will
give it's best guess as to the data type involved.
In general, any number that can be used in a
calculation is considered numerical. An address
number, like a zip code, would be a string.
Numerical Data
• While strings must be quoted, numbers
must not be, if they are to be calculated.
• JavaScript treats most numbers
automatically, meaning there is one
numerical data type
Strings Of Data
• In JavaScript, user data, like names or
HTML look like “strings” of data that is
NOT specifically meaningful to JavaScript.
• This data type is called a “string” because
it is alphanumeric data that is “strung”
together like beads on a chain
• Strings are required to be in quotes, either
single or double quotes, but not both
Variables
• Variables are programming constructs that
have contents inside them that ‘vary’
• Variables allow us to tailor our code to the
circumstances:
var myAnswer = 2 + 2;
• In the above code, a variable named
‘myAnswer’ is declared, and it is assigned
a value, the sum of 2 and 2.
Concatenation
• Concatenation is a programmer’s word for
‘connect’.
• When we use variables, we ‘concatenate’
data into meaningful statements:
myVar = ‘The Year is: ‘;
myVar += myDate.getFullYear();
Operators
• JavaScript uses “operators” which allow us to make
mathematical calculations, and also to concatenate
strings of data:
• var myVar = 2 + 2;
• In the above example the “plus” sign is the operator that
allows us to add 2 and 2. The same operator is used to
concatenate strings:
• var myName = “Bill ” + “Newman”;
• Note the “space” left after the first name. This is there so
that the two words have a space between them, once
they are concatenated.
Keywords
• Keywords are words that have special meaning
in JavaScript. These words must be used in
accordance to JavaScript rules and can't be
used as variable or function names.
• Some common keywords are break, do, else,
for, this, true, false, if, var, void, null, return,
while, function, in and switch.
• If we are tempted to use a word that logically is
very close to a keyword, the suggestion is to
attach the prefix "my" to it, ie: myFunction.
Read Right To Left
• Isn’t it odd that the statements read right to
left?
var myVar = 2 + 2;
• This is because the most important part of
the statement (the sum, if it’s math) is
easier to scan this way in a long program.
JavaScript Functions
• JavaScript has several built in “functions”
which allow us to perform actions
automatically by calling the name of the
function, and supplying some data. Here
is a very common function, called “alert()”.
alert(‘Here is a message that pops up!’);
• Note the function includes a “string” of
data, that is a message to a user
Anatomy Of A Function
• For a function to “function” certain rules
must be followed:
• Functions all require parenthesis:
alert(“message here”);
• Sometimes they require “data” inserted
inside the parenthesis. In this case, the
“string” of text saying, “message here”.
Booleans
• Boolean data gets its name from the
Mathematician George Boole
• Boolean data consists of logic types. For
us, that would be the values true and false
• Boolean data, like numerical data, does
NOT use quotation marks
• Booleans (true or false) are always lower
case
If(x == true){alert(“It’s true!!”);}
Equal? NOT!
• An important operator, often associated
with Booleans, is the NOT operator,
symbolized by the exclamation mark “!”
• The “not” operator is used with the equal
sign to create “not equal”, which is the
same as false:
If(x != true){alert(“That would be false!”);}
Late Binding
• JavaScript reads and processes
statements one at a time.
• JavaScript makes assumptions about the
code it sees, since it processes data on
the fly.
• If it sees numbers that are not quoted, it
tries to calculate them.
• If it sees numbers that are quoted, it tries
to connect, or concatenate them
Curly Braces
• Curly braces (the “{“ and the “}” signs) are
required to let JavaScript know where to
start and stop.
• These are required when you build your
own functions, and for if statements, for
example:
if(x == y){alert(“x equals y!”);}
Conditionals
• JavaScript allows us to do different things
according to different circumstances
• We do this as people, when we say:
If it rains, bring an umbrella. Otherwise,
bring shorts.
• A ‘conditional’ is a statement that allows us
to determine what happens “if” something
occurs
If Statement
• Here is a sample ‘If’ statement:
If(x == y)
{
alert(“I guess x equals y!”);
}
The “double equal” is the operator that
checks for equality. If the variables x and
y are equivalent, then the alert displays
Assignment vs. Comparison
• The “equals” sign carries special significance in
JavaScript
• To “compare” data, we need to use the “double” equal:
if(x == y){alert(“x equals y!”);}
• To “assign” data, we use a single equal sign:
var myVar = 2 + 2;
var myName = “Bill “ + “Newman”;
• Both of these examples “assign” data to the variable on
the left.
Custom Message Based On Date
The sample below accesses the date object
on the user’s machine, and displays an
“alert()” message, if it’s noon, or later:
var myDate = new Date();
If(myDate.getHour() > 12)
{
alert(‘It’s after Noon!’);
}
JavaScript Objects
• JavaScript uses “objects” to allow us to access
resources like the “date” on the system clock of
the user’s machine:
var myDate = new Date();
• We need to create an ‘instance’ (example) of a
date object in order to use it further. This allows
us to work with different date objects at once.
The Date Object
• Users come to our website from different
parts of the world
• Accessing the user’s system clock is
useful for tailoring a user’s experience to
their time of day
• What if you wanted to show a custom
image or message based on the time of
day of the user? JavaScript does this.
Document Object Model (DOM)
• Document Object Model: The elements that
make up an HTML document can be put to
various purposes by JavaScript.
• The way that an HTML document is navigated is
by a structure called the Document Object Model
(DOM).
• The DOM allows us to read down to a part of an
HTML document and either read or change
data.
• You can call out the object by it's exact name, or
by climbing the DOM "tree" elements
sequentially.
The Navigator Object
• JavaScript can determine information
about what browser is being used. This is
useful for tailoring HTML for a specific
browser:
var myBrowser = navigator.appName();
alert(“Your browser is: “ + myBrowser);
Event Handlers
• Events are occurrences on an HTML page, like
a “page load” or the actions by the user, like
mouse clicks and mouse hovers, etc.
• Events can be “captured” and used as a trigger
for actions taken by JavaScript.
• The mouse clicks and mouse hovers, etc. are
called "events", and the JavaScript "handles" or
reacts to the actions of the user, hence the
phrase "event handler".
Rollovers
• The most common kind of event handler is a “rollover",
where an image is "swapped out" (changed) when a
user hovers the mouse over an image.
• The simple "mouse over" example code below simply
(although inefficiently) handles a mouse over event:
• <a href="mypage.htm"
onMouseOver="document.myImage.src='images/on.gif'"
onMouseOut="document.myImage.src='images/off.gif'">
<img src="images/on.gif" name="myImage"><a/>
• The above example uses the “document” object model to
identify an object by name, in this case an image named
“myImage”
Download