What is JavaScript?
JavaScript was designed to add interactivity to HTML pages
JavaScript is a scripting language
A scripting language is a lightweight programming language
JavaScript is usually embedded directly into HTML pages
JavaScript is an interpreted language (means that scripts
execute without preliminary compilation)
Everyone can use JavaScript without purchasing a license
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 saves the server
from extra processing
JavaScript can be used to detect the visitor's browser - A JavaScript
can be used to detect the visitor's browser, and - depending on the
browser - load another page specifically designed for that browser
JavaScript can be used to create cookies - A JavaScript can be used
to store and retrieve information on the visitor's computer
Example of Java Script
<html>
<body>
<script type="text/javascript">
document.write("This is my first JavaScript!");
</script>
</body>
</html>
JavaScript Code
JavaScript code (or just JavaScript) is a sequence of JavaScript
statements.
Each statement is executed by the browser in the sequence they are
written.
This example will write a heading and two paragraphs to a web page:
Example
<script type="text/javascript">
document.write("<h1>This is a heading</h1>");
document.write("<p>This is a paragraph.</p>");
document.write("<p>This is another paragraph.</p>");
</script>
JavaScript Blocks
JavaScript statements can be grouped together in blocks.
Blocks start with a left curly bracket {, and ends with a right curly bracket }.
The purpose of a block is to make the sequence of statements execute together.
This example will write a heading and two paragraphs to a web page:
Example
<script type="text/javascript">
{
document.write("<h1>This is a heading</h1>");
document.write("<p>This is a paragraph.</p>");
document.write("<p>This is another paragraph.</p>");
}
</script>
The example above is not very useful. It just demonstrates the use of a block. Normally a
block is used to group statements together in a function or in a condition (where a group
of statements should be executed if a condition is met).
Commenting in java script
<html>
<body>
<script type="text/javascript">
<!--
document.write("Hello World!");
//-->
</script>
</body>
</html>
Single line comments start with //.
The following example uses single line comments to explain the code:
Example
<script type="text/javascript">
// Write a heading
document.write("<h1>This is a heading</h1>");
// Write two paragraphs:
document.write("<p>This is a paragraph.</p>");
document.write("<p>This is another paragraph.</p>");
</script>
JavaScript Multi-Line Comments
Multi line comments start with /* and end with */.
The following example uses a multi line comment to explain the code:
Example
<script type="text/javascript">
/*
The code below will write
one heading and two paragraphs
*/
document.write("<h1>This is a heading</h1>");
document.write("<p>This is a paragraph.</p>");
document.write("<p>This is another paragraph.</p>");
</script>
Using Comments to Prevent Execution
In the following example the comment is used to prevent the
execution of a single code line (can be suitable for debugging):
Example
<script type="text/javascript">
//document.write("<h1>This is a heading</h1>");
document.write("<p>This is a paragraph.</p>");
document.write("<p>This is another paragraph.</p>");
</script>
In the following example the comment is used to prevent the
execution of a code block (can be suitable for debugging):
Example
<script type="text/javascript">
/*
document.write("<h1>This is a heading</h1>");
document.write("<p>This is a paragraph.</p>");
document.write("<p>This is another paragraph.</p>");
*/
</script>
Using Comments at the End of a Line
In the following example the comment is placed at the end of a
code line:
Example
<script type="text/javascript">
document.write("Hello"); // Write "Hello"
document.write(" Dolly!"); // Write " Dolly!"
</script>
If 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">
function message()
{
alert("This alert box was called with the onload event");
}
</script>
</head>
<body onload="message()">
</body>
</html>
If you place a script in the body section, it generates the content of
a page.
<html>
<head>
</head>
<body>
<script type="text/javascript">
document.write("This message is written by JavaScript");
</script>
</body>
</html>
Using an External JavaScript
If you want to run the same JavaScript on several pages, without having
to write the same script on every page, you can write a JavaScript in an
external file.
Save the external JavaScript file with a .js file extension.
<html>
<head>
<script type="text/javascript" src="xxx.js"></script>
</head>
<body>
</body>
</html>
Example
<script type="text/javascript">
document.write("<h1>This is a heading</h1>");
document.write("<p>This is a paragraph.</p>");
document.write("<p>This is another paragraph.</p>");
</script>
You can declare JavaScript variables with the var statement:
var x;
var carname;
After the declaration shown above, the variables are empty (they have
no values yet).
However, you can also assign values to the variables when you
declare them:
var x=5;
var carname="Volvo";
JavaScript Arithmetic
As with algebra, you can do arithmetic operations with JavaScript variables:
y=x-5;
z=y+5;
JavaScript Arithmetic Operators
Arithmetic operators are used to perform arithmetic between variables and/or values.
Given that y=5, the table below explains the arithmetic operators:
Operator Description Example Result
+ Addition x=y+2 x=7
- Subtraction x=y-2 x=3
* Multiplication x=y*2 x=10
/ Division x=y/2 x=2.5
% Modulus (division x=y%2 x=1
remainder)
++ Increment x=++y x=6
-- Decrement x=--y x=4
JavaScript Assignment Operators
Assignment operators are used to assign values to JavaScript variables.
Given that x=10 and y=5, the table below explains the assignment
operators:
Operator Example Same As Result
= x=y x=5
+= x+=y x=x+y x=15
-= x-=y x=x-y x=5
*= x*=y x=x*y x=50
/= x/=y x=x/y x=2
%= x%=y x=x%y x=0
The + Operator Used on Strings
The + operator can also be used to add string variables or text values together.
To add two or more string variables together, use the + operator.
txt1="What a very";
txt2="nice day";
txt3=txt1+txt2;
After the execution of the statements above, the variable txt3 contains "What a
verynice day".
To add a space between the two strings, insert a space into one of the strings:
txt1="What a very ";
txt2="nice day";
txt3=txt1+txt2;
or insert a space into the expression:
txt1="What a very";
txt2="nice day";
txt3=txt1+" "+txt2;
After the execution of the statements above, the variable txt3 contains:
"What a very nice day"
JavaScript is Case Sensitive
Unlike HTML, JavaScript is case sensitive - therefore watch your capitalization
closely when you write JavaScript statements, create or call variables, objects
and functions.
Adding Strings and Numbers
The rule is: If you add a number and a string, the result will be a string!
Example
x=5+5;
document.write(x);
x="5"+"5";
document.write(x);
x=5+"5";
document.write(x);
x="5"+5;
document.write(x);
Comparison Operators
Comparison operators are used in logical statements to determine equality or
difference between variables or values.
Given that x=5, the table below explains the comparison operators:
Operator Description Example
== is equal to x==8 is false
=== is exactly equal to (value and x===5 is true
type) x==="5" is false
!= is not equal x!=8 is true
> is greater than x>8 is false
< is less than x<8 is true
>= is greater than or equal to x>=8 is false
<= is less than or equal to x<=8 is true
How Can it be Used
Comparison operators can be used in conditional statements to compare values
and take action depending on the result:
if (age<18) document.write("Too young");
You will learn more about the use of conditional statements in the next chapter
of this tutorial.
Logical Operators
Logical operators are used to determine the logic between variables or values.
Given that x=6 and y=3, the table below explains the logical operators:
Operator Description Example
&& and (x < 10 && y > 1) is true
|| or (x==5 || y==5) is false
! not !(x==y) is true
Conditional Operator
JavaScript also contains a conditional operator that assigns a value to a variable
based on some condition.
Syntax
variablename=(condition)?value1:value2
Example
greeting=(visitor=="PRES")?"Dear President ":"Dear ";
If the variable visitor has the value of "PRES", then the variable greeting will
be assigned the value "Dear President " else it will be assigned "Dear".
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 the following conditional statements:
if statement - use this statement to execute some code only if a
specified condition is true
if...else statement - use this statement to execute some code if the
condition is true and another code if the condition is false
if...else if....else statement - use this statement to select one of many
blocks of code to be executed
switch statement - use this statement to select one of many blocks of
code to be executed
If Statement
Use the if statement to execute some code only if a specified condition is true.
Syntax
if (condition)
{
code to be executed if condition is true
}
Note that if is written in lowercase letters. Using uppercase letters (IF) will
generate a JavaScript error!
Example
<script type="text/javascript">
//Write a "Good morning" greeting if
//the time is less than 10
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 tell the browser to execute
some code only if the specified condition is true.
If...else Statement
Use the if....else statement to execute some code if a condition is true
and another code if the condition is not true.
Syntax
if (condition)
{
code to be executed if condition is true
}
else
{
code to be executed if condition is not true
}
Example
<script type="text/javascript">
//If the time 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>
If...else if...else Statement
Use the if....else if...else statement to select one of several blocks of code to be
executed.
Syntax
if (condition1)
{
code to be executed if condition1 is true
}
else if (condition2)
{
code to be executed if condition2 is true
}
else
{
code to be executed if condition1 and condition2 are not true
}
Example
<script type="text/javascript">
var d = new Date()
var time = d.getHours()
if (time<10)
{
document.write("<b>Good morning</b>");
}
else if (time>10 && time<16)
{
document.write("<b>Good day</b>");
}
else
{
document.write("<b>Hello World!</b>");
}
</script>
Alert Box
An alert box is often used if you want to make sure information comes through
to the user.
When an alert box pops up, the user will have to click "OK" to proceed.
Syntax
alert("sometext");
Example
<html>
<head>
<script type="text/javascript">
function show_alert()
{
alert("I am an alert box!");
}
</script>
</head>
<body>
<input type="button" onclick="show_alert()" value="Show alert box" />
</body>
</html>
Confirm Box
A confirm box is often used if you want the user to verify or accept something.
When a confirm box pops up, the user will have to click either "OK" or "Cancel"
to proceed.
If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box
returns false.
Syntax
confirm("sometext");
Example
<html>
<head>
<script type="text/javascript">
function show_confirm()
{
var r=confirm("Press a button");
if (r==true)
{
document.write("You pressed OK!");
}
else
{
document.write("You pressed Cancel!");
}
}
</script>
</head>
<body>
<input type="button" onclick="show_confirm()" value="Show confirm box" />
</body>
</html>
Prompt Box
A prompt box is often used if you want the user to input a value before entering
a page.
When a prompt box pops up, the user will have to click either "OK" or "Cancel"
to proceed after entering an input value.
If the user clicks "OK" the box returns the input value. If the user clicks "Cancel"
the box returns null.
Syntax
prompt("sometext","defaultvalue");
Example
<html>
<head>
<script type="text/javascript">
function show_prompt()
{
var name=prompt("Please enter your name","Harry Potter");
if (name!=null && name!="")
{
document.write("Hello " + name + "! How are you today?");
}
}
</script>
</head>
<body>
<input type="button" onclick="show_prompt()" value="Show prompt box" />
</body>
</html>
JavaScript Function Example
Example
<html>
<head>
<script type="text/javascript">
function displaymessage()
{
alert("Hello World!");
}
</script>
</head>
<body>
<form>
<input type="button" value="Click me!" onclick="displaymessage()" />
</form>
</body>
</html>
The return Statement
The return statement is used to specify the value that is returned from the
function.
So, functions that are going to return a value must use the return statement.
The example below returns the product of two numbers (a and b):
Example
<html>
<head>
<script type="text/javascript">
function product(a,b)
{
return a*b;
}
</script>
</head>
<body>
<script type="text/javascript">
document.write(product(4,3));
</script>
</body>
</html>
onFocus, onBlur and onChange
The onFocus, onBlur and onChange events are often used in combination with
validation of form fields.
Below is an example of how to use the onChange event. The checkEmail()
function will be called whenever the user changes the content of the field:
<input type="text" size="30" id="email" onchange="checkEmail()">
onSubmit
The onSubmit event is used to validate ALL form fields before submitting it.
Below is an example of how to use the onSubmit event.
The checkForm() function will be called when the user clicks the submit button in
the form.
If the field values are not accepted, the submit should be cancelled.
The function checkForm() returns either true or false.
If it returns true the form will be submitted, otherwise the submit will be
cancelled:
<form method="post" action="xxx.htm" onsubmit="return checkForm()">
Assignments
HOW IT'S DONE
Here's the entire page, minus my comments. Take a few minutes to
learn as much as you can from this, then I'll break it down into smaller
pieces.
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
<!-- Beginning of JavaScript -
function MsgBox (textstring) {
alert (textstring) }
// - End of JavaScript - -->
</SCRIPT>
</HEAD>
<BODY>
<FORM>
<INPUT NAME="text1" TYPE=Text>
<INPUT NAME="submit" TYPE=Button VALUE="Show Me"
onClick="MsgBox(form.text1.value)">
</FORM>
</BODY>
</HTML>
Here is a look at the script. See if you can trace how it works.
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
<!-- Beginning of JavaScript -
function changecolor(code) {
document.bgColor=code
// - End of JavaScript - -->
</SCRIPT>
</HEAD>
<BODY>
<form>
<input type="button" name="Button1" value="RED"
onclick="changecolor('red')">
<input type="button" name="Button2" value="GREEN"
onclick="changecolor('green')">
<input type="button" name="Button3" value="BLUE"
onclick="changecolor('blue')">
<input type="button" name="Button4" value="WHITE"
onclick="changecolor('white')">
</form>
</BODY>
</HTML>
This is a good example of an If-Then statement. Password scripts can also be
combined with an encryption function so that hackers can't break in simply
by viewing your source code. The purpose of this chapter, however, is to
give you some practice with if-then statements.
<HTML>
<HEAD>
<TITLE>Chapter 3, If-then statements</TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!-- Beginning of JavaScript -
function password() {
Ret = prompt('Type the word castle',"");
if(Ret=="castle") {
location = 'ch03_1.htm';
} else {
alert("Please try again")
// - End of JavaScript - -->
</SCRIPT>
</HEAD>
<BODY>
<A HREF="javascript:password()">
<IMG SRC="pict1.gif" NAME="pic1" ALT="about us!" BORDER="0"
align="left"></A>
<H3>Click the image to enter a password protected document. Try a
wrong entry first.</H3>
</BODY>
</HTML>
Definition and Usage
The eval() function evaluates a string and executes it as if it was script code.
Syntax
eval(string)
Parameter Description
string Required. The string to be evaluated
Example
In this example we use eval() on some strings and see what it returns:
<script type="text/javascript">
eval("x=10;y=20;document.write(x*y)");
document.write("<br />");
document.write(eval("2+2"));
document.write("<br />");
var x=10;
document.write(eval(x+17));
document.write("<br />");
</script>
The output of the code above will be:
200
4
27