0% found this document useful (0 votes)
121 views46 pages

Unit - III (Widt) Pre

Uploaded by

Vishnu Rajeev
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
121 views46 pages

Unit - III (Widt) Pre

Uploaded by

Vishnu Rajeev
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

UNIT – III

Client side Validation: Introduction to JavaScript - What is DHTML, JavaScript, basics,


variables, string manipulations, mathematical functions, statements, operators, arrays,
functions.
Objects in JavaScript - Data and objects in JavaScript, regular expressions, exception
handling.
DHTML with JavaScript - Data validation, opening a new window, messages and
confirmations, the status bar, different frames, rollover buttons, moving images.

JavaScript introduction:-

 JavaScript is a dynamic computer programming language.


 It is lightweight and most commonly used as a part of web pages, whose
implementations allow client-side script to interact with the user and make dynamic
pages.
 It is an interpreted programming language with object-oriented capabilities.
 JavaScript was first known as Live Script, but Netscape changed its name to
JavaScript, possibly because of the excitement being generated by Java.
 JavaScript can provide functionality, such as password protection, browser
detection, or display information, such as correct time and date.
 JavaScript is the most popular scripting language on the internet, and works in all
major browsers, such as internet explorer, Netscape navigator, etc.
 JavaScript is usually embedded directly in to HTML pages.

1. Write about basic JavaScript?


How to insert JavaScript into a HTML page:

 You can insert JavaScript into an HTML page by using <script> tag.
 JavaScript is placed between tags starting with <script language=”javascript”> and
ending with </script>.
 The script tag attributes are:
 language: Scripting language name.
 type: Internet content type for a scripting language.
 src: URL for an externally linked script.
 General syntax of JavaScript is as follows:
 <script language=”javascript”>
 JavaScript code here……
 </script>

1
Different places where JavaScript can be placed in HTML:

 JavaScript is traditionally embedded into a standard html program.


 JavaScript is embedded between <script>……</script> tags. These tags embedded
within the <head>….</head> or <body>…..</body> tags of the HTML program.
 JavaScript placed in the HEAD section of HTML will be executed when called.
 JavaScript placed in the BODY section will be executed only when the page is loaded.
 JavaScript can be placed in various locations in HTML such as
 JavaScript in HEAD section
 JavaScript in BODY section
 JavaScript in both HEAD and BODY
 JavaScript in External file
 The general structure for placing JavaScript in the HEAD section is:

<html><head>
<script language=”javascirpt”>
JavaScript written in HEAD section
</script>
</head>
</body>…</body></html>

 The general structure for placing JavaScript in the BODY section is:

<html>
<head>…</head>
<body>
<script language=”javascirpt”>
JavaScript written in BODY section
</script>
</body></html>

Basic Rules:
JavaScript programs contain variables, objects, and functions. They key points that
you need to apply in all scripts are listed below:
 JavaScript is case sensitive.
 JavaScript statements end with semi-colons.
 JavaScript has two forms of comments:
 Single line comments with a double slash (//) Ex: // this is JavaScript.
 Multiline comments begin with “/*” and end with “*/”. Ex: /* multiple lines */
 Blocks of code must be surrounded by a pair of curly brackets.
 Variables are declared using the var keyword.

2
 Functions have parameters which are passed inside parentheses.

How to display content on browser using JavaScript:


 JavaScript command used for writing output to a page is [Link].
 The [Link] command takes the arguments as the required for producing
output.
 The example below shows how to place JavaScript command inside an HTML page.

<script language=”javascript”>
[Link](“JavaScript is not java”); // JavaScript statement
</script>

2. Explain advantages and disadvantages of JavaScript?


Advantages of JavaScript:
 JavaScript is one of the simple, lightweight, versatile and interpreted programming
languages used to extend functionality in websites.
 Executed on the client side: For example, you can validate any user input before
sending a request to the server. This makes less load on the server.
 Relatively an easy language: This is quite easy to learn and the syntax that is close to
English.
 Instance response to the visitors: Without any server interaction, you don’t have to
wait for a page reload to get your desire result.
 Fast to the end user: As the script is executed on the user’s computer, depending on
task, the results are completed almost instantly.
 Interactivity increased: Creating interfaces that can react when the user hovers over
them or activates them using the keyboard.
 Rich interfaces: Drag and drop components or slider may give a rich interface to your
site visitors.

Disadvantages of JavaScript:
 Security issues: Any JavaScript snippets, while appended onto web pages on client
side immediately can also be used for exploiting the user’s system.
 Doesn’t have any multiprocessor or multi threading capabilities.
 JavaScript cannot be used for any networking applications.
 JavaScript does not allow us to read or write files.
 JavaScript render varies: JavaScript may be rendered by different layout engines
differently. As a result, this causes inconsistency in terms of interface and
functionality.

3
3. Explain Variables in JavaScript?
 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. Ex: var money;
 You can also declare multiple variables with the same var keyword.
Ex: var age, ID;
 Variables declaration and assignment can be done in a single step.
Ex: var age=34;

JavaScript variable Scope:


 The scope of the variable is the region of your program in which it is defined.
JavaScript variable will have only two scopes.
 Global variable: A global variable has global scope which means it is defined
everywhere in your JavaScript code.
 Local variable: A local variable will be visible only within a function where it is
defined. Function parameters are always local to those functions.
Example:<script type = "text/ javascript">
varmyVar = "global"; // Declare a global variable
functioncheckscope( ) {
varmyVar = "local"; // Declare a local variable
[Link](myVar); }
</script>
Output: local

JavaScript Variable Naming Rules:


While naming your variables in JavaScript, keep the following rules in mind.
 You should not use any of the JavaScript reserved keywords as a variable name. For
example, break or boolean variable names are not valid.
 JavaScript variable names should not start with a numeral (0-9). They must begin
with a letter or an underscore character. For example, 123test is an invalid variable
name but _123test is a valid one.
 JavaScript variable names are case-sensitive. For example, Name and name are two
different variables.

4
4. Explain about Data types in JavaScript?
 JavaScript provides different data types to hold different types of values. JavaScript
includes data types similar to other programming languages like java or c#.
 Data type indicates characteristics of data. It tells the compiler whether the data
value is numeric, alphabetic, data etc.., so that it can perform appropriate
operation. There are two types of data types in JavaScript.
1. Primitive data type 2. Non-primitive (reference) data type
 JavaScript is a dynamic type language, means you don't need to specify type of the
variable because it is dynamically used by JavaScript engine.
 You need to use var here to specify the data type. It can hold any type of values
such as numbers, strings etc.
Example: var a=30; //holding number
var b="balu"; //holding string

I. JavaScript primitive data types:-


There are five types of primitive data types in JavaScript. They are as follows:
 String: - The string data type is used to represents sequence of characters.
Ex: var name=” Hello balu”; orvarstr=new String(“Hello Balu”);
 Number: - The number data type is used to represents numeric values.
Ex: var x=1.2; var y=32;
 Boolean: - The Boolean data type represents boolean value either false or true.
Ex: var x=true; var y=false;
 Undefined: - The undefined data type represents undefined value.
Ex: var person=undefined;
 Null: - The null data type represents null i.e. no value at all.
Ex: var person=null;

II. JavaScript non-primitive data types:-


The non-primitive data types are as follows:
 Object: - The object data type represents instance through which we can access
members. Ex: var person={firstname:”Web”, lastname:”technology”};
 Array: - The array data type represents group of similar values.
Ex: var subjects = {“WT”, “DS”, “ICT”,”JAVA”,”CP”};
 RegExp: - The RegExp data type represents regular expressions.
Ex: var reg=new RegExp(“pattern”);

5) What is DHTML? Differentiate HTML and DHTML.


 DHTML is essentially Dynamic HTML. It is a new way of looking at and controlling the
