AIP Chapter Four
AIP Chapter Four
AIP Chapter Four
JAVASCRIPT
1
JAVASCRIPT
What is JavaScript?
JavaScript: the first Web scripting language, developed by
Netscape in 1995 which is syntactically similar to Java/C+
+,
but simpler & more flexible
2
CLIENT-SIDE PROGRAMMING
JavaScriptprograms are embedded within HTML
documents in source code form which is
interpreted by the browser.
Platform independence
Recall:
HTML is good for developing static pages
can specify text/image layout, presentation, links and
specifying the same look for different pages.
In order to develop interactive/reactive pages, we
must integrate different programming
3
CONT…
client-side programming:
programs can be written in a separate programming language
E.g., JavaScript, VBScript
programs are embedded in the HTML of a Web page, with
tags to identify the program component
e.g., <script type="text/javascript">
…
</script>
the browser executes the program as it loads the page,
integrating the dynamic output of the program with the
static content of HTML
4
COMMON SCRIPTING TASKS
JavaScript can perform the following task:
Decision making (switch and if statements)
Used in input data validation
Submitting forms(document.forms["myform"].submit();)
Performing complex mathematical calculations.
Adding dynamic features to Web pages
Image rollovers
Time-sensitive or random page elements
utilize
buttons, text boxes, clickable images, prompts, frames
Can Change HTML Content
Can Change the value of HTML Attributes
Can Change HTML styles for a given element 5
JAVASCRIPT AND JAVA
Although the names resemble quite closely, they are
different languages.
Some facts:
7
// Java script code inside the head part of our code
<head>
<script>
function myFunction() {
---
}</script>
</head>
/ * Javascript code inside the body part of our html code */
<body>
<script>
function myFunction() {
----
}</script></body>
// starts a single line comment
/*…*/ enclose multi-line comments 8
EXTERNAL JAVASCRIPT
9
Advantages External Script:
10
11
JavaScript Function and events
JavaScript function is a block of JavaScript code, that can be
12
Writing into the HTML output using document.write()
<script>
document.write(5 + 6);
</script>
Writing into an HTML element, using innerHTML
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =“Hello
Javascript”;
</script>
13
EXAMPLE
<html>
<head>
<title>JavaScript Page</title>
</head>
<body>
<script type="text/javascript">
document.write("Hello world!");
document.write("<p>How are <br />"
+"<i>you</i>?</p>");
</script>
<p>Here is some static text as well.
</p></body>
</html>
14
JAVASCRIPT SYNTAX
JavaScript syntax is the rules, how JavaScript programs are
constructed.
JavaScript statements are separated by semicolon:
17
JAVASCRIPT STATEMENTS
In HTML, JavaScript statements are "instructions" to be
"executed" by the web browser.
Example
document.getElementById("demo").innerHTML = "Hello
John.";
This statement tells the browser to write "Hello John."
inside an HTML element with id="demo":
Statements are executed, one by one, in the same order as they
are written.
Example var x = 5;
var y = 6;
var z = x + y;
document.getElementById("demo").innerHTML = z; 18
In this example, x, y, and z is given values, and finally z is
displayed:
JavaScript statements are separated by semicolon
E.g var a = 5;
var b = 6;
You can declare many variables in one statement-start the
statement with var and separate the variables by comma:
E.g
var person = "John Doe", carName = "Volvo;
JavaScript ignores multiple spaces. You can add white space to
your script to make it more readable.
19
JAVASCRIPT VARIABLES
var x = 5;
var y = 6;
var z = x + y;/* In this example, x, y, and z, are variables */
All JavaScript variables must be identified with unique
names called identifiers.
Identifiers can be short names (like x and y), or more
descriptive names (age, sum, totalmark).
20
The general rules for constructing names for variables (unique
identifiers) are:
Names can contain letters, digits, underscores, and dollar signs.
21
JAVASCRIPT DATA TYPES
In programming, data types is an important concept.
To be able to operate on variables, it is important to know
something about the type.
Without data types, a computer cannot safely solve this: var x
= 16 + "Volvo"
Does it make any sense to add "Volvo" to sixteen? Will
produce an error or a result?
JavaScript has three primitive data types
strings : "foo" 'howdy do' "I said 'hi'." ""
numbers : 12 3.14159 1.5E6
booleans : true false
JavaScript variables can hold numbers like 100, and text values
like “Hello JS". 22
In programming, text values are called text strings.
Strings are written inside double or single quotes.
E.g
var carName = "Volvo XC60"; // Using double quotes
var carName = 'Volvo XC60'; // Using single quotes
You can use quotes inside a string, as long as they don't match
the quotes surrounding the string:
var answer = "It's alright"; // Single quote inside double quotes
var answer = "He is called 'Johnny'"; // Single quotes inside
double quotes
var answer = 'He is called "Johnny "'; // Double quotes inside
single quotes
23
JavaScript has only one type of numbers which can be written with, or
without decimals:
Example
var cars = ["Saab", "Volvo", "BMW"];
Arrays use numbers to access its elements.
document.write(person.firstName);//return John
26
In JavaScript we can use the JavaScript typeof
operator to find the type of a JavaScript variable:
Example
Example
27
JAVASCRIPT FUNCTION
A JavaScript function is a block of code designed to perform
a particular task.
A JavaScript function is defined with the function keyword,
followed by a name, followed by parentheses ().
Example
function myFunction(p1, p2) {
return p1 * p2; // the function returns the product of p1 and p2
}
A JavaScript function is executed when "something" invokes
it (calls it).
28
Function names can contain letters, digits, underscores, and
dollar signs (same rules as variables).
The parentheses may include parameter names separated by
commas: (parameter1, parameter2, ...)
The code to be executed, by the function, is placed inside
curly brackets: {}
functionName(parameter1, parameter2, parameter3)
{
code to be executed
}
29
JAVASCRIPT TERMINOLOGY
30
OBJECTS
Objects refers to windows, documents, images, tables,
forms, buttons or links, etc.
31
PROPERTIES
Properties are object attributes.
Object properties are defined by using the object's name,
a period, and the property name.
e.g.,background color is expressed by: document.bgColor
= “lightblue";
document is the object.
bgcolor is the property.
32
METHODS
Methods are actions applied to particular objects.
Methods are what objects can do.
e.g., document.write(”Hello World")
document is the object.
write is the method.
33
DOCUMENT.WRITE(“STRING”)
<HTML>
<HEAD><TITLE>Hello!</TITLE></HEAD>
<BODY>
<H1> First JavaScript Page </H1>
<SCRIPT TYPE="text/javascript">
document.write("<HR/>");
document.write("Hello WWW!");
document.write("<HR/>");
document.bgColor = “lightblue";
</SCRIPT>
</BODY>
</HTML>
34
EVENTS
Events associate an object with an action.
e.g., the OnMouseover event handler action can change an
image.
e.g., the onSubmit event handler sends a form.
onClick
35
EVENTS…
JavaScript defines various events:
onClick – when a link or image is clicked
onSubmit -a form is submitted
onMouseOver -the mouse cursor moves over it
onChange-when the content of a form element, the
selection, or the checked state have changed.
onLoad -something gets loaded in the browser
etc.
Events are specified in the HTML code.
36
EVENT EXAMPLE
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Click me</button>
<p id="demo"></p>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Hello World";
}
</script>
</body>
</html>
37
FUNCTIONS
39
VARIABLES
40
EXPRESSIONS
41
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.
The message is specified within parenthesis.
Syntax: alert("sometext");
The following script in the <body> tag uses the
onLoad event to display an Alert window
42
EXAMPLE
<html>
<head>
<script type="text/javascript">
function show_alert()
{
alert("I am an alert box!");
}
</script>
</head>
<body onload="show_alert()" value="Show alert box">
</body>
</html>
43
PROMPT BOX
• A prompt box is often used if you want the user to input a
value.
• 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(“message text","defaultvalue");
1st argument: the prompt message that appears in the dialog
box
2nd argument: a default value that will appear in the box (in
case the user enters nothing)
44
EXAMPLE 1
<html><head>
<script type="text/javascript">
<!--
function prompter() {
var reply = prompt("Hey there, good looking stranger! What's your
name?", "")
alert ( "Nice to see you around these parts " + reply + "!")
}
//-->
</script>
</head>
<body>
<input type="button" onclick="prompter()" value="Say my
name!">
</body> </html> 45
EXAMPLE 2
<html> <head>
<title>Interactive page</title>
</head> <body>
<script type="text/javascript">
userName = prompt("What is your name?", "");
userAge = prompt("Your age?", "");
userAge = parseFloat(userAge);
document.write("Hello " + userName + ".")
if (userAge < 18) {
document.write(" Do your parents know " + "you are
online?");
}
</script>
<p>The rest of the page...
</body> </html> 46
JAVASCRIPT CONFIRM BOX
47
EXAMPLE
<html> <head>
<script type="text/javascript">
function show_confirm()
{
var r=confirm("Press a button");
if (r==true)
{
alert("You pressed OK!");
}
else
{
alert("You pressed Cancel!");
}
}
</script>
</head> <body>
<input type="button" onclick="show_confirm()" value="Show
confirm box" />
48
</body> </html>
JAVASCRIPT FUNCTIONS
JavaScript function is a block of code (group of statements)
designed to perform a particular task.
A JavaScript function is defined with the function keyword,
followed by a name, followed by parentheses ()
function function_name(parameters)
{
JavaScript commands
}
parameters are the values sent to the function (note: not all
functions require parameters)
{ and } are used to mark the beginning and end of the
commands in the function. 49
CREATING JAVASCRIPT FUNCTIONS
Function names are case-sensitive.
Function names can contain letters, digits, underscores,
and dollar signs.
The function name must begin with a letter or underscore
( _ ) and cannot contain any spaces.
There is no limit to the number of function parameters that
a function may contain.
The parentheses may include parameter names separated
by commas: (parameter1, parameter2, ...)
The code to be executed, by the function, is placed inside
curly brackets: {}
Function arguments are the real values received by the
function when it is invoked 50
PERFORMING AN ACTION WITH A FUNCTION
Function Definition
function ShowDate(date) {
document.write(“Today is” + date + “<br>”);
}
Function Call
The code inside the function will execute when
"something" invokes the function:
When an event occurs (when a user clicks a button), called from
JavaScript code or self-invoking.
If a function is called with missing arguments (less than
declared), the missing values are set to: undefined.
var Today = date(); // Variable declaraion
ShowDate(Today); // function call with arguments 51
FUNCTION RETURN
When JavaScript reaches a return statement, the function will stop
executing
The return value of a function is "returned" back to the "caller":
E.g
function Area(Width, Length)
{
var Size = Width*Length; // calculate the area and assigned it size
return Size; // return the result to its caller statement
}
var area= Area (4, 3); // function is called, return value will end up in
area
52
PLACING A FUNCTION IN AN HTML FILE
The function definition must be placed before the
command that calls the function.
One convention is to place all of the function definitions
in the <head> section.
A function is executed only when called by another
JavaScript command.
53
WORKING WITH CONDITIONAL STATEMENTS
Comparison, Logical and Conditional Operators
54
AN EXAMPLE OF BOOLEAN EXPRESSIONS
x < 100;
if x is less than 100, this expression returns the value
true; however, if x is 100 or greater, the expression is
false
y == 20;
55
COMPARISON OPERATORS
Operator Description
== Returns true if variable are equal (x==y)
> Return true of the value on the left is greater than the right
one(x>y)
< Return true if the variable on the left is less than the right
one(x<y)
>= Return true if the variable on the left is greater than or
equal to the right one(x>=y)
<= Return true if the variable on the left is less than or equal to
the right one (x<=y)
56
A LOGICAL OPERATOR
The logical operator && returns a value of true only if all
of the Boolean expressions are true.
Operator Description Examples
Let the value of x=20 and y=25
&& Return true when both (x==20) && (y==25) returns true
expressions are true (x==20 && y==20) returns false
58
WORKING WITH CONDITIONAL STATEMENTS
Conditional statements are used to perform different
actions based on different conditions.
JavaScript has the following conditional statements
68
THE FOR LOOP
The For loop allows you to create a group of commands to be
executed a number of times through the use of a counter that tracks
the number of times the command block has been run.
Syntax:
for (start; condition; update)
{
JavaScript Commands
}
start is the starting value of the counter
condition is a Boolean expression that must be true for the loop to
continue
update specifies how the counter changes in value each time the
command block is executed
Set an initial value for the counter, and each time the command block
is executed, the counter changes in value.
When the counter reaches a value above or below a certain stopping
value, the loop ends. 69
EXAMPLE
<html>
<body>
<script type="text/javascript">
for (i = 1; i <= 6; i++)
{
document.write("<h" + i + ">This is heading " + i);
document.write("</h" + i + ">");
}
</script>
</body>
</html> 70
EXAMPLE 2
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var cars = ["BMW", "Volvo", "Saab", "Ford"];
text = "";
for (var i = 0; i < cars.length; i++) {
text += cars[i] + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>
</body> 71
</html>
EXAMPLE 3
<html>
<body>
<table border="1px">
<tr>
<script>
for(var num=1; num<=5; num++){
document.write("<td>"+ num +"</td>");
}
</script>
</tr>
</table>
</body>
72
</html>
NESTED FOR EXAMPLE
<html>
<body><table border="1px"><tr>
<script>
var rownum, colnum;
for(rownum=1; rownum<=3; rownum++){
document.write("<tr>");
for(colnum=1; colnum<=4; colnum++){
document.write("<td>"+ rownum + "," + colnum +"</td>");
}
document.write("</tr>");
}
</script></tr></table></body>
73
</html>
FOR IN LOOP
for/in - loops through the properties of an object
E.g
<html>
<body><p id="demo"></p>
<script>
var txt = ""; var x;
var person = {fname:“Sam", lname:“Abebe", age:25};
for (x in person) {
txt += person[x] + " ";
}
document.getElementById("demo").innerHTML = txt;
</script> 74
</body> </html>
THE WHILE LOOP
The While loop runs a command group as long as a specific
condition is met, but it does not employ any counters.
Loops through a block of code a specified number of times or
while a specified condition is true.
The general syntax of the While loop is:
while (condition)
{
JavaScript Commands
}
condition is a Boolean expression that can be either true or
false
75
EXAMPLE
<html>
<body>
<table border="1px">
<tr>
<script>
var num=1;
while(num<=5){
document.write("<td>"+ num +"</td>");
num++;
}
</script></tr>
</table></body>
76
</html>
EXAMPLE 2
<html>
<body>
<table border="1px"> <tr><script>
var rownum=1, colnum=1;
while(rownum<=3) {
document.write("<tr>");
while(colnum<=4){
document.write("<td>"+ rownum + "," + colnum +"</td>");
colnum++;
}
document.write("</tr>");
rownum++; colnum=1; 77
}</script></tr></table></body></html>
USING ARRAYS
JavaScript arrays are used to store multiple values in a single
variable(an ordered collection of values referenced by a single
variable name).
Syntax:
Using the JavaScript new keyword
</body></html>
ARRAY DECLARATION AND ASSIGNMENT WITHIN ONE
LINE
<body><script>
var MonthTxt=[ "January", "February", "March", "April",
"May","June", "July", "August", "September", "October",
"November", "December“];
document.write("<h3>"+" Months of the year are:"+"</h3>");
document.write("<ul>");
for (var i = 0; i < MonthTxt.length; i++) {
document.write("<li>"+MonthTxt[i] + "</li>");
}
document.write("</ul>");
</script>
</body> 80
// we can use array() or array[] in array declaration and assignment
JAVASCRIPT OBJECTS AND METHODS
In the context of JavaScript:
◦ An object is a collection of properties and methods which can be
viewed, modified and interacted with.
A simple example of property is color, which is rather easy to
visualize.
They can be directly manipulated by referring to the object and the
document.bgColor = “lightblue”;
document.fgColor = “green”;
In the object-oriented paradigm, methods refer to functions that can be
used to manipulate objects and their properties.
Example:
The method write(), which when invoked on the document object, causes a
specific string of characters to be outputted.
document.write (“Hello Good Day”);
window.alert(“This is an alert!!”); 81
CONT…
Methods which are defined on an object give the range of choices
available for interacting with the object.
Some examples:
A window object can be opened or closed using the open() and close()
methods respectively.
A form object has a submit() method which transmits the contents of
the form to the web server.
The sequential list of a user’s path through a number of URLs is
represented by the history object, which has forward() and
backward() methods to move through the list.
Apart from the pre-defined methods, it is also possible to create
user-defined methods.
◦ Control the rate with which a line of text scrolls across the screen.
◦ Determine the path of an animated object across the display.
82
DATA VALIDATION
JavaScript can be used for client-side validation of data
entered in HTML forms.
Dataentered can be extracted and accessed.
Checks can be made on the data entered.
Non-alphabetic characters in name.
Non-numeric characters in roll number, age, etc.
side application.
83
EXAMPLE
<html><head>
<script type="text/javascript">
function validate(){
if( document.myForm.fName.value == "" ){
alert( "Please provide your First name!" );
document.myForm.fName.focus() ;
return false;}
if( document.myForm.lName.value == "" ){
alert( "Please provide your Last name!" );
document.myForm.lName.focus() ;
return false; }
if( document.myForm.email.value == "" ) {
alert( "Please provide your Email!" );
document.myForm.email.focus() ;
return false;} 84
return(true);} </script> </head>
<body>
<H3> Student Registration Form </H3>
<form action="registration.php" name="myForm"
onsubmit="return(validate());">
<p>First Name:<input type="text" name="fName" /></p>
<p>Father Name:<input type="text" name="lName" /></p>
<p>Email Address:<input type="text" name="email" /></p>
<p>Phone Number:<input type="text" name="phone"/></p>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
</form>
</body> 85
</html>
SIMPLE ANIMATION
JavaScript provides following two functions to be frequently
used in animation programs.
setTimeout(function,duration,param1,param2,..)
Schedules a piece of Javascript code to run at some specified time
in the future.
Time specified in milliseconds.
operations.
setInterval(function,duration,param1,param2,..)
This function calls a function after every duration of milliseconds.
clearTimeout(setTimeout_variable) - This function call clears
any timer set by the setTimeout() functions.
86
EXAMPLE
<script type="text/javascript">
var imgObj = null;
function init(){
imgObj = document.getElementById('myImage');
imgObj.style.position= 'relative';
imgObj.style.left = '0px';
}
function moveRight(){
imgObj.style.left = parseInt(imgObj.style.left) + 10 + 'px';
}
window.onload =init;
</script> 87
</head>
<body onload="setInterval(moveRight,200);">
<form>
<img id="myImage" src="1.gif" width="100"
height="100"/>
</form>
</body>
</html>
88
EXAMPLE
<html><head>
<script type="text/javascript">
function mouseOver(){
document.getElementById("btn1").src ="button_blue.gif";
}
function mouseOut(){
document.getElementById("btn1").src ="button_pink.gif";
}</script>
</head>
<body>
<a href="www.mau.edu.et" target="_blank">
<img border="0" alt="Mekdela Amba University" src="b_pink.gif" id="btn1"
width="26" height="26" onmouseover="mouseOver()"
onmouseout="mouseOut()" /></a>
89
</body></html>
HISTORY BACK / FORWARD
Contains the URLs visited by the user (within a browser window).
Uses the back() and forward() methods to scroll through the
recently visited pages.
history.back()- same as clicking back in the browser
history.forward() - same as clicking forward in the browser
E.g Index.html
<html>
<body>
<h1>Index page</h1>
<br/>
<a href="news.html">News</a>
</body>
</html> 90
News.html
<html>
<body>
<h1>News page</h1>
<a href="newsdetail.html">News Detail</a>
<br/>
<br/>
<button onclick="window.history.back()">Go Back
</button>
<button onclick="window.history.forward()"> Go
forward</button>
</body>
</html> 91
Newsdetail.html
<html>
<body>
<h1>News Detail page</h1>
<br/>
<button onclick="window.history.back()">Go
Back</button>
</body>
</html>
Once you are on the news page, you can go back to the
index page by using window.history.back and to the news
detail page by using windwo.history.forward method
92
BROWSER DETECTION
This feature allows one to find out what type of browser
is being used.
There are two objects used for this:
navigator.appName : returns the name of the browser.
navigator.appVersion : returns the version of the browser.
93
EXAMPLE: BROWSER DETECTION
<html><head>
</head>
<body>
<script type="text/javascript">
var browserName = navigator.appName;
var browserVersion = navigator.appVersion;
if (browserName=="Netscape")
alert("Hi Netscape User!" + browserVersion);
else
if (browserName=="Microsoft Internet Explorer")
alert("Hi, Explorer User!" + browserVersion);
else
alert("Unrecognized browser!");
</SCRIPT>
</body>
</html> 94
PAGE REDIRECTION
An example follows.
Will take us to a page after 5 seconds.
Example
<script>
function getgoing (){
window.location = "http://www.mau.edu.et";
}
alert( "You will be redirected in five seconds."); 95
setTimeout ('getgoing()', 5000); </script >
CREATING NEW BROWSER WINDOW
To open a new window, we need to call the window.open()
method.
window.open (‘url to open’, ‘window name’, attribute1,
attribute2, …);
Window attributes:
width = 300
height = 200
resizable = yes or no
scrollbars = yes or no
toolbars = yes or no
status = yes or no
menubar = yes or no
copyhistory = yes or no
98
• JavaScript supports the following built-in language objects:
• The String object
• The Array object
• The Date object
• The Math object
• e.t.c
String Object
• The String Object
• The string object used to manipulate a stored piece of text.
• Can be created by assigning a string value to a variable or a property.
• Syntax: var x=new String(string here);
e.g var y = new String("John");)
• JavaScript’s string and character are appropriate for processing names,
addresses, credit card information, etc.
Characters
Fundamental building blocks of JavaScript strings
String
Series of characters treated as a single unit 99
Method Description
METHODS OF THE STRING OBJECT
charAt(index) Returns a string containing the character at the specified index.
If there is no character at the index, it returns an empty string.
The first character located at index 0 e.g var str = "HELLO
WORLD";
var res = str.charAt(0)
charCodeAt(indext) Returns the Unicode value of the character at the specified
index. If there is no character at the index. charCodeAt ruturns
NaN(not a number)
concat(string) Concatenate its argument to the end of the string that involves
the method.
E.g s1.concat(s2); is the same as s1+s2;
fromCharcode(val1,val Converts a Unicode values into a string concatenating the
2, …) corresponding character
e.gvar res = String.fromCharCode(65);// return A
indexOf(substrin, start) Returns the position of the first found occurrence of a specified
value in a string
var str = "Hello world, welcome to the universe.";
var n = str.indexOf("welcome");// return 13
100
lastIndexOf(subsring, Returns the position of the last found occurrence of a specified
start) value in a string
Method Description
METHODS OF THE STRING
slice(start,end)
OBJECT
Returns a string containing the portion of the string from
index start to index end.
var res = str.slice(0, 5);//return hello
split(string) Split the source string into an array of string where its string
argument specifies the delimiter
str.split(" ");//HELLO, WORLD
substr(start,length) Returns the string containing length characters starting from
index starting the source string. If length is not specified , a
sting containing characters from start to the end of the source
string is returned
substring(start,end) Returns a string containing a character from index start up but
not including index end in the source string. var res =
str.substring(1, 4);// return ELL
toLowerCase() Returns a string in which all upper case letters are converted to
lowercase case letters. Non character strings are not converted
toUpperCase() Returns a string in which all lower case letters are converted to
upper case letters. Non character strings are not converted
• push(): adds one or more elements to the end of an array and returns the
elements of the new array size.Ex: fruits.push(“potato");
• reverse(): reverses the order of the elements of an array- the first becomes the
last, and the last becomes the first.
• shift(): removes the first element from an array. e.g: fruits.shift();
• unshift(): adds one or more elements to the front of an array and returns the new
102
length of the array. E.g:fruits.unshift("Lemon");
THE MATH OBJECT & MATH METHODS
The Math object allows you to perform mathematical tasks.
Includes several mathematical constants and methods.
value = Math.method(variable);
For example,
AbsValue = Math.abs(NumVar);
var pi_value=Math.PI;
var sqrt_value=Math.sqrt(16);
103
Math Method Descrition
Math.abs(number) Returns the absolute value of number
105
CONT…
exp(x) : Returns the value of Ex
floor(x): Returns x, rounded downwards to the nearest integer
log(x):Returns the natural logarithm (base E) of x
max(x,y,z,...,n) :Returns the number with the highest
value
min(x,y,z,...,n):Returns the number with the lowest value
pow(x,y):Returns the value of x to the power of y
random() :Returns a random number between 0 and 1
round(x):Rounds x to the nearest integer
sqrt(x):Returns the square root of x
tan(x):Returns the tangent of an angle
106
DATE OBJECT
getDay() Returns a number from 0 (Sunday) to 6 (Saturday) representing the day of the week in local time or UTC,
getUTCDay() respectively.ዓ.ም በኢሮፓውያን
getFullYear() Returns the year as a four-digit number in local time or UTC, respectively.
getUTCFullYear()
getHours() Returns a number from 0 to 23 representing hours since midnight in local time or UTC, respectively.
getUTCHours()
getMilliseconds() Returns a number from 0 to 999 representing the number of milliseconds in local time or UTC, respectively.
getUTCMilliSeconds() The time is stored in hours, minutes, seconds and milliseconds.
getMinutes() Returns a number from 0 to 59 representing the minutes for the time in local time or UTC, respectively.
getUTCMinutes()
getMonth() Returns a number from 0 (January) to 11 (December) representing the month in local time or UTC,
getUTCMonth() respectively.
getSeconds() Returns a number from 0 to 59 representing the seconds for the time in local time or UTC, respectively.
getUTCSeconds()
getTime() Returns the number of milliseconds between January 1, 1970 and the time in the Date object.
getTimezoneOffset() Returns the difference in minutes between the current time on the local computer and UTC—previously
known as Greenwich Mean Time (GMT).
108
setDate( val ) Sets the day of the month (1 to 31) in local time or UTC, respectively.
setUTCDate( val )
METHODS OF THE DATE OBJECT…..
Me tho d De sc riptio n
setFullYear( y, m, d ) Sets the year in local time or UTC, respectively. The second and third
arguments representing the month and the date are optional. If an optional
setUTCFullYear( y, m, d ) argument is not specified, the current value in the Date object is used.
setHours( h, m, s, ms ) Sets the hour in local time or UTC, respectively. The second, third and fourth
arguments representing the minutes, seconds and milliseconds are optional. If
setUTCHours( h, m, s, ms ) an optional argument is not specified, the current value in the Date object is
used.
setMonth( m, d ) Sets the month in local time or UTC, respectively. The second argument
representing the date is optional. If the optional argument is not specified, the
setUTCMonth( m, d ) current date value in the Date object is used.
setSeconds( s, ms ) Sets the second in local time or UTC, respectively. The second argument
representing the milliseconds is optional. If this argument is not specified, the109
setUTCSeconds( s, ms ) current millisecond value in the Date object is used.
METHODS OF THE DATE OBJECT…..
Me tho d De sc rip tio n
setTime( ms ) Sets the time based on its argument—the number of elapsed milliseconds
since January 1, 1970.
toLocaleString() Returns a string representation of the date and time in a form specific to the
computer’s locale. For example, September 13, 2001 at 3:42:22 PM is
represented as 09/13/01 15:47:22 in the United States and 13/09/01
15:47:22 in Europe.
toUTCString() Returns a string representation of the date and time in the form: 19 Sep 2001
15:47:22 UTC
toString() Returns a string representation of the date and time in a form specific to the
locale of the computer (Mon Sep 19 15:47:22 EDT 2001 in the United
States).
valueOf() The time in number of milliseconds since midnight, January 1, 1970.
110
THE DOCUMENT OBJECT MODEL
Every web page resides inside a browser window can be considered as
an object.
A Document object represents the HTML document that is displayed
in that window.
The way that document content is accessed and modified is called
the Document Object Model, or DOM.
The Objects are organized in a hierarchy which applies to the
organization of objects in a Web document.
Window object: Top of the hierarchy. It is the outmost element of the
object hierarchy.
Document object: Each HTML document that gets loaded into a
window becomes a document object.
Form object: Everything enclosed in the <form>...</form> tags sets
the form object. 111
PART OF THE DOM
window (browser window)
Location (URL)
document (HTML page)
anchors <a>
body <body>
images <img>
forms <form>
elements <input>, <textarea>, <select>
frames <frame>
tables <table>
Rows <tr>
cells <th>, <td>
title <title> 112
JavaScript Object Hierarchy
113
• JavaScript define objects for all elements in a Web
page.
• Some widely used objects are:
• The Window object
• The Document object
• The History object
• The Location object
• The Navigator object
114
“WINDOW” OBJECT
Basic idea:
Primary task of a web browser is to display HTML
documents in a window.
The “window” object represents the window (or
frame) where the document is being displayed.
It is one of the highest-level objects in the JavaScript
object hierarchy.
It represents the content area of the browser window
that can be divided into multiple frames or sub-
regions.
Each sub region or frame is itself a window.
115
IMPORTANT PROPERTIES OF “WINDOW”:
closed
a Boolean value; true if window is closed.
document
represents the HTML document displayed in the
window.
history
represents the user’s browsing history.
location
117
IMPORTANT METHODS SUPPORTED BY
“WINDOW”:
alert(),prompt(), confirm()
displays dialog boxes (already discussed).
close()
close the window.
open()
opens a top-level window to display a specific URL
118
moveBy(), moveTo()
◦ moves the window to a new position.
resizeBy(), resizeTo()
◦ width, height
size of the display in pixels.
◦ availWidth, availHeight
display size that is actually available (excluding space required
by Windows taskbar, for example).
121
“LOCATION” OBJECT
The window.location object represents the URL of the document
currently being displayed in the window.
The Location Object is used to enable navigation to different URLs on
the Internet through JavaScript.
Main properties:
href
contains a string that consists of the complete text of the URL.
protocol, host, pathname, search
contains the various individual parts of the URL.
Methods supported by “location”:
reload()
reloads the currently displayed page from the web server.
replace()
loads a specified URL, and displays it.
the specified URL replaces the current one in the browser’s history122
list.
“HISTORY” OBJECT
The History Object contains a list of all pages that have
been visited in the browser window.
The document.history object has been designed to model the
browsing history of a window as an array of recently
visited URLs.
Elements of the array are not directly accessible, due to
security reasons.
Only the “length” property of the “history” object can be
accessed which is an integer value representing the number
of links currently referenced by the History object .
123
Property:
◦ length
contains the number of URLs stored in the browsing
history.
Methods:
◦ back()
moves backward in the window’s browsing history.
◦ forward()
moves forward in the window’s browsing history.
◦ go(x)
takes an integer argument, and can skip forward or
124
“DOCUMENT” OBJECT
125
The window.document object refers to the HTML document
displayed in the window.
Main properties of “document” object:
document.
◦ applets [ ]
an array of “applet” objects representing the Java applets in the
document.
126
bgColor, fgColor
◦ represents the background and foreground colors of the
document.
cookie
◦ a special property that allows Javascript programs to read and
write HTTP cookies.
forms [ ]
◦ an array of “form” objects representing the <FORM>
elements in the document.
images [ ]
◦ an array of “image” objects representing the <IMG> elements
in the document.
127
lastModified
◦ last modification date of the document.
links [ ]
◦ an array of “link” objects representing the hypertext links in
the document.
location, URL
◦ specifies the URL from which the doccument was loaded.
title
◦ the text between the <TITLE> and </TITLE> tags.
128
METHODS AVAILABLE IN “DOCUMENT”:
open()
opens a new document, overwriting any existing document
content.
close()
closes a document that was begun with open().
write()
appends text to the currently open document.
writeln()
outputs text to the currently open document, and append a
“newline” character,
129
JAVASCRIPT FORM OBJECT
The JavaScript Form Object is a property of the document object.
The Form object represents an HTML <form> element.
A form can be submitted by calling the JavaScript submit method
or clicking the form submit button.
Form Object Properties
action - This specifies the URL and CGI script file name the form is
to be submitted to.
It allows reading or changing the ACTION attribute of the
HTML FORM tag.
elements - An array of fields and elements in the form.
130
FORM OBJECT PROPERTIES
method - This is a read or write string. It has the value "GET" or
"POST".
name - The form name. Corresponds to the FORM Name attribute.
target - The name of the frame or window the form submission
response is sent to by the server. Corresponds to the FORM
TARGET attribute
encoding - This is a read or write string. It specifies the encoding
method the form data is encoded in before being submitted to the
server. It corresponds to the ENCTYPE attribute of the FORM tag.
The default is "application/x-www-form-urlencoded". Other
encoding includes text/plain or multipart/form-data.
length - The number of fields in the elements array. I.E. the length of
the elements array.
131
FORM OBJECTS
Forms have their own objects.
button - An GUI pushbutton control. Methods are click(), blur(), and
focus(). Attributes:
name - The name of the button
type - The object's type. In this case, "button".
value - The string displayed on the button.
checkbox - An GUI check box control. Methods are click(), blur(), and
focus(). Attributes:
checked - Indicates whether the checkbox is checked. This is a read
or write value.
defaultChecked - Indicates whether the checkbox is checked by
default. This is a read only value.
name - The name of the checkbox.
type - Type is "checkbox".
value - A read or write string that specifies the value returned when132
the checkbox is selected.
FileUpload - This is created with the INPUT type="file". This is the
same as the text element with the addition of a directory browser.
Methods are blur(), and focus(). Attributes:
name - The name of the FileUpload object.
type - Type is "file".
value - The string entered which is returned when the form is
submitted.
hidden - An object that represents a hidden form field and is used for
client/server communications. No methods exist for this object.
Attributes:
name - The name of the Hidden object.
type - Type is "hidden".
value - A read or write string that is sent to the server when the
form is submitted.
133
password - A text field used to send sensitive data to the server. Methods are
blur(), focus(), and select(). Attributes:
defaultValue - The default value.
name - The name of the password object."
type - Type is "password".
value - A read or write string that is sent to the server when the form is
submitted.
radio - A GUI radio button control. Methods are click(), blur(), and focus().
Attributes:
checked - Indicates whether the radio button is checked. This is a read or
write value.
defaultChecked - Indicates whether the radio button is checked by
default. This is a read only value.
length - The number of radio buttons in a group.
name - The name of the radio button.
type - Type is "radio".
value - A read or write string that specifies the value returned when the 134
radio button is selected.
reset - A button object used to reset a form back to default values.
Methods are click(), blur(), and focus(). Attributes:
name - The name of the reset object.
type - Type is "reset".
value - The text that appears on the button. By default it is "reset".
select - A GUI selection list. This is basically a drop down list. Methods
are blur(), and focus(). Attributes:
length - The number of elements contained in the options array.
name - The name of the selection list.
options - An array each of which identifies an options that may be
selected in the list.
selectedIndex - Specifies the current selected option within the select
list
type - Type is "select".
135
submit - A submit button object. Methods are click(), blur(), and
focus(). Attributes:
name - The name of the submit button.
type - Type is "submit".
value - The text that will appear on the button.
text - A GUI text field object. Methods are blur(), focus(), and
select(). Attributes:
defaultValue - The text default value of the text field.
name - The name of the text field.
type - Type is "text".
value - The text that is entered and appears in the text field. It is
sent to the server when the form is submitted.
136
textarea - A GUI text area field object. Methods are blur(),
focus(), and select(). Attributes:
defaultValue - The text default value of the text area field.
name - The name of the text area.
type - Type is textarea.
value- The text that is entered and appears in the text area
field. It is sent to the server when the form is submitted
Form Object Methods
reset() - Used to reset the form elements to their default
values.
submit() - Submits the form as though the submit button were
pressed by the user.
Events
onReset
onSubmit 137
E N D
T H E
138