Java Script
Java Script
<html>
<head>
</head>
<body>
<script language="JavaScript">
document.write("Hello World!")
</script>
</body>
</html>
Hello World!
To insert a script in an HTML document, use the <script> tag. Use the language attribute to define the
scripting language.
<script language="JavaScript">
Then comes the JavaScript: In JavaScript the command for writing some text on a page is
document.write:
document.write("Hello World!")
</script>
<script language="JavaScript">
<!--
some statements
//-->
</script>
The two forward slashes on front of the end of comment line (//-->) are a JavaScript comment symbol, and
prevent the JavaScript from trying to compile the line.
Note that you cannot put // in front of the first comment line (like //<!--), because older browser will display it.
Funny? Yes ! But that's the way it is.
<html>
<head>
<script language="JavaScript">
some statements
</script>
</head>
Scripts in the body section: Scripts to be executed when the page loads, goes 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 language="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 language="JavaScript">
some statements
</script>
</head>
<body>
<script language="JavaScript">
some statements
</script>
</body>
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.
Declaring Variables
Or like this:
strname = "Hege"
The variable name is on the left side of the expression and the value you want to assign to the variable is
on the right. Now the variable "strname" has the value "Hege".
Assignment Operators
Lifetime of Variables
When you declare a variable within a function, only code within that function can access or change the
value of that variable. When the function exits, 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 you declare a variable outside a function, all the functions in your script will recognize it. These variables
exists from the time they are declared until the time the script is finished running.
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:
function myfunction(argument1,argument2,etc)
{
some statements
}
function myfunction()
{
some statements
}
Arguments are variables that will be used in the function. The variable values will be the 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.
function result(a,b)
{
c=a+b
return c
}
myfunction(argument1,argument2,etc)
or without arguments:
myfunction()
function total(a,b)
{
result=a+b
return result
}
When you call this function you must send two arguments with it:
sum=total(2,3)
Conditionals
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 two conditional statements:
• 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 Condition
You should use the this statement if you want to execute some code if a condition is true, or if you want to
select one of two blocks of code to execute.
If you want to execute only one statement when a condition is true, use this syntax for the if...else
statement, like this:
if (condition)
{
code to be executed if condition is true
}
Notice that there is no ..else.. in this syntax. You just tell the code to perform one action if the condition is
true.
If you want to execute some statements if a condition is true and execute others if a condition is false, use
this syntax for the if....else statement, like this:
if (condition)
{
code to be executed if condition is true
}
else
{
code to be executed if condition is false
}
Equality Operators
Operator Meaning
== is equal to
!= is not equal to
> is greater than
>= is greater than or equal to
< is less than
<= is less than or equal to
Switch Condition
You should use the this statement if you want to select one of many blocks of code to execute.
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
}
Looping
Very often when you write code, you want allow the same block of code to run a number of times. You can
use looping statements in your code to do this.
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
Symbols
Open symbols, like ( { [ " ', must have a matching closing symbols, like ' " ] } ).
White Space
JavaScript ignores extra spaces. You can add white space to your script to make it more readable. These
two lines means exactly the same:
name="Hege"
name = "Hege"
document.write \
("Hello World!")
You can insert special characters (like " ' ; &) with the backslash:
Comments
You can add a comment to your JavaScript code starting the comment with "'//":
You can also add a comment to the JavaScript code, starting the comment with "/*" and ending it with "*/"
Using "/*" and "*/" is the only way to create a multi-line comment:
/* This is a comment
block. It contains
several lines*/
Examples
The length() Method
Use the length property to find out how many character there is in the string.
The expecting number of elements goes inside the parentheses, in this case 3. You assign data to each of
the elements of the array like this:
names[0] = "Tove"
names[1] = "Jani"
names[2] = "Ståle"
Similarly, the data can be retrieved from any element using an index into the particular array element you
want. Like this:
mother = names[0]
mydate=new Date()
You can write a date inside the parentheses, if not, the "mydate" variable contains today's date, see the
Date() example below. Now you can access all the methods in the Date object from this variable. Example:
mydate.getDay()
Math.random()
Browser:
<html>
<head>
<script language="JavaScript">
document.write("You are browsing this site with: "+ navigator.appName)
</script>
</head>
<body>
</body>
</html>
Message:
<html>
<head>
<script language="JavaScript">
function browserversion()
{
txt="Your Browser is unknown"
browser=navigator.appVersion
if (browser.indexOf("2.")>-1)
{
txt="Your Browser is from the stone-age"
}
if (browser.indexOf("3.")>-1)
{
txt="You should update your Browser."
}
if (browser.indexOf("4.")>-1)
{
txt="Your Browser is good enough"
}
document.forms[0].message.value=txt
}
</script>
</head>
<body onload="browserversion()">
<form>
<input type="text" name="message" size="50">
</form>
</body>
</html>
E-Mail schicken:
<html>
<head>
<script language="JavaScript">
function validate()
{
at=document.forms[0].email.value.indexOf("@")
if (at<0)
{
alert("Not a valid e-mail")
document.forms[0].action="tryjs_email.htm"
}
}
</script>
</head>
<body>
<form onsubmit="validate()" action="tryjs_rightpage.htm">
<input type="text" name="email" size="30">
<input type="submit" value="Validate">
</form>
</body>
</html>
Change Url:
<html>
</html>
<html>
<head>
<script language="JavaScript">
function changeurl()
{
parent.upperframe.location.href="html_frame_c.htm"
parent.lowerframe.location.href="html_frame_d.htm"
}
</script>
</head>
<body>
<form>
<input type="button" value="Change url"
onclick="changeurl()">
</form>
</body>
</html>
Alert:
<html>
<body>
<script language="JavaScript">
alert("Hello World!")
</script>
</body>
</html>
Confirm Box:
<html>
<body>
<script language="JavaScript">
var name = confirm("Press a button")
if (name == true)
{
document.write("You pressed OK")
}
else
{
document.write("You pressed Cancel")
}
</script>
</body>
</html>
HTML:
<html>
<head>
<title>Title of page</title>
</head>
<body>
This is my first homepage. <b>This is some text</b>
</body>
</html>
Start your Internet browser and type "c:\mypage.htm" in the browser's address field, and the browser will
display the page.
Basic Tags:
Link Tags:
<a href="http://www.w3schools.com"
style="text-decoration:none">
THIS IS A LINK!
</a>
</body>
</html>
<html>
<body>
<p>
<a href="#C4">
See also Chapter 4.
</a>
</p>
<p>
<h2>Chapter 1</h2>
<p>This chapter explains ba bla bla</p>
<h2>Chapter 2</h2>
<p>This chapter explains ba bla bla</p>
<h2>Chapter 3</h2>
<p>This chapter explains ba bla bla</p>
<a name="C4"></a>
<h2>Chapter 4</h2>
<p>This chapter explains ba bla bla</p>
<h2>Chapter 5</h2>
<p>This chapter explains ba bla bla</p>
<h2>Chapter 6</h2>
<p>This chapter explains ba bla bla</p>
<h2>Chapter 7</h2>
<p>This chapter explains ba bla bla</p>
<h2>Chapter 8</h2>
<p>This chapter explains ba bla bla</p>
<h2>Chapter 9</h2>
<p>This chapter explains ba bla bla</p>
<h2>Chapter 10</h2>
<p>This chapter explains ba bla bla</p>
<h2>Chapter 11</h2>
<p>This chapter explains ba bla bla</p>
<h2>Chapter 12</h2>
<p>This chapter explains ba bla bla</p>
<h2>Chapter 13</h2>
<p>This chapter explains ba bla bla</p>
<h2>Chapter 14</h2>
<p>This chapter explains ba bla bla</p>
<h2>Chapter 15</h2>
<p>This chapter explains ba bla bla</p>
<h2>Chapter 16</h2>
<p>This chapter explains ba bla bla</p>
<h2>Chapter 17</h2>
<p>This chapter explains ba bla bla</p>
</body>
</html>
<html>
<body>
<a href="http://www.microsoft.com"
target="_blank">Microsoft</a>
<p>
If you set the target attribute of a link to "_blank",
the link will open in a new window.
</p>
</body>
</html>
Mailto:
<html>
<body>
</body>
</html>
Frame Tags:
Table Tags:
List Tags:
Form Tags:
Image Tags:
Try it yourself
The World Wide Web Consortium (W3C) has removed the <font> tag from its recommendations. If future
versions of HTML, style sheets (CSS) will be used to define the layout and display properties of HTML
elements.
Style Tags
<head>
<p>This is some text</p>
</head>
If you put an HTML element like <h1> or <p> inside a head element like this, most browsers will display it,
even if it is illegal.
Should browsers forgive you for errors like this? We don't think so. Others do.
Head Tags:
<meta name="description" content="Free Web tutorials on HTML, CSS, XML, and XHTML">
Script Tags:
Start Tag NN IE W3 Purpose
<script> 3.0 3.0 3.2 Defines a script
<noscript> 3.0 3.0 4.0 Defines a noscript section for browsers that do not support scripting
<object> 3.0 4.0 Defines an embedded object
<param> 3.0 3.0 3.2 Defines run-time settings (parameters) for an object
<applet> Deprecated. Use <object> instead
List of differences:
• Tags and attributes must be in lowercase
• All XHTML elements must be closed
• Attribute values must be quoted and minimization is forbidden
• The id attribute replaces the name attribute
• The script element needs a type definition
• Documents must conform to XML rules
• XHTML documents have some mandatory elements
This is wrong:
<BODY BGCOLOR="#CCCCCC">
<P>This is a paragraph<P>
</BODY>
This is correct:
<body bgcolor="#CCCCCC">
<p>This is a paragraph</p>
</body>
This is wrong:
<p>This is a paragraph
<p>This is another paragraph
This is correct:
<p>This is a paragraph</p>
<p>This is another paragraph</p>
Empty elements must either have an end tag or the start tag must end with />.
This is wrong:
This is a break<br>
Here comes a horizontal rule:<hr>
This is correct:
This is a break<br/>
This is a break too<br></br>
To make your XHTML compatible with today's browsers, you should add an extra space before the
backslash symbol like this: <br /> and this <hr />.
<table rows=3>
This is correct:
<table rows="3">
<dl compact>
<input checked>
<option selected>
This is correct:
<dl compact="compact">
<input checked="checked">
<option selected="selected">
This is correct:
(To interoperate with older browsers for a while, you can try to use both name and id, with identical attribute
values).
To make your XHTML compatible with today's browsers, you should add an extra space before the "/"
symbol like this:
<script>
<![CDATA[
... script content ...
]]>
</script>
In HTML some elements can be improperly nested within each other like this:
In XHTML all elements must be properly nested within each other like this
All XHTML elements must be nested within the <html> root element. All other elements can have sub
(children) elements. Sub elements must be in pairs and correctly nested within their parent element. The
basic document structure is:
<html>
<head> ... </head>
<body> ... </body>
</html>
You can read more about the XML syntax in our XML School.
<!DOCTYPE html>
<html>
<head>
<title>This is a Title</title>
</head>
<body>
.
Body text goes here
.
</body>
</html>
• the DOCTYPE
• the Head
• the Body
<!DOCTYPE ...>
<html ... >
<head> ... </head>
<body> ... </body>
</html>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/strict.dtd">
<html>
<head>
<title>simple document</title>
</head>
<body>
<p>a simple paragraph</p>
</body>
</html>
The DOCTYPE definition specifies the document type:
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/strict.dtd">
<html>
<head>
<title>simple document</title>
</head>
<body>
<p>a simple paragraph</p>
</body>
</html>
Validating an XHTML document's content involves checking its markup against a DTD and reporting
markup errors. There are currently 3 XHTML document types:
• STRICT
• TRANSITIONAL
• FRAMESET
XHTML 1.0 specifies three XML document types that correspond to the three HTML 4.0 DTDs: Strict,
Transitional, and Frameset.
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/strict.dtd">
Use this when you want really clean markup, free of presentational clutter. Use this together with Cascading
Style Sheets.
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/transitional.dtd">
Use this when you need to take advantage of HTML's presentational features because many of your
readers don't have the latest browsers that understand Cascading Style Sheets.
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN"
"http://www.w3.org/TR/xhtml1/DTD/frameset.dtd">
Use this when you want to use HTML Frames to partition the browser window into two or more frames.
<html>
<head>
</head>
<body>
<script language="VBScript">
document.write("I am written using VBScript!")
</script>
</body>
</html>
To insert a script in an HTML document, use the <script> tag. Use the language attribute to define the
scripting language.
<script language="VBScript">
Then comes the VBScript: The command for writing some text on a page is document.write:
</script>
<script language="VBScript">
<!--
some statements
-->
</script>
Scripts in the head section: Scripts to be executed when they are called or when an event is triggered,
goes in the head section. When you place a script in the head section you will assure that the script is
loaded before anyone uses it.
<html>
<head>
<script language="VBScript">
some statements
</script>
</head>
Scripts in the body section: Scripts to be executed when the page loads, goes 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 language="VBScript">
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 language="VBScript">
some statements
</script>
</head>
<body>
<script language="VBScript">
some statements
</script>
</body>
What is a Variable?
A variable is a "container" for information you want to store. A variables value can change during the script.
You can refer to a variable by name to see its value or to change its value. In VBScript, all variables are of
type variant, that can store different types of data.
dim name
name = some value
Now you have created a variable. The name of the variable is "name".
You can also declare variables by using its name in your script. Like this:
Now you have also created a variable. The name of the variable is "name".
However, the last method is not a good practice, because you can misspell the variable name later in your
script, and that can cause strange results when your script is running. This is because when you misspell
for example the "name" variable to "nime" the script will automatically create a new variable called "nime".
To prevent your script from doing this you can use the Option Explicit statement. When you use this
statement you will have to declare all your variables with the dim, public or private statement. Put the Option
Explicit statement on the top of your script. Like this:
option explicit
dim name
name = some value
name = "Hege"
i = 200
The variable name is on the left side of the expression and the value you want to assign to the variable is
on the right. Now the variable "name" has the value "Hege".
Lifetime of Variables
How long a variable exists is its lifetime.
When you declare a variable within a procedure, only code within that procedure can access or change the
value of that variable. When the procedure exits, the variable is destroyed. These variables are called local
variables. You can have local variables with the same name in different procedures, because each is
recognized only by the procedure in which it is declared.
If you declare a variable outside a procedure, all the procedures in your script will recognize it. These
variables exists from the time they are declared until the time the script is finished running.
Array Variables
Some times you want to assign more than one value to a single variable. Then you can create a variable
that can contain a series of values. This is called an array variable. The declaration of an array variable
uses parentheses ( ) following the variable name. In the following example, an array containing 3 elements
is declared:
dim names(2)
The number shown in the parentheses is 2. We start at zero so this array contains 3 elements. This is a
fixed-size array. You assign data to each of the elements of the array like this:
names(0) = "Tove"
names(1) = "Jani"
names(2) = "Ståle"
Similarly, the data can be retrieved from any element using an index into the particular array element you
want. Like this:
mother = names(0)
You can have up to 60 dimensions in an array. Multiple dimensions are declared by separating the numbers
in the parentheses with commas. Here we have a two-dimensional array consisting of 5 rows and 7
columns:
dim table(4, 6)
VBScript Procedures
We have two kinds of procedures: The Sub procedure and the Function procedure.
A Sub Procedure:
Sub mysub()
some statements
End Sub
Function myfunction()
some statements
myfunction = some value
End Function
Using Sub and Function Procedures in Code
When you call a Function in your code, you do like this:
name = findname()
Here you call a Function called "findname", the Function returns a value that will be stored in the variable
"name".
Here you also call a Function called "findname", the Function returns a value that will be displayed in the
message box.
When you call a Sub procedure you can just type the name of the procedure. You can use the Call
statement, like this:
Call MyProc(argument)
MyProc argument
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.
• If...Then...Else statement - use this statement if you want to select one of two sets of lines to
execute
• Select Case statement - use this statement if you want to select one of many sets of lines to
execute
If....then.....else
You should use the IF statement if you want to execute some code if a condition is true, or if you want to
select one of two blocks of code to execute.
If you want to execute only one statement when a condition is true, use this syntax for the if...then...else
statement, like this:
Notice that there is no ..else.. in this syntax. You just tell the code to perform one action if the condition (i)
is equal to some value (in this case the value is 10).
If you want to execute more than one statement when a condition is true, use this syntax for the
if...then...else statement, like this:
If i = 10 Then
msgbox "Hello"
i = 11
more statements
End If
There is no ..else.. in this syntax either. You just tell the code to perform multiple actions if the condition (i)
is equal to some value (in this case the value is 10).
If you want to execute some statements if a condition is true and execute others if a condition is false, use
this syntax for the if...then...else statement, like this:
If i = 10 Then
msgbox "Hello"
i = 11
Else
msgbox "Goodbye"
End If
The first block of code will be executed if the condition is true (if i is equal to 10), the other block will be
executed if the condition is false (if i is not equal to 10).
Select case
You should use the SELECT statement if you want to select one of many blocks of code to execute.
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.
Looping Statements
Very often when you write code, you want allow the same block of code to run a number of times. You can
use looping statements in your code to do this.
Do...Loop
You can use Do...Loop statements to run a block of code when you do not know how many repetitions you
want. The block of code are repeated while a condition is true or until a condition becomes true.
Do While i > 10
some code
Loop
Notice that if i is for example 9, the code inside the loop will never be executed.
Do
some code
Loop While i > 10
Notice that in this example the code inside this loop will be executed at least one time, even if i is less than
10.
Do Until i = 10
some code
Loop
Notice that if i is equal to 10, the code inside the loop will never be executed.
Do
some code
Loop Until i = 10
Notice that in this example the code inside this loop will be executed at least one time, even if i is equal to
10.
Exiting a Do...Loop
Do Until i = 10
i = i - 1
If i < 10 Then Exit Do
Loop
Notice that the code inside this loop will be executed as long i is different from 10, and as long as i is
greater than 10.
For...Next
You can use For...Next statements to run a block of code when you know how many repetitions you want.
You can use a counter variable that increases or decreases with each repetition of the loop, like this:
For i = 1 to 10
some code
Next
The For statement specifies the counter variable i and its start and end values. The Next statement
increases i by 1.
Using the Step keyword, you can increase or decrease the counter variable by the value you specify.
For i = 2 To 10 Step 2
some code
Next
In the example above, i is increased by 2 each time the loop repeats. When the loop is finished, total is the
sum of 2, 4, 6, 8, and 10.
To decrease the counter variable, you use a negative Step value. You must specify an end value that is
less than the start value.
For i = 10 To 2 Step -2
some code
Next
In the example above, i is decreased by 2 each time the loop repeats. When the loop is finished, total is the
sum of 10, 8, 6, 4, and 2.
Exiting a For...Next
You can exit a For...Next statement with the Exit For keyword.
For Each...Next
A For Each...Next loop repeats a block of code for each item in a collection, or for each element of an array.
The For Each...Next statement looks almost identical to the For...Next statement. The difference is that you
do not have to specify the number of items you want to loop through.
dim names(3)
names(0) = "Tove"
names(1) = "Jani"
names(2) = "Hege"