standard HTML codes and commands.
 DHTML is a collection of technologies that are used to create interactive and
animated web sites.

5
 DHTML gives more control over the HTML elements. It allows one to incorporate a
client-side scripting language, such as JavaScript, a presentation definition language,
such as CSS, and the Document Object Model in HTML web pages.

HTML DHTML
DHTML stands for Dynamic Hypertext
[Link] stands for Hypertext markup markup language
language
2. HTML is a mark-up language DHTML is a collection of technology.
( HTML, CSS, javascript and DOM).
3. HTML creates static web pages. DHTML creates dynamic web pages,
4. HTML creates a plain page without any DHTML creates a page with HTML, CSS, DOM
styles and Scripts called as HTML and Scripts called as DHTML.
5. HTML sites will be slow upon client-side DHTML sites will be fast enough upon client-
technologies side technologies.
6. HTML cannot have any server side code DHTML may contain server side code.
7. In HTML, there is no need for database DHTML may require connecting to a
connectivity. database as it interacts with user.
8. HTML files are stored with .htm or .html DHTML files are stored with .dhtm
extension extension.
[Link] does not require any processing DHTML requires processing from browser
from browser, which changes its look and feel.

6. Explain Mathematical Functions in JavaScript?


 The Math object provides you properties and methods for mathematical constants
and functions. Unlike other global objects, Math is not a constructor.
 All the properties and methods of Math are static and can be called by using Math as
an object without creating it.
 Mathematical functions and values are part of a built in javaScript object called
Math.
 You refer to the constant pi as [Link] and you call the sine function as [Link](x),
where x is the method's argument.
 The syntax to call the properties and methods of Math are as follows

6
varpi_val = [Link];
varsine_val = [Link](30);
Math Methods:
1. abs() : This method returns the absolute value for the given number.
Syntax: [Link](n); where n is a number
Example: var m1=[Link](-21);
[Link](“ The absolute value of -21 is :”+m1);
Result: The absolute value of -21 is: 21

2. sqrt() : This method returns the square root of the given number.
Syntax: [Link](n); where n is a number
Example: var m2=[Link](16);
[Link](“ The square root of 16 is :”+m2);
Result: The square root of 16 is: 4

3. pow() : This method returns the m to the power of n that is mn.


Syntax: [Link](m, n); where m is base and n is exponent number
Example: var m3=[Link](8,2);
[Link](“8 to the power of 2 is :”+m3);
Result: 8 to the power of 2 value is: 64

4. ceil() :This method returns the largest integer for the given number.
Syntax: [Link](n); where n is a number
Example: var m4=[Link](45.89);
[Link](“a ceil value of 45.89 is :”+m4);
Result: aceil value of 45.89 is: 46

5. floor() : This method returns the smallest integer for the given number.
Syntax: [Link](n); where n is a number
Example: var m5=[Link](45.89);
[Link](“a floor value of 45.89 is :”+m5);
Result: afloor value of 45.89 is: 45

6. random() : This method returns the random number between 0 and 1.


Syntax: [Link](n); where n is a number
Example: var m6=[Link]();
[Link](“The random number is :”+m6);
Result: The random number is: 0.87556841577261

7
7. max() : This method returns the largest of zero or more numbers. If no arguments
are given, the results is –Infinity.
Syntax: [Link](valu1,valu2,………,valun); where n is a number
Example: var m7=[Link](50,30,60,90);
[Link](“The maximum value is :”+m7);
Result: The maximum value is: 90

8. min() : This method returns the smallest of zero or more numbers. If no arguments
are given, the results is –Infinity.
Syntax: [Link](valu1,valu2,………,valun); where n is a number
Example: var m8=[Link](50,30,60,90);
[Link](“The maximum value is :”+m8);
Result: The maximum value is: 30

9. sin() :This method returns the sine of a number. The sin method returns a numeric
value between -1 and 1, which represents the sine of the argument.
Syntax: [Link](n); where n is a number
Example: var m9=[Link](90);
[Link](“The sine value of 90 is :”+m9);
Result: The sine value of 90 is: 0.8939966636005578

10. tan() :This method returns the tangent of a number. The tan method returns a
numeric value that represents the tangent of the angle.
Syntax: [Link](n); where n is a number
Example: var m11=[Link](45);
[Link](“The tangent value of 45 is :”+m11);
Result: The tangent value of 45 is: 1

11. log() :This method returns the natural logarithm (base E) of a number. If the value of
number is negative, the return value is always NaN.
Syntax: [Link](n); where n is a number
Example: var m12=[Link](10);
[Link](“The logarithm value of 10 is :”+m12);
Result: The logarithm value of a 10 is: 2.302585092994046

7. Explain String manipulation (Functions) in JavaScript?


 The String object lets you work with a series of characters and 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.
 Use the following syntax to create a String object

8
varval = new String(string);
The String parameter is a series of characters that has been properly encoded.
String Methods:

1. charAt():charAt() is a method that returns the character from the specified index.
Characters in a string are indexed from left to right. The index of the first character is
0, and the index of the last character in a string, called stringName, is
[Link] –1.
Syntax:[Link](index);
Example:varstr=new String(“Welcome to JavaScript”);
[Link]("[Link](0) is:" + [Link](0));
Result: [Link](0) is: W

2. charCodeAt(): This method returns a number indicating the Unicode value of the
character at the given index. charCodeAt() always returns a value that is less than
65,536.
Syntax:[Link](index);
Example:varstr=new String(“Welcome to JavaScript”);
[Link]("[Link](0) is:" + [Link](0));
Result: [Link](0) is:87

3. indexOf(): This method returns the index position of the given string.
Syntax:[Link](string);
Example:var str1 = new String( "Welcome to JavaScript" );
var index = [Link]( "JavaScript" );
[Link]("indexOf found String is :" + index );
Result: indexOf found String is:11

4. concat():This method adds two or more strings and returns a new single string.
Syntax:[Link](string2, string3, ..., stringN]);
Example:var str1 = new String( "Hello" );
var str2 = new String(" Welcome to JavaScript" );
var str3 = [Link]( str2 );
[Link]("Concatenated String is :" + str3);
Result: Concatenated String is:Hello Welcome to JavaScript

