Are Java and JavaScript the same?
NO!
Java and JavaScript are two completely different
languages!
JavaScript was developed by Netscape, and is a
scripting language that is like a lightweight programming
language.
Java (developed by Sun Microsystems) is a powerful
and very complex programming language - in the
same category of languages like C and C++.
What can a JavaScript Do?
- JavaScript gives HTML designers a programming
tool - HTML authors are normally not programmers,
but JavaScript is a scripting language with
a very simple syntax! Almost anyone can put
small "snippets" of code into their HTML pages
- JavaScript can put dynamic text into an
HTML page - A JavaScript statement like
this: document.write("<h1>" + name + "</h1>")
can write a variable text into an HTML page
- JavaScript can react to events - A
JavaScript can be set to execute when something
happens, like when a page has finished loading
or when a user clicks on an HTML element
- JavaScript can read and write HTML elements
- A JavaScript can read and change the
content of an HTML element
- JavaScript can be used to validate data
- A JavaScript can be used to validate
form data before it is submitted to a server,
this will save the server from extra processing
How to Put a JavaScript Into an HTML Page
<html>
<body>
<script type="text/javascript">
document.write("Hello World!")
</script>
</body>
</html>
|
The code above will produce this output on an
HTML page:
Example Explained
To
insert a script in an HTML page, we use the <script> tag.
Use the
type attribute to define the scripting language
<script type="text/javascript">
|
Then the JavaScript starts: The JavaScript command for writing some output
to a page is document.write
document.write("Hello World!")
|
Then the <script> tag
has to be closed
Ending Statements With a Semicolon?
With traditional programming languages, like C++ and Java, each code statement
has to end with a semicolon.
Many programmers continue this habit when writing JavaScript, but in general,
semicolons are optional! However, semicolons are required if you want
to put more than one statement on a single line.
How to Handle Older Browsers
Browsers that do not support scripts will display the script as page content.
To prevent them from doing this, we may use the HTML comment tag:
<script type="text/javascript">
<!--
some statements
//-->
</script>
|
The two forward slashes at the end of comment line (//) are a JavaScript comment
symbol. This prevents the JavaScript compiler from compiling the line.
Where to Put the JavaScript
Scripts in a page will be executed immediately while the page loads into the
browser. This is not always what we want. Sometimes we want to execute a script
when a page loads, other times when a user triggers an event.
Scripts in the head section: Scripts
to be executed when they are called, or when an event is triggered, go in
the head section. When you place a script
in the head section, you will ensure that the script is loaded before anyone
uses it.
<html>
<head>
<script type="text/javascript">
some statements
</script>
</head>
|
Scripts in the body section: Scripts to be executed when the page loads
go in the body section. When you place a script in the body section it generates
the content of the page.
<html>
<head>
</head>
<body>
<script type="text/javascript">
some statements
</script>
</body>
|
Scripts in both the body and the head section: You can place an unlimited
number of scripts in your document, so you can have scripts in both the body
and the head section.
<html>
<head>
<script type="text/javascript">
some statements
</script>
</head>
<body>
<script type="text/javascript">
some statements
</script>
</body>
|
JavaScript is Case Sensitive
A function
named "myfunction" is not the same as "myFunction".
Therefore watch your capitalization when you create or call variables, objects
and
functions.
Break up a Code Line
You can break up a code line within a text string with a backslash. The
example below will be displayed properly:
document.write("Hello \
World!")
|
Note: You can not break up a code line like this:
document.write \
("Hello World!")
|
The example above will cause an error.
Insert Special Characters
You can
insert special characters
(like " ' ; &) with the backslash:
document.write ("You \& I say \"Go Bulldogs\".")
|
The example above will produce this output:
You & I say "Go Bulldogs".
|
Comments
You can
add a comment to
your JavaScript
code starting the comment with
two slashes "//":
sum=a + b //calculating the sum
|
You can
also add a comment to the JavaScript code, starting the comment with "/*" and
ending it with "*/"
sum=a + b /*calculating the sum*/
|
Using "/*" and "*/" is
the only way to create a multi-line comment:
/* This is a comment
block. It contains
several lines*/
|
How to Run an External JavaScript
Sometimes you might want to run the same script on several pages, without writing
the script on each and every page.
To simplify this you can write a script in an external file, and save it with
a .js file extension, like this:
document.write("This script is external")
|
Save the external file as xxx.js.
Note: The
external script cannot contain the <script> tag
Now you
can call this script, using the "src" attribute, from any of your
pages:
<html>
<head>
</head>
<body>
<script src="xxx.js"></script>
</body>
</html>
|
Remember to place the script exactly where you normally would write the script.
Variables
A variable
is a "container" for
information you want to store. A variable's value can change during the script.
You can refer
to a variable by name to see its
value or to change its value. Rules for Variable names:
- Variable names are case sensitive
- They must begin with a letter or the underscore character
Declare a Variable
You can create a variable with the var statement:
You can also create a variable without the var statement:
Assign a Value to a Variable
You assign a value to a variable like this:
Or like this:
Functions
A function contains some code that will be executed by an event or a call to
that function. A function is a set of statements. You can reuse functions within
the same script, or in other documents. You define functions at the beginning
of a file (in the head section), and call them later in the document. It is now
time to take a lesson about the alert-box:
This is JavaScript's method to alert the user.
alert("This is a message")
|
How to Define a Function
To create
a function you
define its
name, any values ("arguments"), and some
statements:
function myfunction(argument1,argument2,etc)
{
some statements
}
|
A function with no arguments must include the parentheses:
function myfunction()
{
some statements
}
|
Arguments are variables used in the function. The variable values are values
passed on by the function call.
By placing functions in the head section of the document, you make sure that
all the code in the function has been loaded before the function is called.
Some functions return a value to the calling expression
function result(a,b)
{
c=a+b
return c
}
|
How to Call a Function
A function is not executed before it is called.
You can call a function containing arguments:
myfunction(argument1,argument2,etc)
|
or without arguments:
The return Statement
Functions
that will return
a result
must use the "return" statement. This statement
specifies the value which will be returned to where the function was called from.
Say you have a function that returns the sum of two numbers:
function total(a,b)
{
result=a+b
return result
}
|
When you call this function you must send two arguments with it:
The returned value from the function (5) will be stored in the variable called
sum.
Conditional Statements
Very often when you write code, you want to perform different actions for different
decisions. You can use conditional statements in your code to
do this.
In JavaScript we have three conditional statements:
- if statement - use this statement if you want to execute a set
of code when a condition is true
- if...else statement - use this statement if you want to select
one of two sets of lines to execute
- switch statement - use this statement if you want to select one
of many sets of lines to execute
If and If...else Statement
You should use the if statement if you want to execute some code if a condition
is true.
Syntax
if (condition)
{
code to be executed if condition is true
}
|
Example
<script type="text/javascript">
//If the time on your browser is less than 10,
//you will get a "Good morning" greeting.
var d=new Date()
var time=d.getHours()
if (time<10)
{
document.write("<b>Good morning</b>")
}
</script>
|
Notice that there is no ..else.. in this syntax. You just tell the code to
execute some code if the condition is true.
If you want to execute some code if a condition is true and another code if
a condition is false, use the if....else statement.
Syntax
if (condition)
{
code to be executed if condition is true
}
else
{
code to be executed if condition is false
}
|
Example
<script type="text/javascript">
//If the time on your browser is less than 10,
//you will get a "Good morning" greeting.
//Otherwise you will get a "Good day" greeting.
var d = new Date()
var time = d.getHours()
if (time < 10)
{
document.write("Good morning!")
}
else
{
document.write("Good day!")
}
</script>
|
Switch Statement
You should use the Switch statement if you want to select one of many blocks
of code to be executed.
Syntax
switch (expression)
{
case label1:
code to be executed if expression = label1
break
case label2:
code to be executed if expression = label2
break
default:
code to be executed
if expression is different
from both label1 and label2
}
|
This is how it works: First we have a single expression (most often a variable),
that is evaluated once. The value of the expression is then compared with the
values for each case in the structure. If there is a match, the block of code
associated with that case is executed. Use break to prevent the code
from running into the next case automatically.
Example
<script type="text/javascript">
//You will receive a different greeting based
//on what day it is. Note that Sunday=0,
//Monday=1, Tuesday=2, etc.
var d=new Date()
theDay=d.getDay()
switch (theDay)
{
case 5:
document.write("Finally Friday")
break
case 6:
document.write("Super Saturday")
break
case 0:
document.write("Sleepy Sunday")
break
default:
document.write("I'm looking forward to this weekend!")
}
</script>
|
Looping
Very often when you write code, you want the same block of code to run a number
of times. You can use looping statements in your code to do this.
In JavaScript we have the following looping statements:
- while - loops through a block of code while a condition is true
- do...while - loops through a block of code once, and then repeats
the loop while a condition is true
- for - run statements a specified number of times
while
The while
statement will
execute
a block of code while a condition is true..
while (condition)
{
code to be executed
}
|
do...while
The do...while statement will execute a block of code once, and then it will
repeat the loop while a condition is true
do
{
code to be executed
}
while (condition)
|
for
The for statement will execute a block of code a specified number of times
for (initialization; condition; increment)
{
code to be executed
}
|