Javascript: Roby John Cdac-Acts Fall 2006
Javascript: Roby John Cdac-Acts Fall 2006
Roby John
CDAC-ACTS
Fall 2006
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)
A JavaScript consists of lines of executable
computer code
A 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
Are Java and JavaScript the Same?
NO!
as 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
JavaScript can be used to detect the visitor's browser
JavaScript can be used to create cookies - A JavaScript can
be used to store and retrieve information on the visitor's
computer
Examples
<html>
<body>
<script type="text/javascript">
document.write("Hello World!")
</script>
</body>
</html>
Guidelines
With traditional programming languages, like C++ and
Java, each code statement has to end with a semicolon.
To use the external script, point to the .js file in the "src" attribute
of the <script> tag:
<html>
<head>
<script src="xxx.js"></script>
</head>
<body>
</body>
</html>
JavaScript 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.
Declare a Variable
Lifetime of Variables
When you declare a variable within a function, the variable can
only be accessed within that function. When you exit the function,
the variable is destroyed. These variables are called local
variables.
You can have local variables with the same name in different
functions, because each is recognized only by the function in
which it is declared.
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!
<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>
<script type="text/javascript">
//Write "Lunch-time!" if the time is 11
var d=new Date()
var time=d.getHours()
if (time==11)
{
document.write("<b>Lunch-time!</b>")
}
</script>
Note: When comparing variables you must always use two equals signs
next to each other (==)! Notice that there is no ..else.. in this syntax. You
just tell the code to execute some code only if the specified condition is
true.
If...else Statement
If you want to execute some code if a condition is
true and another code if the condition is not true,
use the if....else statement.
Syntax
if (condition)
{
code to be executed if condition is true
}
else
{
code to be executed if condition is not true
}
<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.
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
}
<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>
JavaScript Switch Statement
You should use the switch statement if you want to select one of
many blocks of code to be executed.
switch(n)
{
case 1:
execute code block 1
break
case 2:
execute code block 2
break
default:
code to be executed if n is
different from case 1 and 2
}
txt1="What a very"
txt2="nice day!"
txt3=txt1+" "+txt2
variablename=(condition)?value1:value2
Example
the variable visitor is not equal to PRES, then put the string
"Dear " into the variable named greeting.
JavaScript Popup Boxes
In JavaScript we can create three kind of popup
boxes: Alert box, Confirm box, and Prompt box.
Examples
Alert box
Confirm box
Prompt box
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.
alert("sometext")
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.
confirm("sometext")
Prompt Box
A prompt box is often used if you want the user
to input a value before entering a page.
prompt("sometext","defaultvalue")
JavaScript Functions
A function is a reusable code-block that will be
executed by an event, or when the function is
called.
To keep the browser from executing a script as
soon as the page is loaded, you can write your
script as a function.
A function contains some code that will be
executed only by an event or by a call to that
function.
You may call a function from anywhere within the
page (or even from other pages if the function is
embedded in an external .js file).
Functions are defined at the beginning of a page,
in the <head> section.
<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 function below should return the product of two numbers (a and b):
function prod(a,b)
{
x=a*b
return x
}
When you call the function above, you must pass along two parameters:
product=prod(2,3)
The returned value from the prod() function is 6, and it will be stored in
the variable called product.
JavaScript For Loop
The for loop is used when you know in
advance how many times the script should
run.
Syntax
for
(var=startvalue;var<=endvalue;var=var+
increment)
{
code to be executed
}
<html>
<body>
<script type="text/javascript">
var i=0
for (i=0;i<=10;i++)
{
document.write("The number is " + i)
document.write("<br />")
}
</script>
</body>
</html>
JavaScript While Loop
How to write a while loop. Use a while
loop to run the same block of code while a
specified condition is true.
while (var<=endvalue)
{
code to be executed
}
Continue statement
Use the continue statement to break the
current loop and continue with the next
value.
JavaScript break and continue Statements
<html>
<body>
<script type="text/javascript">
var i=0
for (i=0;i<=10;i++)
{
if (i==3){break}
document.write("The number is " + i)
document.write("<br />")
}
</script>
</body>
</html>
<html>
<body>
<script type="text/javascript">
var i=0
for (i=0;i<=10;i++)
{
if (i==3){continue}
document.write("The number is " + i)
document.write("<br />")
}
</script>
</body>
</html>
JavaScript For...In Statement
The for...in statement is used to loop (iterate) through the
elements of an array or through the properties of an object.
The code in the body of the for ... in loop is executed once
for each element/property.
Syntax
<script type="text/javascript">
var x
var mycars = new Array()
mycars[0] = "Saab"
mycars[1] = "Volvo"
mycars[2] = "BMW"
for (x in mycars)
{
document.write(mycars[x] + "<br />")
}
</script>
</body>
</html>
JavaScript Events
By using JavaScript, we have the ability to create
dynamic web pages. Events are actions that can
be detected by JavaScript.
try
{
//Run some code here
}
catch(err)
{
//Handle errors here
}
<html>
<head>
<script type="text/javascript">
function message()
{
adlert("Welcome guest!")
}
</script>
</head>
<body>
<input type="button" value="View message"
onclick="message()" />
</body>
</html>
<html>
<head>
<script type="text/javascript">
var txt=""
function message()
{
try
{
adddlert("Welcome guest!")
}
catch(err)
{
txt="There was an error on this page.\n\n"
txt+="Error description: " + err.description + "\n\n"
txt+="Click OK to continue.\n\n"
alert(txt)
}
}
</script>
</head>
<body>
<input type="button" value="View message" onclick="message()" />
</body>
</html>
<html>
<head>
<script type="text/javascript">
var txt=""
function message()
{
try
{
adddlert("Welcome guest!")
}
catch(err)
{
txt="There was an error on this page.\n\n"
txt+="Click OK to continue viewing this page,\n"
txt+="or Cancel to return to the home page.\n\n"
if(!confirm(txt))
{
document.location.href="http://www.w3schools.com/"
}
}
}
</script>
</head>
<body>
<input type="button" value="View message" onclick="message()" />
</body>
</html>
The throw Statement
The throw statement allows you to create an
exception.
If you use this statement together with the
try...catch statement, you can control program
flow and generate accurate error messages.
Syntax
throw(exception)
onerror=handleErr
function handleErr(msg,url,l)
{
//Handle the error here
return true or false
}
function handleErr(msg,url,l)
{
txt="There was an error on this page.\n\n"
txt+="Error: " + msg + "\n"
txt+="URL: " + url + "\n"
txt+="Line: " + l + "\n\n"
txt+="Click OK to continue.\n\n"
alert(txt)
return true
}
function message()
{
adddlert("Welcome guest!")
}
</script>
</head>
<body>
<input type="button" value="View message" onclick="message()"
/>
</body>
</html>
JavaScript Special Characters
In JavaScript you can add special characters to a text string by using the
backslash sign.
The backslash (\) is used to insert apostrophes, new lines, quotes, and
other special characters into a text string.
To solve this problem, you must place a backslash (\) before each double
quote in "Viking". This turns each double quote into a string literal:
var txt="We are the so-called \"Vikings\" from the north."
document.write(txt)
<script type="text/javascript">
</script>
12
JavaScript Guidelines
JavaScript is Case Sensitive
A function named "myfunction" is not the same as "myFunction"
and a variable named "myVar" is not the same as "myvar".
JavaScript is case sensitive - therefore watch your capitalization
closely when you create or call variables, objects and functions.
White Space
JavaScript ignores extra spaces. You can add white space to your
script to make it more readable. The following lines are
equivalent:
name="Hege"
name = "Hege"
/* This is a comment
block. It contains
several lines */
document.write("Hello World!")
JavaScript Objects Introduction
JavaScript is an Object Oriented Programming (OOP) language.
An OOP language allows you to define your own objects and make
your own variable types.
Object Oriented Programming
getTime()
Use getTime() to calculate the years since 1970.
setFullYear()
How to use setFullYear() to set a specific date.
toUTCString()
How to use toUTCString() to convert today's date (according to
UTC) to a string.
getDay()
Use getDay() and an array to write a weekday, and not just a
number.
Methods
Methods are the actions that can be performed on objects.
<script type="text/javascript">
</script>
HELLO WORLD!
JavaScript String Object
The String object is used to manipulate a stored piece of text.
Common Methods
Style strings
How to style strings.
if (myDate>today)
alert("Today is before 14th January 2010")
else
alert("Today is after 14th January 2010")
JavaScript Array Object
The Array object is used to store a set of values in a single variable name.
Create an array
Create an array, assign values to it, and write the values to the output.
For...In Statement
How to use a for...in statement to loop through the elements of an array.
Or
var mycars=new Array("Saab","Volvo","BMW")
document.write(mycars[0])
Saab
Modify Values in Existing Arrays
To modify a value in an existing array, just add a
new value to the array with a specified index
number:
mycars[0]="Opel"
document.write(mycars[0])
Opel
JavaScript Boolean Object
The Boolean object is used to convert a non-Boolean value to a
Boolean value (true or false).
Boolean Object
The Boolean object is an object wrapper for a Boolean value.
All the following lines of code create Boolean objects with an initial value of
false:
And all the following lines of code create Boolean objects with an initial value
of true:
Math Object
The Math object allows you to perform common mathematical
tasks.
The Math object includes several mathematical values and
functions. You do not need to define the Math object before using
it.
Mathematical Values
JavaScript provides eight mathematical values (constants) that
can be accessed from the Math object. These are: E,
You may reference these values from your JavaScript like this:
Math.E
Math.PI
Math.SQRT2
Math.SQRT1_2
Math.LN2
Math.LN10
Math.LOG2E
Math.LOG10E
JavaScript Cookies
A cookie is often used to identify a user.
A cookie is a variable that is stored on the
visitor's computer. Each time the same
computer requests a page with a browser,
it will send the cookie too.
With JavaScript, you can both create and
retrieve cookie values.
* Name cookie - The first time a visitor arrives to your web
page, he or she must fill in her/his name. The name is then
stored in a cookie. Next time the visitor arrives at your
page, he or she could get a welcome message like
"Welcome John Doe!" The name is retrieved from the
stored cookie
Password cookie - The first time a visitor arrives to your
web page, he or she must fill in a password. The password
is then stored in a cookie. Next time the visitor arrives at
your page, the password is retrieved from the cookie
Date cookie - The first time a visitor arrives to your web
page, the current date is stored in a cookie. Next time the
visitor arrives at your page, he or she could get a message
like "Your last visit was on Tuesday August 11, 2005!" The
date is retrieved from the stored cookie
Create and Store a Cookie
function setCookie(c_name,value,expiredays)
{
var exdate=new Date()
exdate.setDate(expiredays)
document.cookie=c_name+ "=" +escape(value)+
((expiredays==null) ? "" : ";expires="+exdate)
}
function getCookie(c_name)
{
if (document.cookie.length>0)
{
c_start=document.cookie.indexOf(c_name + "=")
if (c_start!=-1)
{
c_start=c_start + c_name.length+1
c_end=document.cookie.indexOf(";",c_start)
if (c_end==-1) c_end=document.cookie.length
return unescape(document.cookie.substring(c_start,c_end))
}
}
return null
}
function checkCookie()
{
username=getCookie('username')
if (username!=null)
{alert('Welcome again '+username+'!')}
else
{
username=prompt('Please enter your name:',"")
if (username!=null||username!="")
{
setCookie('username',username,365)
}
}
}
JavaScript Form Validation
JavaScript can be used to validate input data in
HTML forms before sending off the content to a
server.
is OK):
function validate_required(field,alerttxt)
{
with (field)
{
if (value==null||value=="")
{alert(alerttxt);return false}
else {return true}
}
}
E-mail Validation
The function below checks if the content has the general syntax of an
email.
This means that the input data must contain at least an @ sign and a dot
(.). Also, the @ must not be the first
character of the email address, and the last dot must at least be one
character after the @ sign:
function validate_email(field,alerttxt)
{
with (field)
{
apos=value.indexOf("@")
dotpos=value.lastIndexOf(".")
if (apos<1||dotpos-apos<2)
{alert(alerttxt);return false}
else {return true}
}
}
JavaScript Create Your Own Objects
Creating Your Own Objects
personObj=new Object()
personObj.firstname="John"
personObj.lastname="Doe"
personObj.age=50
personObj.eyecolor="blue"
Adding a method to the personObj is also simple. The following code adds
a method called eat() to the personObj:
personObj.eat=eat
JavaScript Create Your Own Objects
2. Create a template of an object
function person(firstname,lastname,age,eyecolor)
{
this.firstname=firstname
this.lastname=lastname
this.age=age
this.eyecolor=eyecolor
}
Once you have the template, you can create new instances of the object,
like this:
myFather=new person("John","Doe",50,"blue")
myMother=new person("Sally","Rally",48,"green")
You can also add some methods to the person object. This is also done
inside the template:
function person(firstname,lastname,age,eyecolor)
{
this.firstname=firstname
this.lastname=lastname
this.age=age
this.eyecolor=eyecolor
this.newlastname=newlastname
}
Note that methods are just functions attached to objects. Then we will
have to write the newlastname() function:
function newlastname(new_lastname)
{
this.lastname=new_lastname
}
Usage
myMother.newlastname("Doe").