5. toLowerCase(): This method returns the given string in lowercase letters.


Syntax:[Link]();
Example:var str1 = new String("WELCOME TO JAVASCRIPT" );
var str2 = [Link]();

9
[Link]("Lowercase String is :" + str2);
Result: Lowercase String is: welcome to javascript

6. toUpperCase():This method returns the given string in Uppercase letters.


Syntax:[Link]();
Example:var str1 = new String("welcome to javascript" );
var str2 = [Link]();
[Link]("Uppercase String is :" + str2);
Result: Uppercase String is: WELCOME TO JAVASCRIPT

7. slice():The slice(beginIndex, endIndex) method returns the parts of string from given
beginIndex to endIndex. In slice() method, beginIndex is inclusive and endIndex is
exclusive.
Syntax:[Link](begindex, endindex);
Example:var str1 = new String("welcome to JavaScript" );
var str2 = [Link](3,6);
[Link]("sliced value is :" + str2);
Result: sliced value is: come

8. split() :This method splits a String object into an array of strings by separating the
string into substrings.
Syntax:[Link](separator,limit);
Example:var str1 = new String("welcome to JavaScript let you start" );
var str2 = [Link](“ “,6);
[Link]("splitted value is :" + str2);
Result: splitted value is: welcome, to, JavaScript, let, you, start

9. trim():The JavaScript String trim() method removes leading and trailing whitespaces
from the string.
Syntax:[Link]();
Example:var str1 = new String(" welcome to JavaScript " );
var str2 = [Link]();
[Link]("Trimmed string is :" + str2);
Result: Trimmed string is: welcome to JavaScript

10. substr():This method returns the characters in a string beginning at the specified
location through the specified number of characters.
Syntax:[Link](start, length);
Example:var str1 = new String("welcome to JavaScript ");
var str2 = [Link](3,6);
[Link]("The sub string is :" + str2);

10
Result: The sub string is: come

8. What is an Operator? Explain types of Operators in JavaScript.


 JavaScript operators are symbols that are used to perform operations on operands.
 For example: var sum= a + b;
Where ‘+’ is the arithmetic operator and ‘=’ is the assignment operator and a, b are
operands. The following are types of operators in JavaScript.
1. Arithmetic Operators:
 Arithmetic operators are used to perform arithmetic operations on the operands
and return a single value. The following operators are known as JavaScript
arithmetic operators. Assume variable A holds 10 and variable B holds 20 then:

Operator Description Example


+ Adds two operands A + B will give 30
- Subtracts second operand from the first A – B will give -10
* Multiply both operands A * B will give 200
/ Divide the numerator by the denominator B / A will give 2
% Outputs the remainder of an integer division B % A will give 0
++ Increment operator, increases integer value by A++ will give 11
one
-- Decrement operator, decreases integer value by A-- will give 9
one

2. Comparison Operators:
 A comparison operator compares its operands and return a logical value based on
whether the comparison is true or not. The comparison operators are listed below
assume variable A holds 10 and variable B holds 20 then:

Operator Description Example


== Returns true if the two operands are equal (A==B) is not true
!= Returns true if the two operands are not equal (A!=B) is true
> Greater than returns true if the left operand is (A>B) is not true
greater than the right
>= Returns true if the left operand is greater than or (A>=B) is not true
equal to the right one
< Returns true if the left operand is less than the (A<B) is true
right
<= Returns true if the left operand is less than or (A<=B) is true
equal to the right one

3. Logical Operators:
 These operators are typically used with Boolean (logical) values. They return a
Boolean value. The Boolean operators are listed below, Assume variable A holds 10
and variable B holds 20 Then:

11
Operator Description Example
&& Called logical AND operator. If both the operands (A && B) is true
are non zero then condition becomes true.
|| Called Logical OR operator. If any of the two (A || B) is true
operands are non zero then condition becomes
true
! Called Logical NOT operator. Logical NOT returns !( A && B) is false
false if the operand evaluates to true. Otherwise it
returns true

4. Assignment Operators:
 These assignment operators (=) to assign a value to a variable or constant or
expression assigned for given variable. The assignment operators listed below
Operator Description Example
= Assign the value of the right operand to the left C = A + B will assign
operand value of A + B into C
+= Adds together the operands and assigns the result C += A is equivalent to
to the left operand C=C+A
-= It subtracts right operand from the left operand C -= A is equivalent to C
and assigns the result to left operand. =C–A
*= It multiplies right operand with the left operand C *= A is equivalent to C
and assigns the result to left operand. =C*A
/= It divides left operand with the right operand and C /= A is equivalent to C
assigns the result to left operand. =C/A
%= It takes modulus using two operands and assigns C %= A is equivalent to C
the result to left operand. =C%A

5. Bitwise Operators:
 The bitwise operators perform bitwise operations on operands. The bitwise
operators are as follows:

Operator Description Example


& Bitwise AND (10==20 & 20==33) = false
| Bitwise OR (10==20 | 20==33) = false
^ Bitwise XOR (10==20 ^ 20==33) = false
~ Bitwise NOT (~10) = -10
<< Bitwise Left Shift (10<<2) = 40
>> Bitwise Right Shift (10>>2) = 2
>>> Bitwise Right Shift with Zero (10>>>2) = 2

6. Conditional Operator (? :)
 JavaScript provides conditional operator which is used for comparing two
expressions, also contains a conditional operator that assigns a value to a variable
used on some condition.
 Syntax: variable = (condition)? value1:value2;
Example: result = (marks>=35)? “Passed”: “Failed”;

12
 Displays result depends on marks, if marks greater than are equal to 35 displays as
passed otherwise failed message.

7. The + Operator used on Strings:


 The + operator can also be used to add string variable or text values together. To
add two or more string variables together, use + operator.
 text1=” Hello”; text2= “Welcome to Javascript”; text3=text1+text2;
 After executions of the statements are above, the variable text3 contains “Hello
Welcome to JavaScript”.

9. Define a Function? Explain about Functions in JavaScript?


 A function is a group of reusable code which can be called anywhere in your
program.
 This eliminates the need of writing the same code again and again. It helps
programmers in writing modular codes.
 Functions allow a programmer to divide a big program into a number of small and
manageable functions.
 Every function is made up of a number of statements.

I. Function Definition:
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:
function function_Name(parameters list)
{
//code to be executed

}
Example:
function sayHallo()
{
Alert(“Hello there”);
}

II. Calling a Function:


To invoke (call) a function somewhere later in the script, you would simply need to write
the name of that function as shown in the following code.
Example:
<html>
<head>
<script type="text/javascript">
function sayHello()
{
[Link] ("Hello there!");
}

13
</script>
</head>
<body>
<form>
<input type="button" onclick="sayHello()" value="Say Hello">
</form>
</body>
</html>

III. Function Parameters:


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:
<html>
<body>
<script language=”javascript”>
function getcube(number){
alert(number*number*number);
}
</script>
<form>
<input type="button" value="click" onclick="getcube(4)"/>
</form></body></html>

