|
Hyper Text Mark-up
Language
JavaScript
The World Wide Web
began as a text only medium. The first version of HTML didn’t have the capacity
to include graphics on a page. Today’s web pages have the capacity to include
colours, images and sounds on it. Web scripting languages such as JavaScript is
one of the easiest ways of developing and spicing up your
the web page and to interact with users in many ways.
We can
use HTML tags for specifying the needed script since HTML is just a scripting
language. Since HTML is just a scripting Text Mark-up language, it cannot
respond to the user, make decisions, or automate repetitive tasks. Interactive
tasks like this require a more complex programming or scripting language. While
many programming languages are complex, scripting languages are generally
simple. They have simple syntax, with minimum commands.
JavaScript is an interpreted language. The browser executes each lines of the
script as it comes to it. Changes made in a JavaScript script are reflected in a
web browser as soon as you reload the page. Netscape Communications Corporation,
the makers of the popular browser, Netscape Navigator, developed JavaScript. It
was the first scripting language that was developed. It was initially known as
Live Script and was first introduced in Netscape Navigator 2.0 in 1995.
JAVA
Java is a
programming language developed by Sun Microsystems that can be used to create
applets or programs that execute within a web page. JAVA is a compiled language,
but the compiler produces a code for a virtual machine rather than a real
computer. The web browser then interprets this code. Although their names and
commands are the same, JAVA and JavaScript are two different languages. They are
both useful for different things. Infact, they can
be used together to combined their advantages.
Alternatives
to JavaScript
Sometimes known as
Visual Basic Scripting Edition, is Microsoft’s answer to JavaScript. Its syntax
is loosely based on MS-Visual Basic. It is closely integrated with ActiveX,
Microsoft’s standard web-embedded applications. It is only supported by
Microsoft Internet Explorer and not by Netscape Navigator.
-
CGI (Common Gateway Interface)
It is really not a language, but a
specification that allows programs to be run on web servers. CGI programs can be
written in various languages like C,
Perl,
MS-Visual Basic. CGI programs executes on the server.
ActiveX is a
specification developed by Microsoft that allows ordinary Windows programs to be
run on a web page. They can be written using languages like Visual C++ and
Visual Basic. The browser like Java applets executes ActiveX controls called
‘controls’.
Tools
for running JavaScript
The first thing that
you need to have is an editor. Any editor that can store ASCII text files will
be enough. A word processor can be used for scripting, but the file has to be
saved as ASCII text rather than a document file. Then, you will need a browser
to display the web page and at last but not the least, you require a PC to work
on.
Embedding
JavaScript into a HTML-page
The Script code can be embedded directly
into the HTML-page. The type of script that is used should be specified.
Example:
<html>
<body>
<br>
This is a normal
HTML document.
<br>
<script
language="JavaScript">
document.write("This
is Sample JavaScript!")
</script>
<br>
Back in HTML again.
</body>
</html>
Events
Events are mostly caused by user
actions. If the user clicks on a button a Click-event occurs. If the mouse
pointer moves across a link a Mouse Over-event occurs. There are several
different events. We want our JavaScript program to react to certain events.
This can be done with the help of event-handlers. A button might create a popup
window when clicked. This means the window should pop up as a reaction to a
Click-event. The event-handler needed to use is called
onClick. This tells the computer what to do if this event occurs.
Eg:-
<form>
<input
type="button" value="Click me" onClick="alert('Hello
There !!! ')">
</form>
Functions
Functions are used
in almost all Java script programs. Basically functions are a way for bundling
several commands together.
Eg
: 1
<html>
<script
language="JavaScript">
function
myFunction()
{
document.write("Welcome
to my homepage!<br>");
document.write("This
is a small sample function which is called!<br>");
}
myFunction();
myFunction();
myFunction();
</script>
</html>
Predefined objects
1.
The ‘Date’ object
This object lets
you work with time and date. For example it is possible to calculate how many
days are left until next Christmas or it is possible to add the actual time to
your HTML document.
Eg:-
today= new Date();
It creates a new Date-object called “today”.
If a certain date and time are not specified when creating a new Date-object,
the actual date and time is used. This means after executing today= new
Date(), the new Date-object today
represents the date and time of this specific moment.
The Date-object offers some
methods, which can now be used with object today. Some examples are
getHours(),
setHours(),
getMinutes(), setMinutes(),
getMonth(),
setMonth(), etc……
In order to get another date and time,
use another constructor (Here, the Date() method
is called through the “new” operator when constructing a new Date-object):
today=
new Date(1997, 0, 1, 17, 35, 23);
This will create a Date-object which
represents the first of January 1997 at 17:35 and 23 seconds.
Date(year,
month, day, hours, minutes, seconds)
Script which
outputs the actual date and time
<script language="JavaScript">
<!--
hide
now=
new Date();
document.write("Time:
" + now.getHours() + ":" +
now.getMinutes() + "<br>");
document.write("Date:
" + (now.getMonth() + 1) + "/" +
now.getDate() + "/" + (1900 +
now.getYear()));
// -->
</script>
Result:
Time: 17:53
Date: 4/3/2010
Script which displays a working clock:
<html>
<head>
<script Language="JavaScript">
var
timeStr, dateStr;
function
clock()
{
now=
new Date();
// time
hours=
now.getHours();
minutes=
now.getMinutes();
seconds=
now.getSeconds();
timeStr= "" + hours;
timeStr+= ((minutes < 10) ? ":0"
: ":") + minutes;
timeStr+= ((seconds < 10) ? ":0"
: ":") + seconds;
time.value
= timeStr;
// date
date=
now.getDate();
month=
now.getMonth()+1;
year=
now.getYear();
dateStr= "" + month;
dateStr+= ((date < 10) ? "/0"
: "/") + date;
dateStr+= "/" + year;
date.value
= dateStr;
Timer=
setTimeout("clock()",1000);
}
</script>
</head>
<body onLoad="clock()">
Time: <input type="text" name="time"
size="8" value=""><br>
Date: <input type="text" name="date"
size="8" value="">
</body>
</html>
setTimeout()
method is used for setting the time and date every second. So, we create every
second a new Date-object with the actual time. You can see that the function
clock() is called with the
onLoad event-handler in the <body>
tag. In the body-part of our HTML-page we have two text-elements. The function
clock() writes the time and date into
these two text boxes in the right format. You can see that we are using two
strings timeStr and
dateStr for this purpose.
We have
mentioned earlier that there is a problem with minutes less than 10 - this
script solves this problem through this line of code:
timeStr+=
((minutes < 10) ? ":0" : ":") + minutes;
Here, the
number of minutes is added to the string timeStr.
If the minutes are less than 10 we have to add a 0. You could also write it like
this, which might look more familiar:
if
(minutes < 10) timeStr+= ":0" + minutes
else timeStr+= ":" +
minutes;
2.
The ‘Array’ object
Just think of
an example where you want to store 100 different names. You can define 100
variables and assign the different names to them. This is quite complicated.
Arrays are the variables that can hold more than one value at the same time
under a single name. Since JavaScript 1.1 (Netscape Navigator 3.0), you can use
the Array-object.
You can
create a new array through myArray = new
Array( ), where “myArray”
is the arrayname.
myArray[0]=
17;
myArray[1]=
"ALLAN";
myArray[2]=
"LONDON";
JavaScript arrays are really flexible.
You do not have to bother about the size of the array - its size is being set
dynamically. If you write myArray[99]="xyz"
the size of the array get 100 elements (a JavaScript array can only grow - it
hasn't got the ability to shrink. So keep your arrays as small as possible.). It
doesn't matter if you store numbers, strings or other objects in an array.
Example for the source code for an
array:
<script language="JavaScript">
myArray=
new Array();
myArray[0]=
"first element";
myArray[1]=
"second element";
myArray[2]=
"third element";
for
(var i= 0;
i< 3; i++)
{
document.write(myArray[i]
+ "<br>");
}
</script>
The
output of the following example is:
first
element
second
element
third
element
The variable,
i
counts from 0 to 2 with this “for-loop”. You can see
that we are using myArray[i]
inside the “for-loop”. As
i
counts from 0 to 2 we get three
document.write()
calls. We could rewrite the loop as:
document.write(myArray[0]
+ "<br>");
document.write(myArray[1]
+ "<br>");
document.write(myArray[2]
+ "<br>");
3.
The Math-object
If we need to
do mathematical calculations we can find some methods in the Math-object which
might help us further. We can find a complete reference in the Netscape
documentation. There have been some problems with the
random() method. If we call
Math.random(),
we will receive a random number between 0 and 1. The MATH object provides a
standard library of mathematical constants and functions.
|
Method |
Description |
|
abs (A) |
Returns the absolute value of ‘A’ |
|
max (X,Y) |
Returns the maximum value of X and Y |
|
min (X,Y) |
Returns the minimum value of X and Y |
|
random ( ) |
Returns numbers between 0 and 1 |
|
pow
(X,Y ) |
Returns the value of X raise to Y |
|
log (A) |
Returns the natural logarithm of ‘A’ |
|
sqrt
(A) |
Returns the square root value of ‘A’ |
|
round ( ) |
Returns the closest integer to ‘A’ |
|
sin (A)
/
cos (A)
/
tan (A) |
Returns the value of Sine, Cosine or
Tangent of ‘A’ |
|
ceil (A) |
Returns the lowest integer that is
greater than or equal to ‘A’ |
|
floor (A) |
Returns the greatest integer that is
lesser than or equal to ‘A’ |
PI ( )
It is a property that returns the value
of the constant, “PIE”.
4.
String Object
Strings store a group
of text characters. JavaScript stores strings as
string objects.
There are two ways of creating string objects,
.
Test =
“My name is Chandramohan”;
.
Test =
new String (“My name is Chandramohan”);
There are some methods
that can be used along with the string objects are,
§
length =
To calculate the length of a string.
(Eg:
msg.length)
§
toUpperCase
( ) = To convert all characters in the string to uppercase.
(Eg:
document.write(test.toUpperCase(
)) )
§
toLowerCase
( ) = To convert all characters in the string to lowercase.
(Eg:
document.write(test.toLowerCase(
)) )
§
substring
( ) = To retrieve a portion of a string between two index values. (Eg:
document.write(test.substr(3,6))
)
§
charAt(
) = It is used to grab a single character, anywhere from a string.
(Eg: alpha.charAt(5)
§
indexOf(
) = It is used to find a string within another string.
(Eg:
emailaddress.indexOf(“@”) )
An optional character
can be specified along with this method to indicate the position to begin the
search.
(Eg:
loc = myname.indexOf(“C”,
5) )
Another method,
lastindexOf(
) finds the last occurrence of the string. It searches the string backwards
starting from the last character.
(Eg:
loc = myname.lastindexOf(“C”,
5) )
5.
Location Object
Besides the window- and document-objects
there is another important object: the location-object. So, if you need to load
the page, http://www.yahoo.com/index.html, then specify the value of
location.href as this address. We can assign
new values to location.href, as and when
necessary.
This button, for example loads the
specified page into the actual window:
<form>
<input type=button value="Click here to
Yahoo..........."
onClick="location.href='http://www.yahoo.com';
">
</form>
6.
Window Object
Creating
windows
Script for opening new browser window
when user clicks a button.
<html>
<script language="JavaScript">
function
openWin()
{
myWin= open("index.htm");
}
</script>
<body>
<form>
<input type="button" value="Open new
window" onClick="openWin()">
</form>
</body>
</html>
List of the properties of a window:
|
directories |
yes|no |
|
height |
Number of
pixels |
|
location |
yes|no |
|
menubar |
yes|no |
|
resizable |
yes|no |
|
scrollbars |
yes|no |
|
status |
yes|no |
|
toolbar |
yes|no |
|
width |
Number of
pixels |
|
alwaysLowered |
yes|no |
|
alwaysRaised |
yes|no |
|
dependent |
yes|no |
|
hotkeys |
yes|no |
|
innerWidth |
Number of
pixels (replaces width) |
|
innerHeight |
number of
pixels (replaces
height) |
|
outerWidth |
number of
pixels |
|
outerHeight |
number of
pixels |
|
screenX |
position
in pixels |
|
screenY |
position in
pixels |
|
titlebar |
yes|no |
|
z-lock |
yes|no |
Opening
2 html files in the same window
Script to open 2 html files in the same
window using the name of that window.
<html>
<script language="JavaScript">
function
openWin2()
{
myWin=open("index.htm","displayWindow","width=400,height=300,status=yes,
toolbar=no,menubar=no");
}
</script>
<body>
<form>
<input type="button" value="Open new
window" onClick="openWin2()">
</form>
<a href="maveli.htm"
target="displayWindow">click here</a>
</body>
</html>
Writing message on
status bar
<html>
<script language="JavaScript">
function
statbar(txt)
{
window.status
= txt;
}
</script>
<body>
<form>
<input type="button" name="look"
value="Click here for the status bar message"
onClick="statbar('Hello
!!! this is a tesing message');">
<input type="button" name="erase"
value="removemesssage" onClick="statbar('');">
</form>
</body>
</html>
Displaying
text on the status bar can easily be used in combination with links. Instead of
showing the URL of the link the status bar shows the specified message.
The code is:
<a href="dontclck.htm"
onMouseOver="window.status='Don\'t
click me!'; return true;"
onMouseOut="window.status='';">link</a>
Moving
text string in a status bar - Scroller
Example :
<html>
<head>
<script language="JavaScript">
<!--
hide
//
define the text of the scroller
var
scrtxt = "This is JavaScript! " +
"This is JavaScript!
" +
"This is JavaScript!";
var
length = scrtxt.length;
var
width = 100;
var
pos = -(width + 2);
function
scroll() {
// display the text at the right position and set a timeout
// move the position one step further
pos++;
// calculate the text which shall be displayed
var scroller = "";
if (pos ==
length) {
pos =
-(width + 2);
}
// if the text hasn't reached the left
side yet we have to
// add some spaces - otherwise we have
to cut of the first
// part of the text (which moved
already across the left border
if (pos <
0) {
for (var
i = 1; i <=
Math.abs(pos); i++) {
scroller = scroller
+ " ";}
scroller = scroller
+ scrtxt.substring(0, width - i
+ 1);
}
else {
scroller = scroller
+ scrtxt.substring(pos, width + pos);
}
// assign the text to the statusbar
window.status
= scroller;
// call this function again after 100
milliseconds
setTimeout("scroll()",
100);
}
// -->
</script>
</head>
<body onLoad="scroll()">
Your HTML-page goes here.
</body>
</html>
The
main part of the scroll() function is
needed for calculating which part of the text is being displayed. In order to
start the scroller use the
onLoad event-handler of the <body> tag. This means the function
scroll() will be called right after the
HTML-page has been loaded. scroll()
function is called with the onLoad property.
The first step of the scroller is being calculated
and displayed. At the end of the scroll()
function timeout is set. This causes the scroll()
function to be executed again after 100 milliseconds. The text is moved one step
forward and another timeout is set which goes on for ever.
Forms
Validating
form input
Forms are widely used on the Internet.
The form input is often being sent back to the server or via mail to a certain
e-mail account. With the help of JavaScript the form input can easily be checked
before sending it over the Internet.
In this example the HTML-page shall
contain two text-elements. The user has to write his name into the first and an
e-mail address into the second element otherwise a message is displayed.
<html>
<head>
<script language="JavaScript">
<!--
Hide
function
test1(form) {
if
(form.text1.value == "")
alert("Please
enter a string!")
else {
alert("Hi
"+form.text1.value+"! Form input ok!");
}
}
function
test2(form) {
if
(form.text2.value == "" ||
form.text2.value.indexOf('@', 0) == -1)
alert("No
valid e-mail address!");
else
alert("OK!");
}
</script>
<body>
<form name="first">
Enter your name:<br>
<input type="text" name="text1">
<input type="button" name="button1"
value="Test Input" onClick="test1(this.form)">
<P>
Enter your e-mail
address:<br>
<input type="text" name="text2">
<input type="button" name="button2"
value="Test Input" onClick="test2(this.form)">
</body>
</html>
Submitting
form input via e-mail
<form
method=post action="mailto:your.address@goes.here"
enctype="text/plain">
Do you like this page?
<input name="choice" type="radio"
value="1">Not at all.<br>
<input name="choice" type="radio"
value="2" CHECKED>Waste of time.<br>
<input name="choice" type="radio"
value="3">Worst site of the Net.<br>
<input name="submit" type="submit"
value="Send">
</form>
The
property enctype="text/plain" is used
in order to send plain text without encoded parts. To validate the form before
it is sent over the net use the onSubmit
event-handler by putting this event-handler into the <form> tag.
Eg:
function
validate() {
// check if input ok
// ...
if (inputOK)
return true
else
return false;
}
...
<form ... onSubmit="return
validate()">
DHTML
concepts
Style
sheets in HTML
HTML is used to design a web-page. It
doesn’t give the user very much control over a page’s appearance. For example,
one can’t change the number of spaces between words because they get converted
into a single space. It may not be displayed the same on each computer or
browsers. For this, the web developers went for Cascading Style Sheets
(CSS).
CSS adds a number of features to a standard HTML page. With style sheets, one
can make a document 100% identical on all the browsers and platforms.
The main HTML tag that one will have to use while working
with a style sheet is “<STYLE> </STYLE>”. These tags have to be placed in
between the “<HEAD> </HEAD>” tags.
Each line within
the <STYLE> </STYLE> tags is known as a rule.
Eg:
<STYLE type=“text/css”>
B {e=“color:red;font-size:14”}
</STYLE>
Eg:
<STYLE type=“text/css”>
H1, H2, H3 {color:blue;font-style:italic}
</STYLE>
One of the major
useful features of style sheets is that one can easily change the spacing and
alignment of text, by using following properties.
-
letter-spacing
: specifies the spacing between the letters (MS-IE 4.0 only).
-
text-decoration
: allows to create lines over, under, through the text or even to
make the text blink.
-
vertical-align
: to move the item up or down along with other items on the same
line (MS-IE 4.0 only).
-
text-align
: specifies the alignment of the text (center,
left, right, justify).
-
text-transform
: changes all the characters in a text into the specified case
(capitalize, uppercase, lowercase).
-
text-indent
: specifies the amount of indentation for paragraphs and other
elements.
-
line-height
: specifies the distance between the previous line and the text
following it.
One can also use
style sheets to gain more control over colours and images used in the web pages.
-
color
: specifies the writing color for an
element.
-
background-color
: specifies the background colour for the element.
-
background-image
: specifies the background image for the element.
-
background-repeat
: specifies whether the background image is repeated horizontally,
vertically or both (MS-IE 4.0 only).
-
background-attatchment
: specifies if the background image scrolls or not, when the
document is scrolled. Its value can either be “fixed” or “scroll”
(MS-IE 4.0 only).
-
background
: one can specify all the attributes in a single background rule.
Style sheets also allow one to control
the fonts used on a web page.
·
font-family
: specifies the name of the font.
·
font-style : specifies the style of
the font(normal, italic,
oblique)
·
font-size
: specifies the size of the font.
One can also use style sheets to control
the general layout of a web page.
·
margin-top
margin-left
: specifies the margins on the element.
margin-right
margin-bottom
·
weight
: specifies the width of an element.
·
height
: specifies the height of an element.
·
float
: allows the text to flow around an element.
Using JavaScript Style
Sheets
(JSS)
Netscape supports an alternate style
sheet syntax called JavaScript Style Sheets (JSS). This type of style sheets
are not supported by MS-Internet Explorer. They use JavaScript based syntax for
defining various styles. JSS style sheets begin with the following tag.
<STYLE TYPE=“text/javascript”>
---------------------
---------------------
</STYLE>
Netscape supports
three basic objects,
·
tags,
that include all basic HTML tags.
·
classes,
that include the classes the user defines.
·
ids,
that include ID codes for individual elements.
All these are
children of the “document” object.
HOME
<<PREVIOUS |