Saltar al contenido principal
JAVA SCRIPT
1
JavaScript
JavaScript is a dynamic computer programming
language. It is lightweight and most commonly used as a
part of web pages, whose implementations allow client-
side script to interact with the user and make dynamic
pages. It is an interpreted programming language with
object-oriented capabilities.
2
JavaScript has been around for several years now, in many
different flavors. The main benefit of Javascript is to add
additional interaction between the web site and its visitors
at the cost of a little extra work by the web developer.
Javascript allows industrious web masters to get more out
of their website than HTML and CSS can provide.
3
By definition, Javascript is a client-side scripting language.
This means the web surfer's browser will be running the
script. This is opposite to client-side is server-side, which
occurs in a language like PHP. These PHP scripts are run by
the web hosting server.
There are many uses (and abuses!) for the powerful
Javascript language. Here are a few things that you may or
may not have seen in your web surfing days.
4
Example of java scripts:
Clocks
Mouse Trailers (an animation that follows your mouse
when you surf a site)
Drop Down Menus
Alert Messages
Popup Windows
Html form Data Validation
5
Advantages of JavaScript
Less server interaction − You can validate user input before sending
the page off to the server. This saves server traffic, which means less
load on your server.
Immediate feedback to the visitors − They don't have to wait for a
page reload to see if they have forgotten to enter something.
Increased interactivity − You can create interfaces that react when
the user hovers over them with a mouse or activates them via the
keyboard.
Richer interfaces − You can use JavaScript to include such items as
drag-and-drop components and sliders to give a Rich Interface to your
site visitors.
Limitations of JavaScript
We cannot treat JavaScript as a full-fledged
programming language. It lacks the following important
features −
• Client-side JavaScript does not allow the reading or
writing of files. This has been kept for security reason.
• JavaScript cannot be used for networking applications
because there is no such support available.
• JavaScript doesn't have any multi-threading or
multiprocessor capabilities.
Syntax of Java Script
JavaScript can be implemented using JavaScript statements that are placed
within the <script>... </script> HTML tags in a web page.
The <script> tag alerts the browser program to start interpreting all the text
between these tags as a script. A simple syntax of your JavaScript will appear as
follows.
<script ...>
JavaScript code
</script>
The script tag takes two important attributes −
Language − This attribute specifies what scripting language you are using.
Typically, its value will be javascript. Although recent versions of HTML (and
XHTML, its successor) have phased out the use of this attribute.
Type − This attribute is what is now recommended to indicate the scripting
language in use and its value should be set to "text/javascript".
So your JavaScript segment will look like −
<script language = "javascript" type = "text/javascript">
JavaScript code
</script>
Whitespace and Line Breaks
JavaScript ignores spaces, tabs, and newlines that appear in JavaScript
programs.
Semicolons are Optional
Simple statements in JavaScript are generally followed by a semicolon character,
just as they are in C, C++, and Java. JavaScript, however, allows you to omit this
semicolon if each of your statements are placed on a separate line. For example,
the following code could be written without semicolons.
<script language = "javascript" type = "text/javascript">
<!--
var1 = 10
var2 = 20
//-->
</script>
But when formatted in a single line as follows, you must use semicolons −
<script language = "javascript" type = "text/javascript">
<!--
var1 = 10; var2 = 20;
//-->
</script>
Case Sensitivity
JavaScript is a case-sensitive language. This means that the language keywords,
variables, function names, and any other identifiers must always be typed with a
consistent capitalization of letters.
So the identifiers Time and TIME will convey different meanings in JavaScript.
Comments in JavaScript
JavaScript supports both C-style and C++-style comments, Thus −
• Any text between a // and the end of a line is treated as a comment and is ignored
by JavaScript.
• Any text between the characters /* and */ is treated as a comment. This may span
multiple lines.
• JavaScript also recognizes the HTML comment opening sequence <!--. JavaScript
treats this as a single-line comment, just as it does the // comment.
• The HTML comment closing sequence --> is not recognized by JavaScript so it
should be written as //-->.
Example
The following example shows how to use comments in JavaScript.
<script language = "javascript" type = "text/javascript">
<!--
// This is a comment. It is similar to comments in C++
/*
* This is a multi-line comment in JavaScript
* It is very similar to comments in C Programming
*/
//-->
</script>
How To Write Javascript
If you have ever used CSS before, then the whole
part about how to include Javascript will be a lot
simpler to grasp. Here are three important steps you
should always take when creating or using someone
else's Javascript code.
12
Use the script tag to tell the browser you are using
Javascript.
Write or download some Javascript
Test the script!
There are so many different things that can go
wrong with a script, be it human error, browser
compatability issues, or operating system
differences. So whenever using Javascript, be sure
that you test your script out on a wide variety of
systems and most importantly, different web
browsers.
13
Your First Javascript Script
To follow the classic examples of many programming
let's use Javascript to print out "Hello World" to the
browser. I know this isn't very interesting, but it will
be a good way to explain all the overhead required
to do something in Javascript
14
HTML & JavaScript Code:
<html>
<body>
<script type="text/javascript">
document.write("Hello World!")
</script>
</body>
</html>
15
Our first step was to tell the browser we were using a
script with <script> tag. Next we set the type of script
equal to "text/javascript", which you may notice that
doing this is similar to the way you specify CSS, which
is "text/css".
Next we added an optional HTML comment that
surrounds our Javascript code. If a browser does not
support Javascript, then it will not display our code in
plain text to the user! The comment was ended with a
"//-->" because "//" signifies a comment in Javascript,
so we add that to prevent a browser from reading the
end of the HTML comment in as a piece of Javascript
code.
16
Javascript document.write
The final step of our script was to use a function called
document.write which writes a string into our HTML
document. document.write can be used to write text,
HTML, or a little of both. We passed the famous string of
text to the function to spell out "Hello World!" which it
printed to the screen.
17
Syntax
Looking at our Javascript code above, notice that there is
no semicolon at the end of the statement
"document.write(Hello World!)". Why? Because Javascript
does not require that you use semicolons to signify the end
of each statement.
If you are an experienced programmer and prefer to use
semicolons, feel free to do so. Javascript will not
malfunction from ending semicolons. The only time it is
necessary to use a semicolon is when you choose to smash
two statements onto one line(i.e. two document.write
statements on one line).
18
Javascript - Is it Enabled?
This lesson will first teach you how to enable
Javascript in Internet Explorer then show you how
you can write a very simple script to separate those
who don't have Javascript enabled from those that
do on your websites.
19
Enable Javascript - Internet Explorer
In Internet Explorer 6/7 (download Internet Explorer) you
can check to see if Javascript is enabled by navigating to
the custom security settings that are somewhat buried
(don't worry we'll help you find it).
Click on the Tools menu
Choose the Internet Options... from the menu
Click the Security tab on the Internet Options pop up
Click the Custom Level... button to access your security
settings
Scroll almost all the way down to the Scripting section
Select the Enable button for Active scripting
Click OK to finish the process
Click Yes when asked to confirm
20
Javascript Detection
These days it's basically impossible to navigate the
web without a Javascript enabled browser, so
checking whether or not a user has Javascript
enabled is not all that important. Chances are the
only way it be disabled is if the company's IT staff
has decided to disable Javascript for some reason.
However, if you still want to be sure your users are
Javascript enabled, this script will get it done
21
The only sure fire way to separate users that
don't have Javascript from those that do is to
use a simple redirect script that will only work
for those with Javascript enabled. If a person's
browser does not have Javascript enabled the
script will not run and they will remain on the
same page.
22
Javascript Code:
<script type="text/javascript">
window.location =“tt.html"
</script>
23
Where to Place Javascript
There are three general areas that
Javascript can be placed for use in a web
page.
24
Inside the head tag
Within the body tag
In an external file
The location choice of head or body is very simple. If you
want to have a script run on some event, such as when a
user clicks somewhere, then you will place that script in
the head. If you want the script to run when the page
loads, like our "Hello World!" example , then you will want
to place the script within the body tag.
25
An Example Head Script
Since we have already seen the kind of script that
goes in the body, how about we write a script that
takes place when some event occurs, say a click on a
button.
26
HTML & JavaScript Code:
<html>
<head>
<script type="text/javascript">
function popup()
{
document.write("Hello World!")
}
</script> </head>
<body>
<input type="button" onclick="popup()" value="popup">
</body>
</html>
27
28
29
We created a function called popup and placed it in
the head of the HTML document. Now every time
someone clicks on the button (this is an event)
"Hello World!“ will be display. We will go into more
depth on functions and events in a later .
30
External Javascript Files
Having already dicussed placing Javascript in
the head and body of your HTML document,
let us now explore the third possible
location, an external file.
31
Importing an External Javascript File
Importing an external file is relatively painless. First the
file you are importing must be valid Javascript, and only
Javascript. Second, the file must have the extension ".js".
Lastly, you must know the location of the file.
Let us assume we have a file "myjs.js" that contains a one
line Hello World alert function. Also, let us assume that the
file is the same directory as our HTML file we are going to
code up. To import the file you would do the following in
your HTML document.
32
HTML & JavaScript Code:
<html>
<head>
<script src="myjs.js">
</script>
</head>
<body> <input type="button" onclick="popup()"
value="Click Me!">
</body>
</html>
33
function popup()
{
document.write("Hello World!")
}
myjs.js
34
35
36
37
Great Javascript Repositories
There is a ton of great stuff you can do with
Javascript, if you know how to code like Paul Allen
and Bill Gates, but for the rest of us it is nice to get
incredible Javascript tools without having to write
them ourselves. Below are some of the better
Javascript resources on the web these days.
JavaFile.com
Java-Scripts.com
38
External File Tips & Recap
Use external Javascript files when you want to use the same
script on many pages, but don't want to have to rewrite the
code on every page!
Use external Javascript files for including both types of
scripts! The type that you place in the head (functions) and
the type you place in the body (scripts you want to run
when the page loads).
Be sure that your Javascript files (.js) do not include the
<script> tag. They should only have the HTML comment and
Javascript code.
39
Javascript Operators
Operators in Javascript are very similar to
operators that appear in other programming
languages. The definition of an operator is a
symbol that is used to perform an operation.
Most often these operations are arithmetic
(addition, subtraction, etc), but not always.
40
Javascript Arithmetic Operator Chart
41
Operator English Example
+ Addition 2 + 4
- Subtraction 6 - 2
* Multiplication 5 * 3
/ Division 15 / 3
% Modulus 43 % 10
42
Assignment operator
Operator Example Same As
= x = y x = y
+= x += y x = x + y
-= x -= y x = x - y
*= x *= y x = x * y
/= x /= y x = x / y
%= x %= y x = x % y
**= x **= y x = x ** y
Javascript Operator Example with Variables
Performing operations on variables that
contain values is very common and easy to
do. Below is a simple script that performs all
the basic arithmetic operations
44
<html>
<body>
<script type="text/javascript">
var two=2
var ten=10
document.write("two + ten = ")
result=two + ten
document.write(result)
</script>
</body>
<html>
45
46
<html>
<body>
<script type="text/javascript">
var two=2
var ten=10
document.write("two - ten = ")
result=two - ten
document.write(result)
</script>
</body>
<html>
47
48
Comparison Operators
Comparisons are used to check the relationship
between variables and/or values. A single equal sign
sets a value while a double equal sign (==) compares
two values. Comparison operators are used inside
conditional statements and evaluate to either true
or false.
49
Operator English Example Result
== Equal To x == y false
!= Not Equal To x != y true
< Less Than x < y true
> Greater Than x > y false
<= Less Than or Equal To x <= y true
>= Greater Than or Equal To x >= y false
50
Logical operator
Operator Description
&& logical and
|| logical or
! logical not
String Operator:The + operator can also be u
to add (concatenate) strings.
Type operator
Operator Description
typeof Returns the type of a variable
instanceof Returns true if an object is an
instance of an object type
Bitwise operator
Operator Descriptio
n
Example Same as Result Decimal
& AND 5 & 1 0101 &
0001
0001 1
| OR 5 | 1 0101 |
0001
0101 5
~ NOT ~ 5 ~0101 1010 10
^ XOR 5 ^ 1 0101 ^
0001
0100 4
<< Zero fill
left shift
5 << 1 0101 << 1 1010 10
>> Signed
right shift
5 >> 1 0101 >> 1 0010 2
>>> Zero fill
right shift
5 >>> 1 0101 >>> 1 0010 2
JavaScript Variables
Variables in Javascript behave the same as
variables in most popular programming
languages (C, C++, etc) except that you don't
have to declare variables before you use
them. If you don't know what declaring is,
don't worry about it, it isn't important!
54
Javascript Using Variables
A variable's purpose is to store information so that it
can be used later. A variable is a symbolic name that
represents some data that you set. To think of a
variable name in real world terms, picture that the
name is a grocery bag and the data it represents are
the groceries. The name wraps up the data so you
can move it around a lot easier, but the name is not
the data!
55
A Variable Example
When using a variable for the first time it is
not necessary to use "var" before the variable
name, but it is a good programming practice
to make it crystal clear when a variable is
being used for the first time in the program.
Here we are showing how the same variable
can take on different values throughout a
script
56
<body>
<script type="text/javascript">
var linebreak = "<br />“
var my_var = "Hello World!“;
document.write(my_var)
document.write(linebreak)
my_var = "I am learning javascript!"
document.write(my_var);
document.write(linebreak)
my_var = "Script is Finishing up..."
document.write(my_var)
</script> </body>
57
58
We made two variables in this example. One to hold the
HTML for a line break and the other was a dynamic variable
that had a total of three different values throughout the
script.
To assign a value to a variable you use the equal sign (=)
with the variable on the left and the value to be assigned
on the right. If you swap the order then your script will not
work correctly! In english the Javascript "myVar = 'Hello
World!'" would be: myVar equals 'Hello World!'.
The first time we used a variable we placed var in front to
signify its first use. In subsequent assignments of the same
variable we did not need the var.
59
Javascript Variable Naming Conventions
When choosing a variable name you must first be
sure that you do not use any of the Javascript
reserved names . Another good practice is choosing
variable names that are descriptive of what the
variable holds. If you have a variable that holds the
size of a shoe, then name it "shoe_size" to make
your Javascript more readable.
60
Finally, Javascript variable names may not start with
a numeral (0-9). These variable names would be
illegal: 7lucky, 99bottlesofbeer, and 3zacharm.
A good rule of thumb is to have your variable names
start with a lowercase letter (a-z) and use
underscores to separate a name with multiple words
(i.e. my_var, strong_man, happy_coder, etc).
61
Javascript Functions
If you have any programming experience, then you
do not need to spend much time on this . Functions
in Javascript behave similar to numerous
programming languages (C, C++, PHP, etc). If this is
your first time learning about functions, then be
sure to go through this very thoroughly as a solid
understanding of functions will make the rest of this
easier to follow
62
What's a Function?
A function is a piece of code that sits dormant until
it is referenced or called upon to do its "function". In
addition to controllable execution, functions are
also a great time saver for doing repeatable tasks.
Instead of having to type out the code every time
you want something done, you can simply call the
function multiple times to get the same effect. This
benefit is also known as "code reusability”
63
Example Function in Javascript
A function does not execute when the page
loads and so it should be placed inside the
head of your HTML document. Creating a
function is really quite easy, all you have to
do is tell the browser you're making a
function, give the function a name, and then
write the Javascript like normal.
64
HTML & JavaScript Code:
<html>
<head>
<script type="text/javascript">
function popup()
{
document.write("Hello World!")
}
</script> </head>
<body>
<input type="button" onclick="popup()" value="popup">
</body>
</html>
65
We first told the browser we were going to be using
a function by typing "function". Next, we gave our
function a name, so that we could use it later. Since
we are making a pop up , we called our function
"popup".
The curly braces "{,}" define the boundaries of our
function code. All popup function code must be
contained within the curly braces.
66
What we didn't talk about was how we got
this function to execute when the button is
clicked. The click is called an event, and we
will be talking about how to make functions
execute from various types of events in the
next lesson.
67
Writing Your Own Function
You can also make your own functions to
be used on your webpage. If you would
like to write your own function then you
must use the special keyword function
68
Events in Javascript
The absolute coolest thing about Javascript is the
ability to create dynamic web pages that increase
user interaction, making the visitor feel like the
website is almost coming alive right before their
eyes.
69
The building blocks of an interactive web page is the
Javascript event system. An event in Javascript is
something that happens with or on the web page. A
few example of events:
A mouse click
The web page loading
Mousing over a hot spot on the web page, also
known as hovering
Selecting an input box in an HTML form
A keystroke
70
A Couple of Examples Using Events
Javascript has predefined names that cover
numerous events that can occur, including the ones
listed above. To capture an event and make
something happen when that event occurs you must
specify the event, the HTML element that will be
waiting for the event, and the function(s) that will
be run when the event occurs.
71
<html>
<head>
<script type="text/javascript">
function popup()
{
document.write("hello")
} </script>
</head>
<body>
<input type="button" value="Click Me!" onclick="popup()">
<br />
<a href="#" onmouseover="popup()" > Hover Me!</a>
</body>
</html>
72
73
74
<html>
<head>
<script type="text/javascript">
function popup()
{
document.write("hello")
} </script>
</head>
<body>
<input type="button" value="Click Me!" onclick="popup()">
<br />
<a href="#" onmouseout="popup()" > Hover Me!</a>
</body>
</html>
75
76
77
With the button we used the event onClick event as
our desired action and told it to call our popup
function that is defined in our header. To call a
function you must give the function name followed
up with parenthesis "()".
Our mouseover and mouseout events were combined
on one HTML element, a link. We wanted to do
nothing when someone put their mouse on the link,
but when the mouse leaves (onMouseout) we
displayed a popup.
78
<html>
<head>
<script type="text/javascript">
function popup()
{
document.write("hello")
}
</script>
</head>
<body>
<input type="button" value="Click Me!"
onmouseout="popup()">
<br />
</body>
</html>
79
80
81
82
Javascript Statements
All the Javascript code that you will write
will, for the most part, be comprised of many
separate statements. A statement is setting a
variable equal to a value. A statement is also
a function call, i.e. document.write().
Statements define what the script will do
and how it will be done.
83
Typical Ending of a Statement
In typical programming languages like C , the
end of a statement is marked with a
semicolon(;), but we have seen that the
colon is optional in javascript. In Javascript
the end of a statement is most often marked
by starting a new line.
84
Categories of Statements
In addition to the standard statements like changing
a variable's value, assigning a new value, or calling a
function, there are groups of statements that are
distinct in their purpose. We will provide a brief
overview of each of these categories .
Conditional Statements
Loop Statements
Object Manipulation Statements
Comment Statements
Exception Handling Statements
85
Conditional Statements
If you were to win a 100 la Rs lottery then you would
probably quit your job. That last statement is a
conditional if/then statement that is used a great
deal in programming. If some condition (winning the
lottery) is true, then something happens (you quit
your job). If the condition is false, then you probably
will not take that action (quit your job).
86
Conditional statements are used to control your
scripts so that different actions can be taken
depending on the situation. You may want to display
a special image on your home page during the
holidays. This condition would depend on what day it
was, and if it was a holiday, then a special holiday
image would be displayed to your visitors. Without
proper knowledge of the conditional statement your
scripts will not be as lively or dynamic as they could
possibly be.
87
Loop Statements
Have you ever had to send out marriage
announcements? If not, this is how it goes. You take
the invitation, place it in the envelope, lick the
envelope, seal the envelope, then send it off. Then
you take the next invitation off the stack of 99
remaining invitations, place it in an envelope, lick
the envelope, seal... You get the idea! It is a boring,
repetitive task!
Wouldn't it be great if there was an easier way? Well
in programming and in Javascript there is. The
process is called "looping" and it will turn your cute
little scripts into massive work horses with the right
planning
88
A loop statement checks to see if some condition is
true, say our condition is "Are there any invitations
left?" and if that condition is true it will execute a
chunk of code. Our code in this example would be to
stuff, lick, and seal the envelope. After the code is
executed the condition is checked again, if it is true
then the process begins again, if it is false, then the
loop code stops execution and the script continues
along.
Believe me when I say this is something you want to
learn more about!
89
Object Manipulation Statements
These are statements that are used to take
advantage of the object model to get tasks
done. If you do not know about the object
model at this time, do not worry. We will be
talking about it later.
90
Comment Statements
Comment statements are used to prevent the
browser from executing certain parts of code that
you designate as non-code. Why would you want to
do this? There are many reasons. By disallowing the
block of text to be read you can then place in
comments for yourself, much like HTML comments,
and you can also block out segments of your code for
whatever reason you may have.
The single line comment is just two slashes (//) and
the multiple line comment starts with (/*) and ends
with (*/).
91
Exception Handling Statements
Sometimes when you are programming you do not know for
sure if the file that you will be writing to, the input stream
you are reading from, or the connection you have
established will be usable for the code that you want to
execute. There is a way to program safety mechanisms, so
that your code handles common problems that may arise
(maybe the input stream you are reading from suddenly
disappears).
The try...catch statement tries to execute a piece of code
and if it fails the catch should handle the error gracefully.
This is an advanced programming subject that is interesting,
but not necessary for the majority of Javascript
programmers.
92
Javascript If Statement
As your Javascript programs get more
sophisticated you will need to make use of
conditional statements that allow your
program to make decisions. Nearly all other
programming languages use conditionals and
Javascript is no exception.
93
The If Statement is a way to make decisions
based on a variable or some other type of
data. For example you might have a variable
that stores the date. With this tiny bit of
information you could easily program a small
script to print out "Today is my Birthday!"
whenever the day and month were equal to
your birthday
94
Javascript If Statement Syntax
There are two major parts to an if statement: the
conditional statement and the code to be executed.
The conditional statement is a statement that will
evaluate to either True or False. The most common
type of a conditional statement used is checking to
see if something equals a value. An example would
be checking if the date equaled your birthday.
95
The code to be executed contains the
Javascript code that will be executed only if
the If Statement's conditional statement was
true. In this simple If Statement example we
print out a message if the variable we are
checking is equal to 7.
96
<html>
<body>
<script type="text/javascript">
var myNum = 7
if(myNum == 7)
{
document.write("Lucky 7!")
}
</script>
</body>html>
97
98
This simple example created myNum and set it to 7.
We then checked to see if myNum was equal to 7
"myNum == 7" in the If Statement's conditional
statement which evaluated to True.
Because the conditional statement was True the
block of code associated with our If Statement
"document.write..." was executed, as you can see in
the Display.
99
Javascript If Statement: Else
We already taught you how to execute code if a
given condition is True, but what if you want to
execute another piece of code if something is False?
The answer is to use an extension to the If
Statement; the Else clause.
The Else clause is executed when the conditional
statement is False. Let's take our example from
above, add an Else clause and change the value of
myNum so that our conditional statement is False.
100