IV. Function Return Values:


The return keyword is used to return values from function. Function can return
results. Results are returned using the return statement.
Example:
<html>
<body>
<script language=”javascript”>
function getInfo(){
return "hello welcome to Javascript” ;
}
<script>
[Link](getInfo());
</script>
</body>
</html>

14
10) Explain Conditional statements (Decision making) in JavaScript?
 Conditional statements are used to perform different actions based on different
conditions. In JavaScript we have the following conditional statements.

I. If statement:
 A if statement is used to execute some code if only, if specified conditions is true.
Syntax:
if (condition)
{
Code to be executed if condition is true
}
Example:
<html>
<head>
<title>If Statement</title></head>
<body>
<script type="text/javascript">
var age=20;
if(age>=18)
{
[Link](" You are eligible to vote ");
}
</script></body></html>
Output: You are eligible to vote

II. If-else statement:


 An if..else statement is used to execute some code if the condition is true and
another code if the condition is false.
Syntax:
if (condition)
{
Code to be executed if condition is true
}
else
{
Code to be executed if condition is false
}
Example:
<html>
<head><title>If else Statement</title></head>
<body>

15
<script type="text/javascript">
var age=20;
if(age>=18)
{
[Link](" You are eligible to vote ");
}
else
{
[Link](" You are not eligible to vote ");
}
</script></body></html>
Output: You are eligible to vote
III. If-else-if statement (else if ladder):
 An if-else-if statement is used to select one of several blocks of code to be executed.
Syntax:
if (condition1)
{
Code to be executed if condition1 is true
}
else if (condition2)
{
Code to be executed if condition2 is true
}
else if (conditionN)
{
Code to be executed if conditionN is true
}
else
{
Code to be executed if condition1 and 2 are not true
}

Example:
<html>
<head><title>If else if Statement</title></head>
<body>
<script type="text/javascript">
var marks=65;
if(marks>=75)
{
[Link](" Distinction");

16
}
else if (marks>=60 && marks<75)
{
[Link](" First division");
}
else if (marks>=50 && marks<60)
{
[Link](" Second division");
}
else if (marks>=40 && marks<50)
{
[Link](" Third division");
}
else
{
[Link](" Fail");
}
</script></body></html>
Output: First Division

IV. Switch statement:


The switch statement is used to select one of several blocks of code to be executed.
Syntax:
Switch (expression)
{
case condition 1: statement(s);
break;

case condition 2: statement(s);


break;
...

case condition n: statement(s);


break;

default: statement(s); break;


}
Example:
<html>
<head><title>If Statement</title></head>
<body>

