Dca 04 Block 03 Javascript
Dca 04 Block 03 Javascript
DCA-04
WEB -DESIGN
Block
JAVA SCRIPT
Unit -5
Getting Started
Unit -6
Advanced Java Script
EXPERT COMMITTEE
Dr.P.K.Behera (Chairman)
Reader in Computer Science
Utkal University , Odisha
DrJ.R.Mohanty (Member)
Prof And HOD
KIIT University, Odisha
ShPabitranandaPattnaik (Member)
Scientist –E,NIC
NIC, ,BhubaneswarOdisha
Sh Malaya Kumar Das (Member)
Scientist –E , NIC
Bhubaneswar , Odisha
Dr.BhagirathiNayak (Member)
Professor And Head (IT & System)
Sri Sri University, Odisha
Dr.ManoranjanPradhan (Member)
Professor and Head
G.I.T.A
Bhubaneswar, Odisha
Mr.V.S.Sandilya (Convener)
Academic Consultant I.T
Odisha State Open University,
Sambalpur,Odisha
COURSE WRITER
Learning objectives:
After the Completion of this unit you should be able to know
The importance of JavaScript
Features of Java Script
Writing format in Java Script
Variable declaration & initialization
Types of operators
Conditional statements
Repetitive statements
Dialog box in Java Script
Structure
5.1.1 Definition:
5.1.2 History
<Script ...>
JavaScript code
</script>
Language: This attribute specifies what scripting language you are using.
Typically, its value will be javascript. Although recent versions of HTML
(and XHTML, its successor) have phased out the use of this attribute.
Type: This attribute is what is now recommended to indicate the scripting
language in use and its value should be set to "text/javascript".So your
JavaScript syntax will look as follows.
JavaScript code
</script>
All the modern browsers come with built-in support for JavaScript. Frequently,
you may need to enable or disable this support manually. This chapter explains
the procedure of enabling and disabling JavaScript support in your browsers:
Internet Explorer, Firefox, chrome, and Opera.
Here are the steps to turn on or turn off JavaScript in Internet Explorer:
1. Follow Tools Internet Options from the menu.
2. Select Security tab from the dialog box.
3. Click the Custom Level button.
4. Scroll down till you find the Scripting option.
5. Select Enable radio button under Active scripting.
6. Finally click OK and come out.
Tips: To disable JavaScript support in your Internet Explorer, you need to select
Disable radio button under Active scripting.
Tips: To disable JavaScript support in Opera, you should not select the Enable
JavaScript checkbox.
If you need a script to run as the page loads so that the script generates content in
the page, then the script goes in the <body> portion of the document. In this case,
you would not have any function defined using JavaScript. Take a look at the
following code.
You can put your JavaScript code in <head> and <body> section
altogether as follows.
<html>
<head>
<script type="text/javascript" src="filename.js" ></script></head>
<body>
……….
……….
</body>
</html>
To use JavaScript from an external file source, you need to write all your
JavaScript source code in a simple text file with the extension ".js" and then
include that file as shown above.
For example, you can keep the following content in filename.js file and then you
can use sayHello function in your HTML file after including the filename.js file.
Function sayHello()
{
alert("Hello World")
}
Answer:__________________________________________________________
_________________________________________________________________
_________________________________________________________________
Answer:__________________________________________________________
_________________________________________________________________
_________________________________________________________________
Answer:__________________________________________________________
_________________________________________________________________
_________________________________________________________________
Answer:__________________________________________________________
_________________________________________________________________
_________________________________________________________________
Q5. Write the steps to turn on or turn off JavaScript in Internet Explorer.
Answer:__________________________________________________________
_________________________________________________________________
_________________________________________________________________
5.5 Variables
Like many other programming languages, JavaScript has variables. Variables can
be thought of as named containers. You can place data into these containers and
then refer to the data simply by naming the container. Before you use a variable in
a JavaScript program, you must declare it. Variables are declared with the var
keyword as follows.
5.5.1 Definition
It is a quantity whose value can be change during the execution of the
program.
You can also declare multiple variables with the same var keyword as follows:
var money, name;
5.5.3Variable Initialization
Storing a value in a variable is called variable initialization. You can do
variable initialization at the time of variable creation or at a later point in time
when you need that variable. For instance, you might create variable named
money and assign the value 523.50 to it later. For another variable, you can assign
a value at the time of initialization as follows.
Tips:Use the var keyword only for declaration or initialization, once for the life of
any variable name in a document. You should not re-declare same variable twice.
JavaScript is untyped language. This means that a JavaScript variable can hold a
value of any data type. Unlike many other languages, you don't have to tell
JavaScript during variable declaration what type of value the variable will hold.
The value type of a variable can change during the execution of a program and
JavaScript takes care of it automatically.
Global Variables: A global variable has global scope which means it can
be defined anywhere in your JavaScript code.
function checkscope( )
{
var myVar = "local"; // Declare a local variable
document.write(myVar);
}
</script>
5.6 Operators
5.6.1 Definition
An Operator is a symbol that tells to perform specific operation.
Note: Addition operator (+) works for Numeric as well as Strings. e.g. "a" + 5
will give "a5".
Example
<html>
<body>
<script type="text/javascript">
<!--
var a = 5;
var b = 2;
var c = "Test";
var linebreak = "<br />";
document.write("a + b = ");
result = a + b;
document.write(result);
document.write(linebreak);
document.write("a - b = ");
result = a - b;
document.write(result);
document.write(linebreak);
document.write("a / b = ");
result = a / b;
document.write(result);
document.write(linebreak);
document.write("a % b = ");
result = a % b;
document.write(result);
document.write(linebreak);
document.write("a + b + c = ");
result = a + b + c;
document.write(result);
document.write(linebreak);
a = a++;
document.write("a++ = ");
result = a++;
document.write(result);
document.write(linebreak);
b = b--;
document.write("b-- = ");
result = b--;
document.write(result);
document.write(linebreak);
//-->
</script>
<p>Set the variables to different values and then try...</p>
5 < Less
than
Checks if the
value of the left
operand is less
A<B True
than the value of
the right operand,
if yes, then the
condition
becomes true.
6 <= Less
than or
Equal to
Checks if the
value of the left
operand is less
A<=B True
than or equal to
the value of the
right operand, if
yes, then the
condition
becomes true.
<html>
<body>
<script type="text/javascript">
<!--
var a = 10;
var b = 20;
var linebreak = "<br />";
document.write("(a == b) => ");
result = (a == b);
document.write(result);
document.write(linebreak);
document.write("(a < b) => ");
result = (a < b);
document.write(result);
document.write(linebreak);
document.write("(a > b) => ");
result = (a > b);
document.write(result);
document.write(linebreak);
document.write("(a != b) => ");
result = (a != b);
document.write(result);
document.write(linebreak);
document.write("(a >= b) => ");
result = (a >= b);
document.write(result);
document.write(linebreak);
document.write("(a <= b) => ");
result = (a <= b);
document.write(result);
document.write(linebreak);
//-->
</script>
<p>Set the variables to different values and different operators and then try...</p>
</body>
</html>
Sl Operator Description
No
1 && Logical AND
If both the operands are
non-zero, then the
condition becomes true.
2 || Logical OR
If any of the two
operands are non-zero,
then the condition
becomes true.
3 ! Logical NOT
Reverses the logical
state of its operand. If a
condition is true, then
the Logical NOT
operator will make it
false.
Sl Operator Description
No
1 = Simple Assignment
Assigns values from the right side operand to
the left side operand
Ex: C = A + B will assign the value of A + B
into C
2 += Add and Assignment
It adds the right operand to the left operand and
assigns the result to the left operand.
Ex: C += A is equivalent to C = C + A
3 -= Subtract and Assignment
It subtracts the right operand from the left
operand and assigns the result to the left
operand.
Ex: C -= A is equivalent to C = C - A
4 *= Multiply and Assignment
It multiplies the right operand with the left
operand and assigns the result to the left
operand.
Ex: C *= A is equivalent to C = C * A
5 /= Divide and Assignment)
It divides the left operand with the right operand
and assigns the result to the left operand.
Ex: C /= A is equivalent to C = C / A
6 %= Modules and Assignment
It takes modulus using two operands and
assigns the result to the left operand.
Ex: C %= A is equivalent to C = C % A
Note: Same logic applies to Bitwise operators, so they will become <<=, >>=,
>>=, &=, |= and ^=.
The conditional operator first evaluates an expression for a true or false value and
then executes one of the two given statements depending upon the result of the
evaluation.
Sl Operator Description
No
1 ?: Conditional
If Condition is true? Then value X : Otherwise
value Y
Example
<html>
<body>
<script type="text/javascript">
<!--
var a = 10;
var b = 20;
var linebreak = "<br />";
document.write ("((a > b) ?100 : 200) => "); result = (a > b) ? 100 : 200;
document.write(result);
document.write(linebreak);
document.write ("((a < b) ?100 : 200) => ");
result = (a < b) ? 100 : 200;
document.write(result);
document.write(linebreak);
//-->
</script>
<p>Set the variables to different values and different operators and then try...</p>
</body>
</html>
Answer:__________________________________________________________
_________________________________________________________________
_________________________________________________________________
Answer:__________________________________________________________
_________________________________________________________________
_________________________________________________________________
5.7 IF….ELSE
While writing a program, there may be a situation when you need to adopt one out
of a given set of paths. In such cases, you need to use conditional statements that
allow your program to make correct decisions and perform right actions.
JavaScript supports conditional statements which are used to perform different
actions based on different conditions. Here we will explain the if…..else
statement.
The „if‟ statement is the fundamental control statement that allows JavaScript to
make decisions and execute statements conditionally.
Syntax
Here a JavaScript expression is evaluated. If the resulting value is true, the given
statement(s) are executed. If the expression is false, then no statement would be
not executed. Most of the times, you will use comparison operators while making
decisions.
Example
The following example to understand how the if statement works.
<html>
<body>
<script type="text/javascript">
<!--
var age = 20;
if( age >=18 ){
document.write("<b>Qualifies for Election Voting</b>");}
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
The „if...else‟ statement is the next form of control statement that allows
JavaScript to execute statements in a more controlled way.
Syntax
The syntax of an if-else statement is as follows:
if (expression)
{
Statement(s) to be executed if expression is true
}
else
{
Statement(s) to be executed if expression is false
}
Here JavaScript expression is evaluated. If the resulting value is true, the given
statement(s) in the „if‟ block, are executed. If the expression is false, then the
given statement(s) in the else block are executed.
Example
The following code to learn how to implement an if-else statement in JavaScript.
<html>
<body>
<script type="text/javascript">
<!--
var age = 15;
if( age >= 18 )
{
document.write("<b>Qualifies for Election Voting</b>"); }else{
document.write("<b>Does not qualify for Election Voting</b>");
}
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
The „if...else if...‟ statement is an advanced form of if…else that allows JavaScript
to make a correct decision out of several conditions.
Syntax
The syntax of an if-else-if statement is as follows:
if (expression 1){
Statement(s) to be executed if expression 1 is true }
else if (expression 2){
Statement(s) to be executed if expression 2 is true }
else if (expression 3){
Statement(s) to be executed if expression 3 is true }
else{
Statement(s) to be executed if no expression is true
}
There is nothing special about this code. It is just a series of if statements, where
each if is a part of the else clause of the previous statement. Statement(s) are
executed based on the true condition, if none of the conditions is true, then the
else block is executed.
Example
The following code to learn how to implement an if-else-if statement in
JavaScript.
<html>
<body>
<script type="text/javascript">
<!--
var mark = 92;
if(mark >= 90 ){
document.write("<b>”Result is Excellent”</b>"); }
else if( mark >=60 ){
document.write("<b>“Result is 1st Class”</b>"); }
else if( mark>=50 ){
document.write("<b>“Result is 2nd Class”</b>"); }
else if( mark>=40 ){
document.write("<b>“Result is 3rd Class”</b>"); }
else{
document.write("<b>Fail</b>");}
//-->
</script>
<p>set the variable to different value and then try...</p>
</body>
</html>
switch (expression)
{
case condition 1: statement(s)
break;
case condition 2: statement(s)
break;
...
case condition n: statement(s)
break;
default: statement(s)
}
The break statements indicate the end of a particular case. If they were omitted,
the interpreter would continue executing each statement in each of the following
cases.
Example
The following example to implement switch-case statement.
<html>
<body>
<script type="text/javascript">
<!--
var grade='A';
document.write("Entering switch block<br />");
switch (grade)
{
case 'A': document.write("Good job<br />");
break;
case 'B': document.write("Pretty good<br />");
break;
case 'C': document.write("Passed<br />");
break;
case 'D': document.write("Not so good<br />");
break;
case 'F': document.write("Failed<br />");
break;
default: document.write("Unknown grade<br />")
}
document.write("Exiting switch block");
//-->
</script>
<p>Set the variable to different value and then try...</p>
Odisha State Open University Page 24
</body>
</html>
5.9 Loops
Iterative statements, also called loop statements, specify certain commands
to be executed repeatedly until some condition is met. The loops are often used to
iterate the values of an array (hence the name) or to work though repetitious
mathematical tasks. It is a command that execute again and again till condition
fulfill.
There are different types of loop used in java script . Some of the loop are
:
Syntax:
statement
} while (expression);
For example:
var i = 0;
do {
i += 2;
The while statement is a pretest loop. This means the evaluation of the
escape condition is done before the code inside the loop has been executed.
Because of this, it is possible that the body of the loop is never executed.
Syntax:
while(expression) statement
For example:
i += 2;
The for statement is also a pretest loop with the added capabilities of variable
initialization before entering the loop and defining post loop code to be entered.
The „for‟ loop is the most compact form of looping. It includes the following
three important parts:
The loop initialization where we initialize our counter to a starting value.
The initialization statement is executed before the loop begins.
The test statement which will test if a given condition is true or not. If the
condition is true, then the code given inside the loop will be executed,
otherwise the control will come out of the loop.
The iteration statement where you can increase or decrease your counter.
Syntax:
For example:
alert(i);
This code defines a variable i that begins with the value 0. The for loop is entered
only if the conditional expression (i <iCount) evaluates to true, making it possible
that the body of the code might not be executed. If the body is executed, the
postloop expression is also executed, iterating the variable i.
Example
<html>
<body>
<script type="text/javascript">
<!--
var count;
document.write("Starting Loop" + "<br />");
for(count = 0; count < 5; count++){
document.write("Current Count : " + count );
document.write("<br />");
}
//-->
</script>
<p>Set the variable to different value and then try...</p>
</body>
</html>
Output
Like any other advanced programming language, JavaScript also supports all the
features necessary to write modular code using functions. You must have seen
functions like alert() and write() in the earlier chapters. We were using these
functions again and again, but they had been written in core JavaScript only once.
JavaScript allows us to write our own functions as well. This section explains how
to write your own functions in JavaScript.
Before we use a function, we need to define it. The most common way to define a
function in JavaScript is by using the function keyword, followed by a unique
function name, a list of parameters (that might be empty), and a statement block
surrounded by curly braces.
Syntax
<script type="text/javascript">
<!--
function functionname(parameter-list) {
statements
}
//-->
</script>
Example
To invoke a function somewhere later in the script, you would simply need to
write the name of that function as shown in the following code.
<html>
<head>
<script type="text/javascript"> function sayHello()
{
document.write ("Hello there!");
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type="button" onclick="sayHello()" value="Say Hello"> </form>
<p>Use different text in write method and then try...</p> </body>
</html>
Output
Till now, we have seen functions without parameters. But there is a facility to pass
different parameters while calling a function. These passed parameters can be
captured inside the function and any manipulation can be done over those
parameters. A function can take multiple parameters separated by comma.
Example
The following example. We have modified our sayHello function here. Now it
takes two parameters.
Output
For example, you can pass two numbers in a function and then you can expect the
function to return their multiplication in your calling program.
Example
Try the following example. It defines a function that takes two parameters
and concatenates them before returning the resultant in the calling
program.
Example
The following example to learn how to implement nested functions.
<html>
<head>
<script type="text/javascript">
<!--
function hypotenuse(a, b) {
function square(x) { return x*x; }
return Math.sqrt(square(a) + square(b));
}
function secondFunction(){
var result;
result = hypotenuse(1,2);
document.write ( result );
}
//-->
</script>
</head>
Odisha State Open University Page 31
<body>
<p>Click the following button to call the function</p>
<form>
<input type="button" onclick="secondFunction()" value="Call Function">
</form>
<p>Use different parameters inside the function and then try...</p>
</body>
</html>
Here we will see a few examples to understand the relation between Event and
JavaScript.
This is the most frequently used event type which occurs when a user
clicks the left button of his mouse. You can put your validation, warning
etc., against this event type.
Example
<html>
<head>
<script type="text/javascript">
<!--
function sayHello() {
document.write ("Hello World")
}
//-->
</script>
</head>
<body>
<p> Click the following button and see result</p>
<input type="button" onclick="sayHello()" value="Say Hello" />
</body>
</html>
onsubmit is an event that occurs when you try to submit a form. You can put your
form validation against this event type.
Example
The following example shows how to use onsubmit. Here we are calling a
validate() function before submitting a form data to the webserver. If validate()
function returns true, the form will be submitted, otherwise it will not submit the
data.
The following example.
<html>
<head>
<script type="text/javascript">
<!--
function validation() {
all validation goes here
.........
return either true or false
}
//-->
</script>
</head>
<body>
<form method="POST" action="t.cgi" onsubmit="return
validate()">
.......
<input type="submit" value="Submit" />
</form>
</body>
</html>
These two event types will help you create nice effects with images or even with
text as well. The onmouseover event triggers when you bring your mouse over
any element and the onmouseout triggers when you move your mouse out from
that element. Try the following example.
<html>
<head>
<script type="text/javascript">
<!--
function over() {
document.write ("Mouse Over");
}
function out() {
document.write ("Mouse Out");
}
//-->
</script>
</head>
<body>
<p>Bring your mouse inside the division to see the result:</p>
<div onmouseover="over()" onmouseout="out()">
<h2> This is inside the division </h2>
</div>
</body>
</html>
5.11.4 HTML5 Standard Events
The standard HTML 5 events are listed here for your reference. Here script
indicates a Javascript function to be executed against that event.
Attribute Value Description
Offline script Triggers when the document
goes offline
Onabort script Triggers on an abort event
onafterprint script Triggers after the document is
printed
onbeforeonload script Triggers before the document
loads
onbeforeprint script Triggers before the document
is printed
onblur script Triggers when the window
loses focus
oncanplay script Triggers when media can start
play, but might has to stop for
buffering
oncanplaythrough script Triggers when media can be
played to the end, without
stopping for buffering
onchange script Triggers when an element
changes
onclick script Triggers on a mouse click
Odisha State Open University Page 34
oncontextmenu script Triggers when a context menu
is triggered
ondblclick script Triggers on a mouse double-
click
ondrag script Triggers when an element is
dragged
ondragend script Triggers at the end of a drag
operation
ondragenter script Triggers when an element has
been dragged to a valid drop
target
ondragleave script Triggers when an element
leaves a valid drop target
ondragover script Triggers when an element is
being dragged over a valid
drop target
ondragstart script Triggers at the start of a drag
operation
ondrop script Triggers when dragged
element is being dropped
ondurationchange script Triggers when the length of
the media is changed
onemptied script Triggers when a media
resource element suddenly
becomes empty.
onended script Triggers when media has
reach the end
onerror script Triggers when an error occur
onfocus script Triggers when the window
gets focus
onformchange script Triggers when a form changes
onforminput script Triggers when a form gets
user input
onhaschange script Triggers when the document
has changed
oninput script Triggers when an element
gets user input
oninvalid script Triggers when an element is
invalid
onkeydown script Triggers when a key is
pressed
onkeypress script Triggers when a key is
pressed and released
onkeyup script Triggers when a key is
released
oncontextmenu script Triggers when a context menu
is triggered
5.12 Cookies
Web Browsers and Servers use HTTP protocol to communicate and HTTP
is a stateless protocol. But for a commercial website, it is required to maintain
session information among different pages. For example, one user registration
ends after completing many pages. But how to maintain users' session information
across all the web pages.
Your server sends some data to the visitor's browser in the form of a cookie. The
browser may accept the cookie. If it does, it is stored as a plain text record on the
visitor's hard drive. Now, when the visitor arrives at another page on your site, the
browser sends the same cookie to the server for retrieval. Once retrieved, your
server knows/remembers what was stored earlier.
Cookies are a plain text data record of 5 variable-length fields:
Expires: The date the cookie will expire. If this is blank, the cookie will
expire when the visitor quits the browser.
Domain: The domain name of your site.
Path: The path to the directory or web page that set the cookie. This may
be blank if you want to retrieve the cookie from any directory or page.
Secure: If this field contains the word "secure", then the cookie may only
be retrieved with a secure server. If this field is blank, no such restriction
exists.
Name=Value: Cookies are set and retrieved in the form of key-value
pairs.
Cookies were originally designed for CGI programming. The data contained in a
cookie is automatically transmitted between the web browser and the web server,
so CGI scripts on the server can read and write cookie values that are stored on
the client.
JavaScript can also manipulate cookies using the cookie property of the
Document object. JavaScript can read, create, modify, and delete the cookies that
apply to the current web page.
document.cookie = "key1=value1;key2=value2;expires=date";
Here the expires attribute is optional. If you provide this attribute with a valid
date or time, then the cookie will expire on a given date or time and thereafter, the
cookies' value will not be accessible.
Note: Cookie values may not include semicolons, commas, or whitespace. For
this reason, you may want to use the JavaScript escape() function to encode the
value before storing it in the cookie. If you do this, you will also have to use the
corresponding unescape() function when you read the cookie value.
<html>
<head>
<script type="text/javascript">
<!--
function WriteCookie()
{
if( document.myform.customer.value == "" ){
alert ("Enter some value!");
return;
}
cookievalue= escape(document.myform.customer.value) + ";";
document.cookie="name=" + cookievalue;
document.write ("Setting Cookies : " + "name=" + cookievalue );
}
//-->
</script>
</head>
<body>
<form name="myform" action="">
Enter name: <input type="text" name="customer"/>
<input type="button" value="Set Cookie" onclick="WriteCookie();"/>
</form>
</body>
</html>
Output
Reading a cookie is just as simple as writing one, because the value of the
document.cookie object is the cookie. So you can use this string whenever you
want to access the cookie. The document.cookie string will keep a list of
name=value pairs separated by semicolons, where name is the name of a cookie
and value is its string value.
You can use strings' split() function to break a string into key and values as
follows:
Example
The following example to get all the cookies.
<html>
<head>
<script type="text/javascript">
<!--
function ReadCookie()
{
var allcookies = document.cookie;
document.write ("All Cookies : " + allcookies );
Note: Here length is a method of Array class which returns the length of an
array. We will discuss Arrays in a separate chapter. By that time, please try to
digest it.
You can extend the life of a cookie beyond the current browser session by setting
an expiration date and saving the expiry date within the cookie. This can be done
by setting the „expires‟ attribute to a date and time.
Example
The following example. It illustrates how to extend the expiry date of a cookie by
1 Month.
<html>
<head>
<script type="text/javascript">
<!--
function WriteCookie()
{
var now = new Date();
now.setMonth( now.getMonth() + 1 );
cookievalue = escape(document.myform.customer.value) + ";"
document.cookie="name=" + cookievalue;
document.cookie = "expires=" + now.toUTCString() + ";"
document.write ("Setting Cookies : " + "name=" + cookievalue );
}
//-->
</script>
</head>
<body>
<form name="formname" action="">
Enter name: <input type="text" name="customer"/>
<input type="button" value="Set Cookie" onclick="WriteCookie()"/>
</form>
</body>
</html>
Sometimes you will want to delete a cookie so that subsequent attempts to read
the cookie return nothing. To do this, you just need to set the expiry date to a time
in the past.
Example
The following example. It illustrates how to delete a cookie by setting its expiry
date to one month behind the current date.
<html>
<head>
<script type="text/javascript">
<!--
Odisha State Open University Page 40
function WriteCookie()
{
var now = new Date();
now.setMonth( now.getMonth() - 1 );
cookievalue = escape(document.myform.customer.value) + ";"
document.cookie="name=" + cookievalue;
document.cookie = "expires=" + now.toUTCString() + ";"
document.write("Setting Cookies : " + "name=" + cookievalue );
}
//-->
</script>
</head>
<body>
<form name="formname" action="">
Enter name: <input type="text" name="customer"/>
<input type="button" value="Set Cookie" onclick="WriteCookie()"/>
</form>
</body>
</html>
You can refresh a web page using JavaScript location.reload method. This code
can be called automatically upon an event or simply when the user clicks on a
link. If you want to refresh a web page using a mouse click, then you can use the
following code:
Example
The following example. It shows how to refresh a page after every 5 seconds. You
can change this time as per your requirement.
<html>
<head>
<script type="text/JavaScript">
<!--
function AutoRefresh( t ) {
setTimeout("location.reload(true);", t);
}
// -->
</script>
</head>
<body onload="JavaScript:AutoRefresh(5000);">
<p>This page will refresh every 5 seconds.</p>
</body>
</html>
<html>
<head>
<script type="text/javascript">
<!--
function Redirect() {
window.location="http://www.tutorialspoint.com";
}
document.write ("You will be redirected to our main page in 10
seconds!");
setTimeout('Redirect()', 10000);
//-->
</script>
</head>
<body>
</body>
</html>
Example 3
The following example shows how to redirect your site visitors onto a different
page based on their browsers.
<html>
<head>
<script type="text/javascript">
<!--
var browsername=navigator.appName;
if( browsername == "Netscape" )
{
window.location="http://www.location.com/ns.htm";
}
else if ( browsername =="Microsoft Internet Explorer")
{
window.location="http://www.location.com/ie.htm";
}
else
{
window.location="http://www.location.com/other.htm";
}
//-->
</script>
</head>
<body> </body></html>
Odisha State Open University Page 43
5.14 Dialogs
JavaScript supports three important types of dialog boxes. These dialog boxes can
be used to raise and alert, or to get confirmation on any input or to have a kind of
input from the users. Here we will discuss each dialog box one by one.
An alert dialog box is mostly used to give a warning message to the users. For
example, if one input field requires to enter some text but the user does not
provide any input, then as a part of validation, you can use an alert box to give a
warning message.
Nonetheless, an alert box can still be used for friendlier messages. Alert box gives
only one button "OK" to select and proceed.
Example
<html>
<head>
<script type="text/javascript">
<!--
function Warn() {
alert ("This is a warning message!");
document.write ("This is a warning message!");
}
//-->
</script>
</head>
<body>
<p>Click the following button to see the result: </p>
<form>
<input type="button" value="Click Me" onclick="Warn();" />
</form>
</body>
</html>
Output
A confirmation dialog box is mostly used to take user's consent on any option. It
displays a dialog box with two buttons: OK and Cancel.
If the user clicks on the OK button, the window method confirm() will return
true. If the user clicks on the Cancel button, then confirm() returns false. You can
use a confirmation dialog box as follows.
Example
<html>
<head>
<script type="text/javascript">
<!--
function getConfirmation(){
var retVal = confirm("Do you want to continue ?");
if( retVal == true ){
document.write ("User wants to continue!");
return true;
}else{
Document.write ("User does not want to continue!");
return false;
}
}
//-->
</script>
</head>
<body>
<p>Click the following button to see the result: </p>
<form>
<input type="button" value="Click Me" onclick="getConfirmation();" />
</form>
</body>
</html>
Output
The prompt dialog box is very useful when you want to pop-up a text box to get
user input. Thus, it enables you to interact with the user. The user needs to fill in
the field and then click OK. This dialog box is displayed using a method called
prompt() which takes two parameters: (i) a label which you want to display in the
text box and (ii) a default string to display in the text box. This dialog box has
two buttons: OK and Cancel. If the user clicks the OK button, the window
method prompt() will return the entered value from the text box. If the user clicks
the Cancel button, the window method prompt() returns null.
Example
<html>
<head>
<script type="text/javascript">
<!--
function getValue(){
var retVal = prompt("Enter your name : ", "your name here");
document.write("You have entered : " + retVal);
}
//-->
</script>
</head>
<body>
<p>Click the following button to see the result: </p>
<form>
<input type="button" value="Click Me" onclick="getValue();" />
</form>
</body>
</html>
Output
<script>
function myFunction() {
var hidden = false;
hidden = !hidden;
if(hidden) {
document.getElementById('togglee').style.visibility = 'hidden';
window.print();
window.location="my_test.html";
} else {
document.getElementById('togglee').style.visibility = 'visible';
}
}
</script>
</body>
</html>
Step-1
Step-2
Upon clicking the print button.
Answer:__________________________________________________________
_________________________________________________________________
Answer:_________________________________________________________
________________________________________________________________
Answer:__________________________________________________________
_________________________________________________________________
Answer:__________________________________________________________
_________________________________________________________________
Answer:__________________________________________________________
_________________________________________________________________
JavaScript code
</script>
Or
Q5. Write the steps to turn on or turn off JavaScript in Internet Explorer.
Answer:
Here are the steps to turn on or turn off JavaScript in Internet Explorer:
1. Follow Tools InternetOptions from the menu.
2. Select Security tab from the dialog box.
3. Click the Custom Level button.
4. Scroll down till you find the Scripting option.
5. Select Enable radio button under Active scripting.
6. Finally click OK and come out.
Answer: It is a quantity whose value can be changed during the execution of the
program. It can be declare using var keyword.
Answer:
Iterative statements, also called loop statements, specify certain commands
to be executed repeatedly until some condition is met. Or A statement that execute
again and again till condition fulfill.
Answer:
Answer:
Cookies are small files which are stored on a user's computer. They are
designed to hold a modest amount of data specific to a particular client and
website, and can be accessed either by the web server or the client computer. This
allows the server to deliver a page tailored to a particular user, or the page itself
can contain some script which is aware of the data in the cookie and so is able to
carry information from one visit to the website (or related site) to the next.
Answer:
Answer:
The JavaScript print function window.print() prints the current web page when
executed.
Learning objectives:
After the Completion of this unit you should be able to know
Structure
Object properties can be any of the three primitive data types, or any of the
abstract data types, such as another object. Object properties are usually
variables that are used internally in the object's methods, but can also be
globally visible variables that are used throughout the page. The syntax
for adding a property to an object is:
objectName.objectProperty = propertyValue;
Example:
The following code gets the document title using the "title" property of the
document object.
Methods are the functions that let the object do something or let something
be done to it. There is a small difference between a function and a method
– at a function is a standalone unit of statements and a method is attached
to an object and can be referenced by the this keyword. Methods are
useful for everything from displaying the contents of the object to the
screen to performing complex mathematical operations on a group of local
properties and parameters.
Example:
<html>
<head>
<title>User-defined objects</title>
<script type="text/javascript">
function book(title, author){
this.title = title;
this.author = author;
}
</script>
</head>
<body>
<script type="text/javascript">
var myBook = new book("Java Script", " Dhruba & Sushanta");
document.write("Book title is : " + myBook.title + "<br>");
document.write("Book author is : " + myBook.author + "<br>");
</script>
</body>
</html>
6.1.6 Defining Methods for an Object
The previous examples demonstrate how the constructor creates the object
and assigns properties. But we need to complete the definition of an object
by assigning methods to it.
Example
<html>
<head>
<title>User-defined objects</title>
<script type="text/javascript">
// Define a function which will work as a method
function addPrice(amount){
this.price = amount;
}
function book(title, author){
this.title = title;
this.author = author;
this.addPrice = addPrice; // Assign that method as property.
}
</script>
</head>
<body>
6.1.7 The‘with’Keyword
Syntax
The syntax for with object is as follows:
with (object)
{
properties used without the object name and dot
}
Example
The following example.
<html>
<head>
<title>User-defined objects</title>
<script type="text/javascript">
// Define a function which will work as a method
function addPrice(amount){
with(this){
price = amount;
}
}
function book(title, author){
this.title = title;
Odisha State Open University Page 59
this.author = author;
this.price = 0;
this.addPrice = addPrice; // Assign that method as property.
}
</script>
</head>
<body>
<script type="text/javascript">
var myBook = new book("Perl", "Mohtashim");
myBook.addPrice(100);
document.write("Book title is : " + myBook.title + "<br>");
document.write("Book author is : " + myBook.author + "<br>");
document.write("Book price is : " + myBook.price + "<br>");
</script>
</body>
</html>
6.2 Working with numbers
The Number object represents numerical date, either integers or floating-
point numbers. In general, you do not need to worry about Number
objects because the browser automatically converts number literals to
instances of the number class.
Syntax
The syntax for creating a number object is as follows:
In the place of number, if you provide any non-number argument, then the
argument cannot be converted into a number, it returns NaN (Not-a-
Number).
Property Description
MAX_VALUE The largest possible value a number in
JavaScript can have
1.7976931348623157E+308
MIN_VALUE The smallest possible value a number in
JavaScript can have 5E-324
NaN Equal to a value that is not a number.
NEGATIVE_INFINITY A value that is less than MIN_VALUE.
POSITIVE_INFINITY A value that is greater than MAX_VALUE
prototype A static property of the Number object. Use
the prototype property to assign new properties
and methods to the Number object in the
current document
constructor Returns the function that created this object's
instance. By default this is the Number object.
Example:
<html>
<head>
<script type="text/javascript">
<!--
function showValue()
{
var val = Number.MAX_VALUE;
document.write ("Value of Number.MAX_VALUE : " + val );
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="Click Me" onclick="showValue();"
/>
</form>
</body>
</html>
Output
Syntax
6.2.1.3 NaN
Unquoted literal constant NaN is a special value representing Not-a-
Number. Since NaN always compares unequal to any number, including NaN, it
is usually used to indicate an error condition for a function that should return a
valid number.
Note: Use the isNaN() global function to see if a value is an NaN value.
Syntax
The syntax to use NaN is:
var val = Number.NaN;
6.2.1.4 NEGATIVE_INFINITY
This is a special numeric value representing a value less than
Number.MIN_VALUE. This value is represented as "-Infinity". It resembles an
infinity in its mathematical behavior. For example, anything multiplied by
NEGATIVE_INFINITY is NEGATIVE_INFINITY, and anything divided by
NEGATIVE_INFINITY is zero. Because NEGATIVE_INFINITY is a constant,
it is a read-only property of Number.
Syntax
The syntax to use NEGATIVE_INFINITY is as follows:
6.2.1.5 POSITIVE_INFINITY
This is a special numeric value representing any value greater than
Number.MAX_VALUE. This value is represented as "Infinity". It resembles an
infinity in its mathematical behavior. For example, anything multiplied by
POSITIVE_INFINITY is POSITIVE_INFINITY, and anything divided by
POSITIVE_INFINITY is zero. As POSITIVE_INFINITY is a constant, it is a
read-only property of Number.
Syntax
Use the following syntax to use POSITIVE_INFINITY.
var val = Number. POSITIVE_INFINITY;
Note: Prototype is a global property which is available with almost all the objects.
Syntax
Use the following syntax to use Prototype.
object.prototype.name = value
6.1.2.7 Constructor
It returns a reference to the Number function that created the instance's
prototype.
Syntax
Its syntax is as follows:
number. Constructor ( )
Return value
Returns the function that created this object's instance.
The Number object contains only the default methods that are a part of
every object's definition.
Method Description
toExponential() Forces a number to display in exponential
notation, even if the number is in the range
in which JavaScript normally uses standard
notation.
Syntax
Its syntax is as follows:
number.toExponential( [fractionDigits] )
Parameter Details
fractionDigits: An integer specifying the number of digits after the decimal point.
Defaults to as many digits as necessary to specify the number.
Return Value
A string representing a Number object in exponential notation with one digit
before the decimal point, rounded to fractionDigits digits after the decimal point.
If the fractionDigits argument is omitted, the number of digits after the decimal
point defaults to the number of digits necessary to represent the value uniquely.
Example
<html>
<head>
<title>Javascript Method toExponential()</title>
</head>
<body>
<script type="text/javascript">
var num=77.1234;
var val = num.toExponential();
document.write("num.toExponential() is : " + val );
document.write("<br />");
val = num.toExponential(4);
document.write("num.toExponential(4) is : " + val );
document.write("<br />");
val = num.toExponential(2);
document.write("num.toExponential(2) is : " + val);
document.write("<br />");
val = 77.1234.toExponential();
document.write("77.1234.toExponential()is : " + val );
document.write("<br />");
val = 77.1234.toExponential();
document.write("77 .toExponential() is : " + val);
</script>
</body>
</html>
This method formats a number with a specific number of digits to the right of the
decimal.
Syntax
Its syntax is as follows:
number.toFixed( [digits] )
Parameter Details
digits: The number of digits to appear after the decimal point.
Return Value
A string representation of number that does not use exponential notation
and has the exact number of digits after the decimal place.
6.2.2.3 toLocaleString ()
This method converts a number object into a human readable string representing
the number using the locale of the environment.
Syntax
Its syntax is as follows:
number.toLocaleString()
Return Value
Returns a human readable string representing the number using the locale of the
environment.
6.2.2.4 toPrecision ()
This method returns a string representing the number object to the specified
precision.
Syntax
Its syntax is as follows:
number.toPrecision( [ precision ] )
Parameter Details
precision: An integer specifying the number of significant digits.
Return Value
Returns a string representing a Number object in fixed-point or exponential
notation rounded toprecision significant digits.
Return Value
Returns a string representing the specified Number object.
Syntax
Property Description
constructor Returns a reference to
the Boolean function
that created the
object.
prototype The prototype
property allows you
to add properties and
methods to an object.
6.3.2 constructor ()
Javascript boolean constructor() method returns a reference to the
Boolean function that created the instance's prototype.
Syntax
Use the following syntax to create a Boolean constructor() method.
boolean.constructor()
Return Value
<html>
<head>
<title>JavaScript constructor() Method</title>
</head>
<body>
<script type="text/javascript">
var bool = new Boolean( );
document.write("bool.constructor() is : " + bool.constructor);
</script>
</body>
</html>
Output
6.3.4 toSource ()
Javascript boolean toSource() method returns a string representing the source
code of the object.
Syntax
Its syntax is as follows:
boolean.toSource()
Return Value
Returns a string representing the source code of the object.
6.3.5 valueOf ()
Javascript boolean valueOf() method returns the primitive value of the specified
boolean object.
Syntax
Its syntax is as follows:
boolean.valueOf()
Return Value
Returns the primitive value of the specified boolean object.
Example
The following example.
<html>
<head>
<title>JavaScript toString() Method</title>
</head>
<body>
<script type="text/javascript">
var flag = new Boolean(false);
document.write( "flag.valueOf is : " + flag.valueOf() );
</script>
</body>
</html>
Property Description
constructor Returns a reference to the String function that created the
object.
length Returns the length of the string.
prototype The prototype property allows you to add properties and
methods to an object.
6.4.2 Length
Syntax
Use the following syntax to find the length of a string:
string.length
Return Value
Returns the number of characters in the string.
Example
<html>
<head>
<title>JavaScript String length Property</title>
</head>
<body>
<script type="text/javascript">
var str = new String( "This is string" );
document.write("str.length is:" + str.length);
</script>
</body>
</html>
Output
Here is a list of the methods available in String object along with their description.
Method Description
charAt() Returns the character at the specified index.
charCodeAt() Returns a number indicating the Unicode value of
the character at the given index.
concat() Combines the text of two strings and returns a
new string.
6.4.4 toLocaleUppereCase ()
This method is used to convert the characters within a string to uppercase while
respecting the current locale. For most languages, it returns the same output as
toUpperCase.
Syntax
Its syntax is as follows:
Return Value
Returns a string in uppercase with the current locale.
Example
The following example.
<html>
<head>
<title>JavaScript String toLocaleUpperCase() Method</title>
</head>
<body>
<script type="text/javascript">
var str = "Apples are round, and Apples are Juicy.";
document.write(str.toLocaleUpperCase( ));
</script>
</body>
</html>
Output
The Array parameter is a list of strings or integers. When you specify a single
numeric parameter with the Array constructor, you specify the initial length of the
array. The maximum length allowed for an array is 4,294,967,295. You can create
array by simply assigning values as follows:
Property Description
constructor Returns a reference to the array function that created the
object.
index The property represents the zero-based index of the match
in the string
input This property is only present in arrays created by regular
expression matches.
6.5.2 Constructor
JavaScript array constructor property returns a reference to the array function
that created the instance's prototype.
Syntax
Its syntax is as follows:
array.constructor
Return Value
Returns the function that created this object's instance.
Example
The following example.
<html>
<head>
<title>JavaScript Array constructor Property</title>
</head>
<body>
<script type="text/javascript">
var arr = new Array( 10, 20, 30 );
document.write("arr.constructor is:" + arr.constructor);
</script>
</body>
</html>
Method Description
concat() Returns a new array comprised of this
array joined with other array(s) and/or
value(s).
every() Returns true if every element in this
array satisfies the provided testing
function.
filter() Creates a new array with all of the
elements of this array for which the
provided filtering function returns true.
forEach() Calls a function for each element in the
array.
indexOf() Returns the first (least) index of an
element within the array equal to the
specified value, or -1 if none is found.
join() Joins all elements of an array into a
string.
lastIndexOf() Returns the last (greatest) index of an
element within the array equal to the
specified value, or -1 if none is found.
map() Creates a new array with the results of
calling a provided function on every
element in this array.
pop() Removes the last element from an array
and
push() Adds one or more elements to the end of
an array and returns the new length of
the array.
reduce() Apply a function simultaneously against
two values of the array (from left-to-
right) as to reduce it to a single value.
reduceRight() Apply a function simultaneously against
two values of the array (from right-to-
left) as to reduce it to a single value.
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
and returns that element.
slice() Extracts a section of an array and returns
a new array.
some() Returns true if at least one element in
this array satisfies the provided testing
function.
toSource() Represents the source code of an object
Odisha State Open University Page 73
sort() Sorts the elements of an array.
splice() Adds and/or removes elements from an
array.
toString() Returns a string representing the array
and its elements.
unshift() Adds one or more elements to the front
of an array and returns the new length of
the array.
6.5.4 Concat()
Javascript array concat( ) method returns a new array comprised of this array
joined with two or more arrays.
Syntax
The syntax of concat() method is as follows:
array.concat(value1, value2, ..., value n);
Parameter Details
valueN : Arrays and/or values to concatenate to the resulting array.
Return Value
Returns the length of the array.
Example
The following example.
<html>
<head>
<title>JavaScript Array concat Method</title>
</head>
<body>
<script type="text/javascript">
var alpha = ["a", "b", "c"];
var numeric = [1, 2, 3];
var alphaNumeric = alpha.concat(numeric);
document.write("alphaNumeric : " + alphaNumeric );
</script>
</body>
</html>
Output
Syntax
You can use any of the following syntaxes to create a Date object using Date()
constructor.
new Date( )
new Date(milliseconds)
new Date(datestring)
new Date(year,month,date[,hour,minute,second,millisecond ])
Here is a list of the properties of the Date object along with their description.
Property Description
constructor Specifies the function that creates an object's
prototype.
prototype The prototype property allows you to add
properties and methods to an object.
6.6.2 Constructor
JavaScript date constructor property returns a reference to the array function that
created the instance's prototype.
Syntax
Its syntax is as follows:
date.constructor
Return Value
Returns the function that created this object's instance.
Example
The following example.
<html>
<head>
<title>JavaScript Date constructor Property</title>
</head>
<body>
<script type="text/javascript">
var dt = new Date();
document.write("dt.constructor is : " + dt.constructor);
</script>
</body>
</html>
Here is a list of the methods used with Date and their description.
Method Description
Date() Returns today's date and time
getDate() Returns the day of the month for the specified date
according to local time.
getDay() Returns the day of the week for the specified date
according to local time.
getFullYear() Returns the year of the specified date according to local
time.
getHours() Returns the hour in the specified date according to local
time.
6.6.4 Date()
Javascript Date() method returns today's date and time and does not need any
object to be called.
Syntax
Its syntax is as follows:
Date()
Return Value
Returns today's date and time.
Example
The following example.
<html>
<head>
<title>JavaScript Date Method</title>
</head>
<body>
<script type="text/javascript">
var dt = Date();
document.write("Date and Time : " + dt );
</script>
</body>
</html>
Output
6.7.2 Math-E
Property Description
E Euler's constant and the base of natural
logarithms, approximately 2.718.
LN2 Natural logarithm of 2, approximately
0.693.
LN10 Natural logarithm of 10, approximately
2.302.
LOG2E Base 2 logarithm of E, approximately
1.442.
LOG10E Base 10 logarithm of E, approximately
0.434.
PI Ratio of the circumference of a circle to its
diameter, approximately 3.14159.
SQRT1_2 Square root of 1/2; equivalently, 1 over the
square root of 2, approximately 0.707.
SQRT2 Square root of 2, approximately 1.414.
This is an Euler's constant and the base of natural logarithms, approximately
2.718.
Syntax
Its syntax is as follows:
Math.E
Example
The following example program.
<html>
<head>
<title>JavaScript Math E Property</title>
</head>
<body>
<script type="text/javascript">
var property_value = Math.E
document.write("Property Value is :" + property_value);
</script>
</body>
</html>
Here is a list of the methods associated with Math object and their description.
Method Description
abs() Returns the absolute value of a number.
acos() Returns the arccosine (in radians) of a
number.
asin() Returns the arcsine (in radians) of a number.
atan() Returns the arctangent (in radians) of a
number.
atan2() Returns the arctangent of the quotient of its
arguments.
ceil() Returns the smallest integer greater than or
equal to a number.
cos() Returns the cosine of a number.
exp() Returns EN, where N is the argument, and E
is Euler's constant, the base of the natural
logarithm.
floor() Returns the largest integer less than or equal
to a number
log() Returns the natural logarithm (base E) of a
number.
max() Returns the largest of zero or more numbers.
min() Returns the smallest of zero or more
numbers.
pow() Returns base to the exponent power, that is,
base exponent.
random() Returns a pseudo-random number between 0
and 1.
round() Returns the value of a number rounded to the
nearest integer.
sin() Returns the sine of a number.
sqrt() Returns the square root of a number.
tan() Returns the tangent of a number.
toSource() Returns the string "Math".
This method returns the square root of a number. If the value of a number is
negative, sqrt returns NaN.
Syntax
Its syntax is as follows:
Math.sqrt ( x );
Parameter Details
x: A number.
Return Value
Returns the square root of a given number.
Example
The following example program.
<html>
<head>
<title>JavaScript Math sqrt() Method</title>
</head>
<body>
<script type="text/javascript">
var value = Math.sqrt( 0.2 );
document.write("First Test Value : " + value );
var value = Math.sqrt( 81 );
document.write("<br />Second Test Value : " + value );
var value = Math.sqrt( 13 );
document.write("<br />Third Test Value : " + value );
var value = Math.sqrt( -4 );
document.write("<br />Fourth Test Value : " + value );
</script>
</body>
</html>
Output
Answer:__________________________________________________________
_________________________________________________________________
Answer:__________________________________________________________
_________________________________________________________________
Answer:__________________________________________________________
_________________________________________________________________
Answer:__________________________________________________________
_________________________________________________________________
Q5. Which property returns a reference to the array function that created the
instance's prototype in java script?
Answer:__________________________________________________________
_________________________________________________________________
Answer:__________________________________________________________
_________________________________________________________________
Answer:__________________________________________________________
_________________________________________________________________
Answer:__________________________________________________________
_________________________________________________________________
Syntax
A regular expression could be defined with the RegExp() constructor, as follows:
var pattern = new RegExp(pattern, attributes);
Brackets
Brackets ([]) have a special meaning when used in the context of regular
expressions.
Expression Description
Here is a list of the properties associated with RegExp and their description
Property Description
constructo Specifies the function that creates an object's
r prototype.
6.8.2 Multiline
Syntax
Its syntax is as follows:
RegExpObject.multiline
Return Value
Returns "TRUE" if the "m" modifier is set, "FALSE" otherwise.
Example
<html>
<head>
<title>JavaScript RegExp multiline Property</title>
</head>
<body>
<script type="text/javascript">
var re = new RegExp( "string" );
if ( re.multiline ){
document.write("Test1-multiline property is set");
}else{
document.write("Test1-multiline property is not set");
}
re = new RegExp( "string", "m" );
if ( re.multiline ){
document.write("<br/>Test2-multiline property is set");
}else{
document.write("<br/>Test2-multiline property is not set");
}
6.8.3.RegExp Methods
Method Description
exec() Executes a search for a match in its string parameter.
test() Tests for a match in its string parameter.
toSource() Returns an object literal representing the specified
object; you can use this value to create a new object.
toString() Returns a string representing the specified object.
6.8.4 Test ( )
The test method searches string for text that matches regexp. If it finds a match, it
returns true; otherwise, it returns false.
Syntax
Its syntax is as follows:
RegExpObject.test( string );
Parameter Details
string: The string to be searched.
Return Value
Returns the matched text if a match is found, and null if not.
Example
<html>
<head>
<title>JavaScript RegExp test Method</title>
</head>
<body>
<script type="text/javascript">
var str = "Javascript is interesting scripting language: Trisha pattnaik";
var re = new RegExp( "script", "g" );
var result = re.test(str);
document.write("Test 1 - returned value : " + result);
re = new RegExp( "pushing", "g" );
var result = re.test(str);
Output
The way a document content is accessed and modified is called the Document
Object Model, or DOM. The Objects are organized in a hierarchy. This
hierarchical structure 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. The document contains the contents of the page.
Form object: Everything enclosed in the <form>...</form> tags sets the form
object.
Form control elements: The form object contains all the elements defined for
that object such as text fields, buttons, radio buttons, and checkboxes.
This is the model which was introduced in early versions of JavaScript language.
It is well supported by all browsers, but allows access only to certain key portions
of documents, such as forms, form elements, and images.
This model provides several read-only properties, such as title, URL, and last
Modified provide information about the document as a whole. Apart from that,
there are various methods provided by this model which can be used to set and get
document property values.
Example:
<html>
<head>
<title> Document Title </title>
<script type="text/javascript">
<!--
functionmyFunc()
{
var ret = document.title;
alert("Document Title : " + ret );
var ret = document.URL;
alert("Document URL : " + ret );
var ret = document.forms[0];
alert("Document First Form : " + ret );
var ret = document.forms[0].elements[1];
alert("Second element : " + ret );
}
//-->
</script>
Output
Syntax Errors
Syntax errors, also called parsing errors, occur at compile time in traditional
programming languages and at interpret time in JavaScript
Runtime Errors
Runtime errors, also called exceptions, occur during execution (after
compilation/interpretation).
Logical Errors
Logic errors can be the most difficult type of errors to track down. These errors
are not the result of a syntax or runtime error. Instead, they occur when you make
a mistake in the logic that drives your script and you do not get the result you
expected.
The try...catch...finallyStatement
<script type="text/javascript">
<!--
try {
// Code to run
[break;]
} catch ( e ) {
// Code to run if an exception occurs
[break;]
}[ finally {
// Code that is always executed regardless of
// an exception occurring
}]
//-->
</script>
Example
<html>
<head>
<script type="text/javascript">
<!--
functionmyFunc()
{
var a = 100;
document.write ("Value of variable a is : " + a );
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="Click Me" onclick="myFunc();" />
</form>
<p>Error will happen and depending on your browser: trisha.</p>
</body>
</html>
Example
We will take an example to understand the process of validation. Here is a
simple form in html format.
<html>
<head>
<title>Form Validation</title>
<script type="text/javascript">
<!--
// Form validation code will come here.
//-->
</script>
</head>
<body>
<form action="/cgi-bin/test.cgi" name="myForm"
Odisha State Open University Page 91
onsubmit="return(validate());">
<table cellspacing="2" cellpadding="2" border="1">
<tr>
<td align="right">Name</td>
<td><input type="text" name="Name" /></td>
</tr>
<tr>
<td align="right">EMail</td>
<td><input type="text" name="EMail" /></td>
</tr>
<tr>
<td align="right">Zip Code</td>
<td><input type="text" name="Zip" /></td>
</tr>
<tr>
<td align="right">Country</td>
<td>
<select name="Country">
<option value="-1" selected>[choose yours]</option>
<option value="1">USA</option>
<option value="2">UK</option>
<option value="3">INDIA</option>
</select>
</td>
</tr>
<tr>
<td align="right"></td>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
</form>
</body>
</html>
Output
<script type="text/javascript">
<!--
// Form validation code will come here.
function validate()
{
if( document.myForm.Name.value == "" )
{
alert( "Please provide your name!" );
document.myForm.Name.focus() ;
return false;
}
if( document.myForm.EMail.value == "" )
{
alert( "Please provide your Email!" );
document.myForm.EMail.focus() ;
return false;
}
if( document.myForm.Zip.value == "" ||
isNaN( document.myForm.Zip.value ) ||
document.myForm.Zip.value.length != 5 )
{
alert( "Please provide a zip in the format #####." );
document.myForm.Zip.focus() ;
return false;
}
if( document.myForm.Country.value == "-1" )
{
alert( "Please provide your country!" );
return false;
}
return( true );
}
//-->
</script>
You can use JavaScript to create a complex animation having, but not limited to,
the following elements:
Fireworks
Fade Effect
Roll-in or Roll-out
Page-in or Page-out
Object movements
JavaScript can be used to move a number of DOM elements (<img />, <div>, or
any other HTML element) around the page according to some sort of pattern
determined by a logical equation or function.
JavaScript provides the following two functions to be frequently used in
animation programs.
setTimeout (function, duration) - This function calls function after
duration milliseconds from now.
setInterval (function, duration) - This function calls function after
every duration milliseconds.
clearTimeout (setTimeout_variable) - This function clears any timer
set by the setTimeout() function.
JavaScript can also set a number of attributes of a DOM object including its
position on the screen. You can set top and left attribute of an object to position it
anywhere on the screen. Here is its syntax.
So let's implement one simple animation using DOM object properties and
JavaScript functions as follows. The following list contains different DOM
methods.
We are using the JavaScript function getElementById() to get a DOM
object and then assigning it to a global variable imgObj.
We have defined an initialization function init() to initialize imgObj
where we have set its position and left attributes.
We are calling initialization function at the time of window load.
Finally, we are calling moveRight() function to increase the left distance
by 10 pixels. You could also set it to a negative value to move it to the left
Example
The following example.
<html>
<head>
<title>JavaScript Animation</title>
<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>
</head>
<body>
<form>
<img id="myImage" src="D:/4.jpg" />
<p>Click button below to move the image to right</p>
<input type="button" value="Click Me" onclick="moveRight();"
/>
</form>
</body>
</html>
6
6.12.2 Automated Animation
In the above example, we saw how an image moves to right with every click. We
can automate this process by using the JavaScript function setTimeout() as
follows. Here we have added more methods. So let's see what is new here:
The moveRight() function is calling setTimeout() function to set the
position of imgObj.
We have added a new function stop() to clear the timer set by
setTimeout() function and to set the object at its initial position.
Example
The following example code.
<html>
<head>
<title>JavaScript Animation</title>
<script type="text/javascript">
<!--
var imgObj = null;
var animate ;
function init(){
imgObj = document.getElementById('myImage');
imgObj.style.position= 'relative';
imgObj.style.left = '0px';
}
Odisha State Open University Page 96
function moveRight(){
imgObj.style.left = parseInt(imgObj.style.left) + 10 + 'px';
animate = setTimeout(moveRight,20); // call moveRight in 20msec
}
function stop(){
clearTimeout(animate);
imgObj.style.left = '0px';
}
window.onload =init;
//-->
</script>
</head>
<body>
<form>
<img id="myImage" src="/images/html.gif" />
<p>Click the buttons below to handle animation</p>
<input type="button" value="Start" onclick="moveRight();" />
<input type="button" value="Stop" onclick="stop();" />
</form>
</body> </html>
Output
Example
Here is an example that shows how to list down all the plug-on installed in your
browser:
<html>
<head>
<title>List of Plug-Ins</title>
</head>
<body>
<table border="1">
<tr><th>Plug-in
Name</th><th>Filename</th><th>Description</th></tr>
Each plug-in has an entry in the array. Each entry has the following properties:
name - is the name of the plug-in.
filename - is the executable file that was loaded to install the plug-in.
description - is a description of the plug-in, supplied by the developer.
mimeTypes - is an array with one entry for each MIME type supported
by the plug-in.
You can use these properties in a script to find out the installed plug-ins, and then
using JavaScript, you can play appropriate multimedia file. Take a look at the
following example.
<html>
<head>
<title>Using Plug-Ins</title>
</head>
<body>
<script language="JavaScript" type="text/javascript">
media = navigator.mimeTypes["video/quicktime"];
NOTE: Here we are using HTML <embed> tag to embed a multimedia file.
Let us take a real example which works in almost all the browsers.
<html>
<head>
<title>Using Embeded Object</title>
<script type="text/javascript">
<!--
function play()
{
if (!document.demo.IsPlaying()){
document.demo.Play();
}
}
function stop()
{
if (document.demo.IsPlaying()){
document.demo.StopPlay();
}
}
function rewind()
if (document.demo.IsPlaying()){
document.demo.StopPlay();
}
document.demo.Rewind();
}
//-->
</script>
</head>
<body>
<embed id="demo" name="demo"
src="http://www.amrood.com/games/kumite.swf"
width="318" height="300" play="false" loop="false"
pluginspage="http://www.macromedia.com/go/getflashplayer"
swliveconnect="true">
</embed>
<html>
<head>
<title>Using JavaScript Image Map</title>
<script type="text/javascript">
<!--
function show(name){
document.myform.stage.value = name
}
//-->
</script>
</head>
<body>
<form name="myform">
<input type="text" name="stage" size="20" />
</form>
Output
6.15.1 Definition:
Extensible Markup Language (XML) is a markup language that defines a
set of rules for encoding documents in a format which is both human-
readable and machine-readable.
Answer:_________________________________________________________
________________________________________________________________
________________________________________________________________
Answer:__________________________________________________________
_________________________________________________________________
_________________________________________________________________
Answer:__________________________________________________________
_________________________________________________________________
_________________________________________________________________
Answer:__________________________________________________________
_________________________________________________________________
_________________________________________________________________
Answer:__________________________________________________________
_________________________________________________________________
_________________________________________________________________
Answer:__________________________________________________________
_________________________________________________________________
_________________________________________________________________
Answer:__________________________________________________________
_________________________________________________________________
_________________________________________________________________
Answer:__________________________________________________________
_________________________________________________________________
_________________________________________________________________
Answer: sqrt( )
Answer: abs( )
Answer: constructor
Answer: An array is a collection of data items, all of the same type, accessed
using a common name. Or The Array object lets you store multiple values in a
single variable. ... An array is used to store a collection of data, but it is often
more useful to think of an array as a collection of variables of the same type.
Answer: The String object lets you work with a series of characters; it wraps
JavaScript‟s string primitive data type with a number of helper methods. As
JavaScript automatically converts between string primitives and String objects,
you can call any of the helper methods of the String object on a string primitive.
Answer: The Boolean object represents two values, either "true" or "false".
Answer: The JavaScript navigator object includes a child object called plugins.
This object is an array, with one entry for each plug-in installed on the browser.
The navigator.plugins object is supported only by Netscape, Firefox, and Mozilla
only.
Answer: First let us see how to do a basic form validation. In the above form, we
are calling validate () to validate data when onsubmit event is occurring. The
following code shows the implementation of this validate () function.
Answer:
Here is the try...catch...finally block syntax:
<script type="text/javascript">
<!--
try {
// Code to run
[break;]
} catch ( e ) {
// Code to run if an exception occurs
[break;]
}[ finally {
// Code that is always executed regardless of
// an exception occurring
}]
//-->
</script>