17
<script type="text/javascript">
var grade=A;
switch (grade)
{
case ‘O’: [Link](" Out Standing”);
break;
case ‘A’: [Link](" Excellent”);
break;
case ‘B’: [Link](" Good”);
break;
case ‘C’: [Link](" Very Good”);
break;
case ‘D’: [Link](" Fair”);
break;
default: [Link](" Fail”);
break;
</script></body></html>
Output: Excellent

11) Explain Looping statements (Iteration) in JavaScript?


 The JavaScript loops are used to iterate the piece of code using for, while, do while
or for-in loops. It makes the code compact.
 In JavaScript we have the following looping statements. For and while loops are
called as entry level loops and do while loop called as exit level loop.

I. For loop:
 The JavaScript for loop iterates the elements for the fixed number of times. It
should be used if number of iteration is known.
Syntax:
for (initialization; condition; increment)
{
code to be executed
}

Example:
<html>
<head><title>For Loop Statement</title></head>
<body>
<script type=”text/javascript”>
for (var i=1; i<=5; i++)
{

18
[Link](i + "<br/>") ;
}
</script></body></html>

Output: 1 2 3 4 5

II. while loop:


 The JavaScript while loop iterates the elements for the infinite number of times. It
should be used if number of iteration is not known.
Syntax:
while (condition)
{
code to be executed
}

Example:
<html>
<head><title>While Loop Statement</title></head>
<body>
<script type=”text/javascript”>
var i=0;
while (i<=5)
{
[Link](i + "<br/>")
}
</script></body></html>

Output: 1 2 3 4 5

III. do while loop:


 The JavaScript do while loop iterates the elements for the infinite number of times
like while loop. But, code is executed at least once whether condition is true or
false.
Syntax:
do
{
code to be executed
}While(condition);

Example:
<html>

19
<head><title>do while Loop Statement</title></head>
<body>
<script type=”text/javascript”>
var i=0;
do
{
[Link](i + "<br/>")
}
while (i<=5);
</script></body></html>

Output: 1 2 3 4 5

12) Explain Break and Continue statements in JavaScript

 JavaScript provides full control to handle loops and switch statements. There may
be a situation when you need to come out of a loop without reaching its bottom.
 There may also be a situation when you want to skip a part of your code block and
start the next iteration of the loop.
 To handle all such situations, JavaScript provides break and continue statements.
 These statements are used to immediately come out of any loop or to start the
next iteration of any loop respectively.
 break and continue statements are used in for, while and do while loops.

I. Thebreak Statement:
 The break statement, which was briefly introduced with the switch statement, is
used to exit a loop early, breaking out of the enclosing curly braces.
Syntax: break;
Example:
<html>
<head><title>Break statement</title></head>
<body>
<script type="text/javascript">
var i;
for(i=0;i<=5;i++)
{
if(i==4)
{
break;
}
[Link](i+"<br>");

20
}
</script></body></html>
Output: 0 1 2 3

II. Thecontinue Statement:


 The continue statement breaks one iteration (in the loop), if a specified condition
occurs, and continues with the next iteration in the loop.
Syntax: continue;
Example:
<html>
<head><title>Continue statement</title></head>
<body>
<script type="text/javascript">
var i;
for(i=0;i<=5;i++)
{
if(i==4)
{
continue;
}
[Link](i+"<br>");
}
</script></body></html>
Output: 0 1 2 3 5

13) Explain about Arrays in JavaScript?

 The Array object lets you store multiple values in a single variable. It stores a fixed-
size sequential collection of elements of the same type.
 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.
There are 3 ways to construct array in JavaScript
By array literal:
The syntax of creating array using array literal is given below:
Syntax: var arrayname=[value1,value2 .... valueN];
As you can see, values are contained inside [ ] and separated by, (comma).
Example:
<html>
<script>
var emp=["Balu","Chiru","Raja"];
for (i=0;i<[Link];i++){

21
[Link](emp[i] + "<br/>");
}
</script>
</html>
Output: Balu
Chiru
Raja

By creating instance of Array directly (using new keyword)


The syntax of creating array directly is given below:
Syntax: var array_name=new Array();
Here, new keyword is used to create instance of array.
Example:
<html>
<script>
var i;
var emp = new Array();
emp[0] = "Balu";
emp[1] = "Chiru";
emp[2] = "Raja";
for (i=0;i<[Link];i++){
[Link](emp[i] + "<br>");
}
</script></html>
Output: Balu
Chiru
Raja

By creating array constructor (new keyword)


Here, you need to create instance of array by passing arguments in constructor so that we
don't have to provide value explicitly.
Syntax: var emp=new Array("Balu","Chiru","Raja");
Example:
The example of creating object by array constructor is given below.
<html>
<script>
var emp=new Array("Balu","Chiru","Balu");
for (i=0;i<[Link];i++){
[Link](emp[i] + "<br>");
}
</script></html>

22
Output: Balu
Chiru
Raja

14) Define an Object? Explain how to create Objects in JavaScript?

 A JavaScript object is an entity having state and behaviour (properties and method).
For example: car, pen, bike, chair, glass, keyboard, monitor etc.
 JavaScript is an object-based language. Everything is an object in JavaScript.
 JavaScript is template based not class based. Here, we don't create class to get the
object. But, we direct create objects.
 Javascript provides a number of application objects such as the document, window,
string, math, array, number and date objects.
 Each object has properties that can be read and sometimes setting JavaScript
statements. Many Objects have methods such as [Link] () that give the
object significant functionality.
Creating Objects: - There are three ways to create objects in JavaScript.
1. By object literal
2. By creating instance of Object directly (using new keyword)
3. By using an object constructor (using new keyword)

1. By object literal:-
 The syntax of creating object using object literal is given below:
object ={property1:value1,property2:value2.... propertyN:valueN}
As you can see, property and value is separated by : (colon).
Example: -
<html>
<script language="javascript">
emp={ id:102,name:"Subbu",salary:40000 }
[Link]([Link]+" "+[Link]+" "+[Link]);
</script>
</html>
Result: - 102 Subbu 40000

2. By creating instance of Object directly (using new keyword): -


 The syntax of creating object directly is given below:
var objectname=new Object();
Here, new keyword is used to create object.
Example:-
<html>
<script language="javascript">

23
var emp=new Object();
[Link]=101;
[Link]="Priyadarsini";
[Link]=50000;
[Link]([Link]+" "+[Link]+" "+[Link]);
</script> </html>
Result: - 102 Priyadarsini 50000

3. By using an object constructor (using new keyword): -


 Here, you need to create function with arguments. Each argument value can be
assigned in the current object by using this keyword. This keyword refers to the
current object.
Example: -
<html>
<script language="javascript">
function emp(id,name,salary)
{
[Link]=id;
[Link]=name;
[Link]=salary;
}
e=new emp(103,"Priyadarsini",30000);
[Link]([Link]+" "+[Link]+" "+[Link]);
</script></html>
Result: - 103 Priyadarsini 30000

15) Explain about Object properties and methods in JavaScript?


 Properties: -
 Properties are the attributes of an object.
 For example the background color and the URL the document was retrieved from
are attributes of an HTML document.
 An objects properties are accessed by combining the objects name and its
property name as follows:
[Link]=”value”;
 In the examples below various properties of the document object are accessed
using the dot operator and assigned to a variable called result.
 Getting the properties of an Object:
 Result=[Link];
(result will contain the URL of the document).
 Result=[Link];
(result will contain the background color of the document)

24
 Setting the properties of an Object: It is also possible to assign values to some
object properties. So while it doesn’t make sense to be able to change the
location where the document came from, you can change the background color
of the document this way:
 [Link]=”#800080”;
 [Link]=”Orange”;
 Methods: -
 Methods are a way of asking an object to do something more complicated than
changing a property.
 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.
 Following is a simple example to show how to use the write() method of
document object to write any content on the document.
[Link](“JavaScript Expression”);
Here write() is a method (a function) that belongs to the document object. Calling
write() is like asking a document to append HTML to itself. The javascript
expression inside the round brackets will be evaluated and the result (whatever it
is) written out to the HTML page.
 Here are some more methods for the document object:
close(), open(), writeln(), getElementById(“ID”)
Example: -
<script type="text/javascript">
var book = new Object(); // Create the object
[Link] = "Web Technology"; // Assign properties to the object
[Link] = "Balu";
</script></head>
<body>
<script type="text/javascript">
[Link]("Book name is : " + [Link] + "<br>"); // Using write() Method
[Link]("Book author is : " + [Link] + "<br>"); // Using write() Method
</script></body>
Result: -
Book name is : Web Technology
Book name is : Balu

25
16) What is Regular Expression? Explain how to create Regular Expressions.
 Regular Expressions are very powerful tools for performing pattern matches.
 You can perform complex tasks that once required lengthy procedures with just a
few lines of code using regular expressions.
 A Regular Expressions is an object that describes a pattern of characters. Regular
Expressions are used to perform pattern-matching and search-and-replace
functions on text.
 Regular Expressions are implemented in two ways:
 Using Literal.
 Using RegExp() constructor.
 The literal syntax looks something like:
var RegularExpression= /pattern/attributes;
 The RegExp() constructor method looks like:
var RegularExpression= new RegExp(“pattern”,”attributes”);
pattern: - A string that specifies the pattern of the regular expression or another
regular expression.
attributes : - An optional string containing any of the "g", "i", and "m" attributes
that specify global, case-insensitive, and multiline matches, respectively.
 RegExp() Object methods: -
Regular expressions are used with the RegExp methods test() and exec() and with
the String methods match(), replace(), search(), and split().
 test() : A RegExp method that tests for a match in a string. It returns true or
false. The test() method syntax is : [Link](str);
 exec() : A RegExp method that executes a search for a match in a string. It
returns an array of information or null on a mismatch.
 match() : A String method that executes a search for a match in a string. It
returns an array of information or null on a mismatch.
 search() : A String method that tests for a match in a string. It returns the
index of the match, or -1 if the search fails.
 replace() : A String method that executes a search for a match in a string,
and replaces the matched substring with a replacement substring.
 split() : A String method that uses a regular expression or a fixed string to
break a string into an array of substrings.
Example:
<html>
<head>
<title>JavaScript RegularExpressions</title>
</head>
<body>
<script type="text/javascript">
var str = "Javascript is an interesting scripting language";

26
var rem = new RegExp( "script", "g" );
var result = [Link](str);
[Link]("Test 1 - returned value is : " + result);
rem = new RegExp( "pushing", "g" );
var result = [Link](str);
[Link]("<br />Test 2 - returned value is : " + result);
</script>
</body>
</html>
Result:
Test 1 - returned value is : script
Test 2 - returned value is : null

17) What is Exception? Explain Exception handling in JavaScript.


 Run time error handling is vitally important in all programs. Many object oriented
programming languages provide a mechanism for dealing with general classes of
error. This mechanism is called exception handling.
 An Exception in object based programming is an object, created by dynamically at
run time, which encapsulates an error and some information about it.
 For instance all incorrect input might be described by UserInputException objects.
 Using Exceptions need two new pieces of the JavaScript language.
The Throw statement: -
 The throw statement allows you to create an exception. If you use this statement
together with the try…catch statement, you can control program flow and
generate accurate error message.
Syntax: Throw (Exception);
The try…catch…finally statement: -
 The try statement allows you to define a block of code to be tested for errors
while it is being executed.
 The catch statement allows you to define a block of code to be executed, if an
error occurs in the try block.
 The finally statement lets you execute code, after try and catch, regardless of the
result.
Syntax:
try {
Block of code to try
}
catch(err) {
Block of code to handle errors
}
finally {

27
Block of code to be executed regardless of the try / catch result
}
Example:
<html>
<head>
<script type="text/javascript">
function myFunc()
{
var a = 100;
var b = 0;
try{
if ( b == 0 )
{
throw( "Divide by zero error." );
}
else
{
var c = a / b;
}
}
catch ( e )
{
alert("Error: " + e );
}
}
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="Click Me" onclick="myFunc();" />
</form>
</body>
</html>

18) Write about Regular Expression grammar?


 In regular expressions pattern match, the grammar rules are as follows:

Token Description
^ Match at the start of the input string
$ Match at the end of the input string

28
* Match 0 or more items
+ Match 1 or more items
? Match 0 or 1 time
a/b Match a or b
{n} Match the string n times
\d Match a digit
\D Match anything except for digits
\w Match anything alphanumeric characters or the underscore.
\W Match anything except alphanumeric characters or the underscore.
\s Match a whitespace character.
\S Match anything except for whitespace characters.
\t Matches horizontal characters.
[xyz] Match any one character enclosed in the character set ex: /[0-9]/
() Grouping characters together to create a clause.

19) What is data validation? Explain data validation with example?


 Data validation is the process of ensuring that user input is clean, correct, and
useful. Most often, the purpose of data validation is to ensure correct user input.
 Typical validation tasks are:
 Has the user filled in all required fields?
 Has the user entered a valid date?
 Has the user entered text in a numeric field?
 Validation can be defined by many different methods, and deployed in many
different ways.
 Server side validation is performed by a web server, after input has been sent to
the server.
 Client side validation is performed by a web browser, before input is sent to a web
server.
 Form validation generally performs two functions.
 Basic Validation − First of all, the form must be checked to make sure all the
mandatory fields are filled in. It would require just a loop through each field in the
form and check for data.
 Data Format Validation − Secondly, the data that is entered must be checked for
correct form and value. Your code must include appropriate logic to test
correctness of data.
Form Validation Example :
<html>
<head>
<title>Form Validation</title>
<script type="text/javascript">
function validate()

29
{
if( [Link] == "" )
{
alert( "Please provide your name!" );
[Link]();
return false;
}
if( [Link] == "" )
{
alert( "Please provide your Password!" );
[Link]();
return false;
}
return (true);
}
</script>
</head>
<body>
<form action="/action_page_post.php" name="f1"
onsubmit="return(validate());">
UserName: <input type="text" name="UserName" /><br><br>
Password: <input type="text" name="Password" ><br><br>
<input type="submit" value="Submit" />
</form>
</body></html>
 Result:

30
20) Explain how to open a new window in JavaScript?
 Web browsers are based around a different model in which each new window is
independent of the application from which it was launched.
 Majority of the JavaScript coding is based using windows.
 The application has a single global frame and when new windows are opened they
appear inside the frame.
 The application frame is said to be the parent of all of the internal frames.
 The following features are available in most browsers:
toolbar=1|0 : Specifies whether to display the toolbar in the new window.
location=1|0 : Specifies whether to display the address line in the new
window.
directories=1|0 : Specifies whether to display the Netscape directory buttons.
status=1|0: Specifies whether to display the browser status bar.
menubar=1|0 : Specifies whether to display the browser menu bar.
scrollbars=1|0 : Specifies whether the new window should have scrollbars.
resizable=1|0 : Specifies whether the new window is resizable.
width=pixels : Specifies the width of the new window.
height=pixels : Specifies the height of the new window.
Example:
<html>
<head>
<title>Opening New Window</title>
</head>
<script type="text/javascript">
function load()
{
var myWindow = [Link]("
[Link] "myWindow",
"location=1, status=1, scrollbars=1, width=500, height=300");
}
</script>
<body onload="load()">
<h1>JavaScript New window Opening</h1>
</body></html>
Result:

31
21) Explain about messages and confirmations (Dialog boxes or Pop-up boxes)
in JavaScript?
 JavaScript provides three built-in window types that can be used from application
code. These are useful when you need information from visitors to your site.
 For instance you may need them to click a confirmation button before submitting
information to your database.
 Three kinds of popup boxes created using JavaScript are:
 Alert box
 Confirm box
 Prompt box
1. Alert Box:
 The alert box is useful for alerting the users to something important.
 When a Javascript alert box triggered, a small box will pop up the text that is
specified in the Javascript code.
 The alert box pops up with an ok button which the user has to press to continue.
 Syntax: alert(“text message”);
Example:
<html>
<head>
<title> alert box Example</title>
</head>
<body>
<script type="text/javascript">
function display()
{
alert("This is an alert box");
}
</script>
<input type="button" value="click me!" onclick="display()"/>
</body>
</html>
Result:

32
2. Confirm box:
 The confirm method shows a dialog box that contains a message and an ok and
cancel button.
 If the user presses the ok button the confirm method returns true.
 If the user presses cancel button return false.
 Syntax: confirm(“text message”);
 Example:
<html>
<head><title> Confirm box Example</title>
</head>
<body>
<script type="text/javascript">
var x= confirm("if you do hardwork");
if(x)
alert(" You will get good marks ");
else
alert(" You will get less marks ");
</script></body></html>
Result:

3. Prompt box:
 The prompt method shows a dialog box with a message, a text entry field, an ok
button, and a cancel button.
 If the user presses ok the text in the test entry field is returned as a string.
 If the user presses cancel the null value is returned by the prompt method.

33
 Prompt takes two parameters. The first is a message (or instructions) and the
second default text that will appear in the text entry field.
 Syntax: prompt(“ Text message”, “Default value”);
 Example:
<html>
<head><title> Prompt box Example</title>
</head>
<body>
<script type="text/javascript">
var age= prompt("Enter your age","18");
if(age>=18)
alert(" you are eligible to vote ");
else
alert(" you are not eligible to vote ");
</script></body></html>
Result:

22) What is an Event? Explain about Events in JavaScript?


 JavaScript's interaction with HTML is handled through events that occur when the
user or the browser manipulates a page.
 When the page loads, it is called an event. When the user clicks a button, that click
too is an event. Other examples include events like pressing any key, closing a
window, resizing a window, etc.
 Events are a part of the Document Object Model (DOM) Level 3 and every HTML
element contains a set of events which can trigger JavaScript Code.
 The event handlers are not case-sensitive; onload, onLoad and ONLOAD all
represent exactly the same thing.
 Event handlers are JavaScript functions which is associated with an HTML element
as part of its definition in the HTML source code.
<element attributes event=”handler”>

Javascript Events: -

34
Event Description
onclick The event occurs when the user clicks on an element
ondblclick The event occurs when the user double-clicks on an element
onmouseover The event occurs when the pointer is moved onto an element, or
onto one of its children
onmouseout The event occurs when a user moves the mouse pointer out of an
element, or out of one of its children
onmouseup The event occurs when a user releases a mouse button over an
element
onmousedown The event occurs when the user presses a mouse button over an
element
onload The event occurs when an object has loaded
onunload The event occurs once a page has unloaded (for <body>)
onsubmit The event occurs when a form is submitted
onfocus The event occurs when an element gets focus
onselect The event occurs after the user selects some text (for <input> and
<textarea>)
onkeypress The event occurs when the user presses a key

Example:
<html>
<head>
<title>Event Handling</title>
</head>
<body onLoad="ShowLoaded()" onunload="SayGoodbye()">
<h1> handling events</h1>
<a href="#" onMouseOver="Mouse()"> A Hyperlink</a><br >
<form>
<input type="button" value="ClickMe!"
onclick="Clicked()"onmouseover="Mouse">
</form>
<script language="javascript">
function ShowLoaded()
{
alert("The page has loaded");
}
function SayGoodbye()
{
alert("Goodbye, thank u for visiting");
}

35
function Clicked()
{
alert("you clicked the button");
}
function Mouse()
{
alert("the mouse is over the link");
}
</script></body></html>

23) Explain about Built-in Objects in JavaScript?


 JavaScript offers a set of built-in objects that provide information about the
currently loaded web page and its content, as well as the current session of
navigator. These objects provide methods for working with their properties.
 There are different types of built-in objects according to their priority level wise
are:
1. Document Object: - A document is a web page that is being either displayed or
created. The document has a number of properties that can be accessed by
JavaScript programs and used to manipulate the content of the page.
Syntax: -
[Link]; (or) [Link](parameters);
Properties: - The following properties of document object are:
bgcolor, fgcolor, url, title, alinkcolor, linkcolor, lastmodified, form, image, link and
anchor.
Methods: - The following methods of document object are:

36
close(), getElementById(“ID”), open(), write(“string”), writeln(“string”).

2. Window Object: - The window object represents an open window in a browser.


If a document contain frames (<iframe> tags), the browser creates one window
object for the HTML document, and one additional window object for each frame.
The browser window is a mutable object that can be addressed by JavaScript code.
Syntax: -
var newwindow=[Link](“url”, “windowName”,”windowFeatures”);
Properties: - The following properties of window object are:
status, document, frames, length, location, top, left,history, closed, opener and name.
Methods: - The following methods of window object are:
alert(), prompt(),open(), confirm(),close(), focus(), setTimeout(), blur(), clearTimeout() and
scroll(x, y).

3. Browser (Navigator) object: - The browser object is a JavaScript object and can be
queried from within your code. The browser object is actually called the navigator
object.
Syntax: -
[Link]; (or) [Link](parameters);
Properties: - The following properties of navigator object are:
appCodeName, appname, appVersion, language, userAgent, plugins, cookieEnabled and
platform.
Methods: - The following methods of navigator object are:
javaEnabled(), taintEnabled().

4. Date Object: - The JavaScript date object can be used to get year, month and day. You
can display a timer on the webpage by the help of JavaScript date object.
You can use different Date constructors to create date object. It provides methods
to get and set day, month, year, hour, minute and seconds. You can use 4 variant of
Date constructor to create date object.
1. Date()
2. Date(milliseconds)
3. Date(dateString)
4. Date(year, month, day, hours, minutes, seconds, milliseconds)
Syntax:
var today=new Date();
Properties: - The following properties of date object are:
Constructor and prototype.
Methods: - The following methods of Date object are:
date(), getDate(), getDay(), getMonth(), getYear(), setTime(), setDate(), setMonth()
and setHours(),…etc,.

37
5. History Object: - The JavaScript historyobject represents an array of URLs visited by
the user. By using this object, you can load previous, forward or any particular page.
Syntax:
[Link]; (or) [Link]();
Properties: - The following properties of history object are:
length, next, previous and current.
Methods: - The following methods of history object are:
forward(), back() and go().

6. Form Object: - The JavaScript Form Object is a property of the document object. This
corresponds to an HTML input from constructed with the FORM tag. A form can be
submitted by calling the JavaScript submit method or clicking the form submit
button. The Form object represents an HTML <form> element.
Syntax:
var x = [Link]("myForm");
Properties: - The following properties of form object are: action, target, name,
method, validate, onsubmit, length and encoding.
Methods: - The following methods of form object are:
reset() and submit().

24) Explain about document object in JavaScript?


 Document Object: - A document is a web page that is being either displayed or
created. The document has a number of properties that can be accessed by
JavaScript programs and used to manipulate the content of the page .
Syntax: -
[Link]; (or) [Link](parameters);
 Properties: - The following properties of document object are:
bgcolor, fgcolor, url, title, alinkcolor, linkcolor, lastmodified, form, image, location,
link and anchor, … etc.
 Methods: -
write("string"): It writes the given string on the doucment.
writeln("string"): It writes the given string on the doucment with newline character
at the end.
getElementById(): Itreturns the element having the given id value.
Open(): Opens a document stream in preparation for [Link]() to write to it
close(): Closes a document stream opened using [Link]().
 Example:
<script language=”javascript”>
[Link](“[Link] = “+[Link]+”<br”>);
[Link](“[Link] = “+[Link]+”<br”>);

38
[Link](“[Link] = “+[Link]+”<br”>);
[Link](“[Link] = “+[Link]+”<br”>);
[Link](“[Link] = “+[Link]+”<br”>);
</script>

25) Explain about window object in JavaScript?


 Window Object: - The window object represents an open window in a browser.
If a document contain frames (<iframe> tags), the browser creates one window
object for the HTML document, and one additional window object for each frame.
The browser window is a mutable object that can be addressed by JavaScript code.
 Syntax: -
var newwindow=[Link](“url”, “windowName”,”windowFeatures”);
 Properties: - The following properties of window object are:
status, document, frames, length, location, top, left,history, closed, opener and name.
 Methods: -
alert(): It displays the alert box containing message with ok button.
confirm() : It displays the confirm dialog box containing message with ok and
cancel button.
prompt(): It displays a dialog box to get input from the user.
open(): It opens the new window.
close(): It closes the current window.
setTimeout(): It performs action after specified time like calling function,
evaluating expressions etc.
focus(): It is used to bring a window in focus.
blur(): It is used to remove focus from the window.
Example 1:
It displays alert dialog box. It has message and ok button.
<script type="text/javascript">
function msg(){
alert("Hello Alert Box");
}
</script>
<input type="button" value="click" onclick="msg()"/>

Example 2:
It displays the confirm dialog box. It has message with ok and cancel buttons.
<script type="text/javascript">
function msg(){
var v= confirm("Are u sure?");
if(v==true){
alert("ok");

39
}
else{
alert("cancel");
}
}
</script>
<input type="button" value="delete record" onclick="msg()"/>
Example 3:
It displays prompt dialog box for input. It has message and text field.
<script type="text/javascript">
function msg(){
var name= prompt("Who are you?");
alert("I am "+name);
}
</script>
<input type="button" value="click" onclick="msg()"/>

26) Explain about date object in JavaScript?


 The JavaScript date object can be used to get year, month and day. You can
display a timer on the webpage by the help of JavaScript date object.
You can use different Date constructors to create date object. It provides methods
to get and set day, month, year, hour, minute and seconds. You can use 4 variant of
Date constructor to create date object.
1. Date()
2. Date(milliseconds)
3. Date(dateString)
4. Date(year, month, day, hours, minutes, seconds, milliseconds)
 Syntax:
var today=new Date();
 Properties: - The following properties of date object are:
Constructor and prototype.
Methods: -
getFullYear(): It returns the year in 4 digit e.g. 2015. It is a new method and
suggested than getYear() which is now deprecated.
getMonth(): It returns the month in 2 digit from 0 to 11. So it is better to use
getMonth()+1 in your code.
getDate(): It returns the date in 1 or 2 digit from 1 to 31.
getDay(): Itreturns the day of week in 1 digit from 0 to 6.
getHours(): It returns all the elements having the given name value.
getMinutes(): It returns all the elements having the given class name.
getSeconds(): It returns all the elements having the given class name.

40
getMilliseconds(): It returns all the elements having the given tag name.
Example:
<script language=”javascript”>
var date=new Date();
var day=[Link]();
var month=[Link]()+1;
var year=[Link]();
[Link]("<br>Date is: "+day+"/"+month+"/"+year);
[Link](“<br>Hours is: “ + [Link]());
[Link](“<br>minuts is: “ + [Link]());
</script>

27) Explain about browser object in JavaScript?


 Browser (Navigator) object: - The browser object is a JavaScript object and can be
queried from within your code. The browser object is actually called the navigator
object.
 Syntax: -
[Link]; (or) [Link](parameters);
 Properties: - The following properties of navigator object are:
appCodeName, appname, appVersion, language, userAgent, plugins, cookieEnabled and
platform.
 Methods: -
javaEnabled(): checks if java is enabled.
taintEnabled(): checks if taint is enabled. It is deprecated since JavaScript 1.2.
Example:
<script>
[Link]("<br/>[Link]: "+[Link]);
[Link]("<br/>[Link]: "+[Link]);
[Link]("<br/>[Link]: "+[Link]);
[Link]("<br/>[Link]: "+[Link]);
[Link]("<br/>[Link]: "+[Link]);
[Link]("<br/>[Link]: "+[Link]);
[Link]("<br/>[Link]: "+[Link]);
</script>
Result:
[Link]: Mozilla
[Link]: Netscape
[Link]: 5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36
(KHTML, like Gecko) Chrome/37.0.2062.124 Safari/537.36
[Link]: true
[Link]: en-US

41
[Link]: Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36
(KHTML, like Gecko) Chrome/37.0.2062.124 Safari/537.36
[Link]: Win32
[Link]: true

28) Explain about status bar in JavaScript?


 The status bar usually displays helpful information about the operation of the
browser.
 Some web developers like to use browsers status bar as part of the site.
 Text strings can be displayed in the status bar but should be used with care.
 Finally anything that can be done in the status bar can be done more interestingly
using DHTML techniques.
Example:
<html>
<head><title>The Status bar</title>
<script language="javascript">
{
[Link]="Hello Computer Science Students";
}
</script></head>
<body>
<h1> Hi Guys ...Have you seen status bar message</h1>
</body></html>
Result:

29) Explain how to write different frames in JavaScript?


 Once frames and JavaScript are combined on the same page, a site can begin to
develop some interesting interactive aspects.
 Often developing a site with links in one frame and output in another provides easy
movement through data.
 One popular use of frames and JavaScript is a color picker. The simple color picker
that I’m going to build here. It was has two frames.
 The upper frame contains a form which is used for data gathering.

42
 The lower frame shows the result of the color selections but has been created by
JavaScript code.
 This application is run totally on the client side.
 The frameset:
The whole page is built around a simple frameset. When the page is initially loaded
it displays the form in the upper window (top) And an empty html page in the
lower window (bottom).
Example:
<html><head>
<title> Addition of two Numbers</title>
</head>
<frameset rows="50%,*">
<frame name="top" src="[Link]">
<frame name="bot" src="[Link]">
</frameset>
</html>
Here is the code for empty frame ([Link]):
<html>
<head>
<title>Empty Frame</title>
</head>
<body>
</body></html>
 The Upper Frame ([Link]):
<html>
<head>
<script language="javascript">
function Addition()
{
var t=[Link][0].elements;
var b=[Link]['bot'].document;
var a1=[Link];
var a2=[Link];
var c=parseInt(a1)+parseInt(a2);
[Link]();
[Link]("The Result is:"+c);
[Link]();
}
</script>
</head>
<body bgcolor="pink" text="green">

43
<h1 align=center> Addition of Two numbers</h1>
<form ><center>
Enter the value of a : <input type="text" name="n1"><br>
Enter The value of b : <input type="text" name="n2"><br>
<input type="button" value="Add" onclick="Addition();">
<input type="button" value="Reset It">
</form></body></html>
Result:

30) Explain about Rollover buttons?


 The most common usage of dynamic HTML is the image rollover.
 The technique is used to give visual feedback about the location of the mouse
cursor by changing the images on the page as the mouse over them.
 This is a highly effective technique, especially where images are used as the
hyperlinks in a menu, or where an image map is being used.
 Rollover is far simpler because it uses two image files which it swaps between as
the mouse is moved.
Example:
<html>
<head>
<title>Image Rollover</title>
</head>
<body>
<div align="center">
<h1 onmouseover="[Link]='red'"
onmouseout="[Link]='green'">
Welcome to Rollover Images
</h1>
<img src="[Link]" onmouseover="[Link]='[Link]'"
onmouseout="[Link]='[Link]'" width="600" height="400" border="2">
</div>
</body></html>

44
Result:

31) Explain about Moving Images in JavaScript?


 Unlike the rollover which takes some understanding, moving images around the
screen is pretty simple. In fact this isn’t a moving image at all, that’s the effect.
 Its more user-friendly if the images only move for a restricted amount of time such
as when the page is first loaded or when the user specifically trigger the event.
 The example flies an image from left of the screen to the center of the screen.
Images can move around repeatedly but doing so takes up processor cycles.
Example:
<html>
<head>
<script type="text/javascript">
var i=1;
function starttimer()
{
[Link]('myimage').[Link]="relative";
[Link]('myimage').[Link]=+i;
i++;
timer=setTimeout("starttimer()",10);
}
</script>
</head>
<body>
<h1>Image is moving right when you click button</h1>
<input type="button" value="click me!" onclick="starttimer()">
<img id="myimage" src="[Link]" width="400" height="250" />
</body>
</html>
Result:

45
46

You might also like