IT Client-Side Scripting Guide
IT Client-Side Scripting Guide
(NBA Accredited)
Prepared By
Yogita Khandagale
1
Client-Side Scripting Language
(22519)
Semester - V
2
Institute Vision and Mission
Vision
Mission
Vision
Mission
Encouraging academic excellence and a passion for learning through the use
of learner-oriented teaching methodologies.
3
Program Outcomes (POs)
Basic knowledge: Apply knowledge of basic mathematics, science and
basic engineering to solve the problems related to application of
computers and communication services in
1
storing, manipulating and transmitting data, often in the context of a
business or other
enterprise.
Discipline knowledge: Apply Information Technology knowledge to
2 solve broad-based Information Technology related problems.
Experiments and practice: Plan to perform experiments, practices and
3 to use the results to solve Information Technology related problems.
Engineering Tools: Apply appropriate Information Technology related
4 techniques/tools with an understanding of the limitations.
The engineer and society: Assess societal, health, safety and legal
5 issues and the consequent responsibilities relevant to practice in the field
of Information technology.
Environment and sustainability: Apply Information Technology
6 related engineering solutions for sustainable development practices in
environmental contexts.
Ethics: Apply ethical principles for commitment to professional ethics,
7 responsibilities and norms of practice in the field of Information
Technology.
Individual and team work: Function effectively as a leader and team
8 member in diverse/multidisciplinary teams.
9 Communication: Communicate effectively in oral and written form. .
Life-long learning: Engage in independent and life-long learning along
10 with the technological changes in the IT and allied industry.
4
5
Vidyalankar Polytechnic
Certificate
Mr/Ms…………………………………………………………………………
Vidyalankar Polytechnic (Institute Code: 0568 / 1090) has completed the Term
Work satisfactory in Course Client Side Scripting Language (22519) for the
Academic Year …………………….………………..
6
List of Experiments and Progressive Assessment for Term Work
Name of Candidate:…………………………………………..…………………………………..
Assessment Scheme
Performance Indicators (15 Marks) Weightage
Process related (15 marks) 30 %
1 Logic formation 10 %
2 Debugging Ability 10 %
3 Follow ethical practices 10 %
Product related (35 Marks) 70 %
4 Expected Output 30 %
5 Timely Submission 30 %
6 Answer to sample Questions 10 %
100 %
Experiment No: 01
Write simple Java Script with HTML for arithmetic expression evaluation
and message printing.
8
Resources required:
Hardware Software
Computer 1)Notepad editor
System 2)Any Web Browser
Proposition-2: Expressions
Many JavaScript statements contain a mathematical expression that tells the
browser to perform a mathematical operation.
9
"hello" // A string literal
/pattern/ // A regular expression literal
JavaScript syntax for number literals was covered in Numbers. String literals were
documented in Text. Some of JavaScript’s reserved words are primary
expressions:
true // Evalutes to the boolean true value
false // Evaluates to the boolean false value
null // Evaluates to the null value
this // Evaluates to the "current" object
Another type of primary expression is the bare variable reference:
i // Evaluates to the value of the variable i.
sum // Evaluates to the value of the variable sum.
undefined // undefined is a global variable, not a keyword like null
When any identifier appears by itself in a program, JavaScript assumes it is a
variable and looks up its value. If no variable with that name exists, the
expression evaluates to the undefined value.
Parts of an Expression
A mathematical expression consists of two parts: operands and operators.
An operand is the value. An operator is the symbol that tells the browser how to
evaluate the mathematical expression.
The operands are the numbers in the following mathematical expression.
The addition symbol (+) is the operator. The browser evaluates this
mathematical expression by adding the value on the right side of the operator to
the value on the left side of the operator:
1+1
10
2) Logical Operators: Logical operators are used to combine two logical
expressions into one expression. A logical expression is an expression that
evaluates to either true or false. Logical expressions are used in JavaScript to
make decisions.
Operator Description Example
&& (Logical If both the operands are non-zero, (A && B) is true.
AND) then the condition becomes true.
|| (Logical OR) If any of the two operands are non- (A || B) is true.
zero, then the condition becomes
true.
! (Logical NOT) Reverses the logical state of its (A && B) is false.
operand. If a condition is true, then
the Logical NOT operator will make it
false.
3) Assignment Operators: The assignment operator assigns the value from the
right side of the operator to the variable on the left side of the operator.
Operat Description Example
or
= Assign 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
+= Add value then It adds the right operand to the left operand
assign and assigns the result to the left operand.
Ex: C += A is equivalent to C = C + A
-= Subtract value then It subtracts the right operand from the left
assign operand and assigns the result to the left
operand.
Ex: C -= A is equivalent to C = C - A
*= Multiply value the It multiplies the right operand with the left
assign operand and assigns the result to the left
operand.
Ex: C *= A is equivalent to C = C * A
/= Divide value then It divides the left operand with the right
assign operand and assigns the result to the left
operand.
Ex: C /= A is equivalent to C = C / A
%= Modulus value then It takes modulus using two operands and
assign assigns the result to the left operand.
Ex: C %= A is equivalent to C = C % A
> Greater than Checks if the value of the left operand is greater
than the value of the right operand, if yes, then the
condition becomes true.
Ex: (A > B) is not true.
< Less than Checks if the value of the left operand is less than
the value of the right operand, if yes, then the
condition becomes true.
Ex: (A < B) is true.
>= Greater than Checks if the value of the left operand is greater
or equal to than or equal to the value of the right operand, if
yes, then the condition becomes true.
Ex: (A >= B) is not true.
<= Less than or Checks if the value of the left operand is less than or
equal to equal to the value of the right operand, if yes, then
the condition becomes true.
Ex: (A <= B) is true.
5) Conditional Operators:
The conditional operator tells the browser to take a specific action after
evaluating an expression. The conditional operator has three parts: The first part
is a logical expression, which you’ll recall is an expression that evaluates to
either true or false. The second part is the action the browser must take if the
expression is true. The third part is the action the browser must take if the
expression is false. The first and second parts of the conditional operator are
separated by a question mark (?). The second part and the third parts are
separated by a colon (:).
Operators Description
Expression? value1 : value2 If expression is true, then use value1;
otherwise, use value2
delete Delete the property of an object.
new Create an object.
typeof Returns the type of an object.
6) Bitwise Operators:
Bitwise operators perform their operations on such binary representations, but
they return standard JavaScript numerical values.
Operat Name Description
or
& AND Sets each bit to 1 if both bits are 1
| OR Sets each bit to 1 if one of two bits is 1
^ XOR Sets each bit to 1 if only one of two bits is 1
~ NOT Inverts all the bits
<< Zero filled left Shifts left by pushing zeros in from the right and let
12
shift the leftmost bits fall off
>> Signed right Shifts right by pushing copies of the leftmost bit in
shift from the left, and let the rightmost bits fall off
>>> Zero fill right Shifts right by pushing zeros in from the left, and let
shift the rightmost bits fall off
Example:
Operation Result Same as Result
5&1 1 0101 & 0001 0001
5|1 5 0101 | 0001 0101
~5 10 ~0101 1010
5 << 1 10 0101 << 1 1010
5^1 4 0101 ^ 0001 0100
5 >> 1 2 0101 >> 1 0010
5 >>> 1 2 0101 >>> 1 0010
Alert Dialog Box: An alert dialog box pops on the screen to display a message
and stays on the screen until someone clicks the OK button that appears in the
dialog box. You display an alert dialog box by calling the alert function and
passing it the text that you want to be displayed.
Example:
<html>
<body>
<script type="text/javascript">
var a = 33;
var b = 10;
var c = "Test";
result = a + b;
alert(result);
result = a - b;
alert(result);
result = a * b;
alert(result);
result = a / b;
alert(result);
</script>
</body>
</html>
Student Activity:
1. List the application of JavaScript.
2. List the features of JavaScript.
3. How to create an object in JavaScript?
4. Explain variable in javascript.
5. Differentiate between prompt () and alert () methods.
6. Write a program to execute the conditional operator(ternary) in JavaScript.
7. Write a program to perform arithmetic operations by using
13
a) prompt() //accepts the inputs from user
b) variable assignment // var a=10; var b= 20;
c) function definition
8. State the use of property getter and setter in JavaScript.
https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_state_forin
https://www.tutorialspoint.com/javascript/javascript_forin_loop.htm
https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_nav_platform
https://www.w3schools.com/jsref/prop_nav_platform.asp
Experiment No: 02
Resources required:
Hardware Software
Computer 1)Notepad editor
System 2)Any Web Browser
Practical Significance:
Theoretical Background:
a) if statement
14
The if statement is one of the most powerful statements that you’ll use in
JavaScript, because it enables you to have the browser execute some statements
only if certain conditions are met while your JavaScript is running.
Syntax:
if (conditional expression)
{
//This is where the code block appears.
}
b) if-else Statement:
If...else statement first checks the condition. If condition is true, then true
statement block is executed. If condition is false, then false statement block is
executed.
Syntax:
if (condition)
{
// if TRUE then execute this code
}
else
{
// if FALSE then execute this code
}
if...else if Statement
The if...else if statement tells the browser, “If the condition is true, then execute
these statements, else evaluate another condition. If the other condition is true,
then execute these other statements.”
Syntax:
if (conditional expression)
{ //Place statements here.
}
else if (conditional expression)
{ //Place statements here. }
switch...case Statement
A switch...case statement tells the browser to compare a switch value with a
series of case values. If the switch value matches a case value, then the browser
executes statements that are placed beneath the case value.
Syntax:
switch (value)
{
case value1:
//Place statements here.
break;
case value2:
//Place statements here.
break;
default:
15
//Place statements here.
}
Loop Statement
1. For Loop: The for loop tells the browser to execute statements within the for
loop until a condition statement returns false. The browser then continues by
executing the statement or statements below the for loop until the test condition
is false.
syntax:
for ( initializer; conditional expression ; post loop statements)
{
//Place statements here.
}
For...in Loop:
The for...in statement iterates over the enumerable properties of an object. For
each distinct property, statements can be executed.
Syntax:
For (variable in object)
{
statement or block to execute
…
}
While Loop:
The while loop tells the browser to execute one or more statements continually
as long as a condition defined in the while loop is true.
Syntax:
while (conditional expression)
{
//Place statements here.
}
do...while Loop:
The do...while loop operates similarly to the while loop, except that statements
within the code block execute at least once, because the browser doesn’t
evaluate the conditional expression condition until the end of the code block.
Syntax:
do
{
// statements.
16
} while (conditional expression)
<html>
<head>
<title>Practical 2</title>
</head>
<body>
<h1>If statement</h1>
<script>
var a=10;
var b=20;
document.write("a="+a+"<br>");
document.write("b="+b+"<br>");
if(a > b){
document.write("a is greater than b");
}
if(a < b){
document.write("a is smaller than b");
}
</script>
</title>
</html>
Output:
a is smaller than b
17
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
}
document.write("Today is " + day);
</script>
</body>
</html>
Exercise:
1. Write a JavaScript program to print the factorial of a given number.
2. Write a JavaScript program to print the Fibonacci series till 10 number.
3. Write a code to find out whether the year is leap year or not.
18
Experiment No: 03
Resources required:
Hardware Software
Computer Notepad Editor
System Any web browser
Practical Significance:
An array is very similar to a variable in that an array tells the browser to reserve
a place in memory that can be used to store information. An array can comprise
one or multiple elements. Each element is like a variable in that an array element
refers to a memory location where information can be temporarily stored.
Theoretical Background:
An array is very similar to a variable in that an array tells the browser to reserve
a place in memory that can be used to store information. An array can comprise
one or multiple elements. Each element is like a variable in that an array element
refers to a memory location where information can be temporarily stored. An
array is identified by a unique name, similar to the name of a variable. A number
called an index identify es an array element. The combination of the array name
and an index is nearly the same as a variable name. In your JavaScript, you use
both the array name and the index to specify a particular memory location.
Declaring an Array
This declaration statement has five parts: the first part is the var syntax; the
second part is the array name, which you create; the third part is the assignment
operator; the fourth part is the new operator;
and the fifth part is the Array() constructor. All these parts are shown here:
Initializing an Array
In the real world, an array usually has more than one array element, with each
element having its own value. Therefore, you’ll fi nd yourself having to initialize
the array with more than one value.
19
How Many Elements Are in the Array?
The length property of the array object contains the number of elements
contained in the array.
Exercise:
1. Write the output for following:
<script> <script>
var car= new Array(); var car= new Array();
car.push("Mercedes"); car.push("Mercedes");
car.push("Ferrari"); car.push("Ferrari");
car.push("Lamborghini"); car.push("Lamborghini");
car.push("BMW"); car.push("BMW");
car.push("Bugatti"); car.sort();
for(var i=0; i<car.length; i++){ for(var i=0; i<car.length; i++){
document.write(car[i]+"<br>"); document.write(car[i]+"<br>");
} }
</script> </script>
20
Experiment No: 04
Resources required:
Hardware Software
Computer Notepad Editor
System Any web browser
Practical Significance:
A function as part of your JavaScript that has a name and contains one or more
statements. You name the function and write the statement(s) that are contained
within the function. You then use the name of the function elsewhere in your
JavaScript whenever you want the browser to execute those statements. A
function can be called from anywhere in the JavaScript fi le or in the HTML
document.
Theoretical Background:
Defining a Function
A function definition consists of four parts: the name, parentheses, a code block,
and an optional return keyword.
It is called Salary() and tells the browser the steps that are necessary to give you
a raise in pay (at least on
paper). This function contains all the values needed to calculate your new salary;
therefore, no argument is needed:
function Salary()
{
var salary = 50000 * 1.5
alert("Your new salary is " + salary)
}
Adding Arguments
An argument is one or more variables that are declared within the parentheses of
a function definition.
function Salary(OldSalary)
{
var Salary = OldSalary * 1.25
21
alert("Your new salary is " + Salary)
}
Exercise:
Calculate the factorial of a number by
1)calling function without argument
2)calling function with argument.
Experiment No: 05
Develop a JavaScript to implement strings.
Resources required:
Hardware Software
Computer Notepad Editor
System Any web browser
22
Theoretical Background:
The JavaScript string is an object that represents a sequence of characters.
There are 2 ways to create string in JavaScript
1. By string literal
2. By string object (using new keyword)
1) By string literal
The string literal is created using double quotes. The syntax of creating string
using string literal is given below:
The syntax of creating string object using new keyword is given below:
Methods Description
charAt() It provides the char value present at the specified index.
substr() It is used to fetch the part of the given string on the basis of
the specified starting position and length.
23
substring() It is used to fetch the part of the given string on the basis of
the specified index.
split() It splits a string into substring array, then returns that newly
created array.
trim() It trims the white space from the left and right side of the
Exercise:
1.Write a program to check whether the given staring is palindrome or not?
2.Write a program to count the number of vowels into the string?
24
Experiment No: 06
Resources required:
Hardware Software
Computer 1)Notepad editor
System 2)Any Web Browser
Practical Significance:
It seems that no matter what web site you visit these days, you are asked to fill
out a form—be it an order form, subscription form, membership form, financial
form, survey, and the list goes on. Although forms may seem invasive, prying
into our private affairs, forms are the only practical way to collect information
that is necessary to conduct business on the Internet.
Theoretical Background:
Forms are created using HTML form elements such as buttons and check boxes.
Forms used by commercial web sites also interact by using JavaScript. A
JavaScript is used for a variety of purposes, including data validation and for
dynamically interacting with elements of a form. A form is a section of an HTML
document that contains elements such as radio buttons, text boxes, check boxes,
and option lists. HTML form elements are also known as controls. Elements are
used as an efficient way for a user to enter information into a form. Forms are
used for all kinds of purposes. In a business, forms are used to gather order
information from a customer. Forms are also used for online surveys. Teachers
use forms for online tests. Information entered into a form is sent to the web
server for processing when the user clicks a submit button. The program that
processes the form is called a Common Gateway Interface (CGI)
program.
Program:
<html>
<head>
<title>Registration Form</title>
</head>
<body>
<form name="MyForm" method="post" action="">
<h2>Register your account</h2>
Enter your Firstname: <input type="text" name="FName"
id="FName"><br><br>
Enter Your Lastname: <input type="text" name="LName"
id="LName"><br><br>
26
Enter your Username: <input type="text" name="UName"
id="UName"><br><br>
Enter your Password: <input type="password" name="pass"
id="pass"><br><br>
Enter you Gender: <input type="radio" name="Gender" id="Male">Male
<input type="radio" name="Gender" id="Female">Female<br><br>
Your Hobbies? <input type="checkbox" name="Hobbies" id="Cricket">Cricket
<input type="checkbox" name="Football" id="Cricket">Football<br><br>
Select your city: <select name="City">
<option name="Mumbai">Mumbai</option>
<option name="Pune">Pune</option>
<option name="Nagpur">Nagpur</option>
<option name="Ahmedabad">Ahmedabad</option>
</select><br><br>
<input type="submit"> <input type="reset">
</form>
</body>
</html>
Exercise:
1)Write a program to create the registration form for creating gmail account.
27
Experiment No: 07
Resources required:
Hardware Software
Computer 1)Notepad editor
System 2)Any Web Browser
Practical Significance:
A JavaScript executes in response to an event that occurs while a form is
displayed on the screen. An event is something the user does to the form, such
as clicking a button, selecting a radio button, or moving the cursor away from an
element on the form. The browser also fires events when the page finishes
loading from the server.
Theoretical Background
Practical Example
<html>
<head>
<title>Mouse Events</title>
</head>
<body>
<h2>Following are the Mouse Events</h2>
<input type="button" name="btn1" onmouseover="alert('You pointed your
mouse on the Button');" value="Hover mouse on me"><br><br>
<input type="button" name="btn2" onmouseout="alert('You pointed your
mouse out of the Button');" value="Hover out of me"><br><br>
<input type="button" name="btn3" onclick="alert('You left-clicked on the
Button');" value="Left-click on me"><br><br>
<input type="button" name="btn4" oncontextmenu="alert('You right-clicked on
the Button');" value="Right-click on me"><br><br>
</body>
</html>
Exercise:
1) Write a program for changing the option list dynamically.
2) Develop a program for as we enter the firstname and lastname , email is
automatically generated.
29
30
Experiment No: 08
Resources required:
Hardware Software
Computer 1)Notepad editor
System 2)Any Web Browser
Practical Significance:
A JavaScript executes in response to an event that occurs while a form is
displayed on the screen. An event is something the user does to the form, such
as clicking a button, selecting a radio button, or moving the cursor away from an
element on the form. The browser also fires events when the page finishes
loading from the server.
Theoretical Background
When you interact with the keyboard, the keyboard events are fired. There are
three main keyboard events:
keydown – fires when you press a key on the keyboard and it fires repeatedly
while you holding down the key.
keypress – fires when you press a character keyboard like a,b, or c, not the left
arrow key, home, or end keyboard, … The keypress also fires repeatedly while
you hold down the key on the keyboard.
The keyboard events typically fire on the text box, through all elements support
them.
When you press a character key once on the keyboard, three keyboard events
are fired in the following order:
keydown
keypress
keyup
Both keydown and keypress events are fired before any change made to the text
box, whereas the keyup event fires after the changes have made to the text box.
If you hold down a character key, the keydown and keypress are fired repeatedly
until you release the key.
31
When you press a non-character key, the keydown event is fired first followed by
the keyup event. If you hold down the non-character key, the keydown is fired
repeatedly until you release the key.
First, select the element on which the keyboard event will fire. Typically, it is a
text box.
Suppose that you have the following text box with the id message:
Example:
<html>
<head><title>Javascript Form Events : onClick Event</title>
<script>
function Japan(){
alert("konnichiwa");
}
function India(){
alert("namaste");
}
function Germany(){
alert("Guten Tag");
}
</script>
32
</head>
<body>
<p>Hello in Different Countries</p>
<form>
<input type="button" value="Japan"
onclick ="Japan()" />
</body>
</html>
Practice Questions
a. onblur
b. onfocus
c. onselect
d. onchange
a. onblur
b. onfocus
c. onselect
d. onchange
a. True
b. False
Exercise:
33
1)Write a program to demonstrate the use of onchange event.
34
Experiment No: 09
Resources required:
Hardware Software
Computer 1)Notepad editor
System 2)Any Web Browser
Practical Significance:
A JavaScript has a special set of functions called intrinsic functions that mimic
actions of the submit button and reset button of a form.
Theoretical Background
The HTML <input> src Attribute is used to specify the URL of the image to be
used as a submit Button. This attribute is not used with <input type=”image”>
Syntax:
<input src="URL">
Attribute Values: It contains a single value URL which specifies the link of source
image. There are two types of URL link which are listed below:
Absolute URL: It points to another webpage.
Relative URL: It points to other files of the same web page.
Following example, we have used one <img> tag to simulate the functionality of
submit button. Before writing the code make sure one “submit.jpg” picture
should save in your folder.
Program:
2)Write a JavaScript program to change the value of an element that the user
cannot change (a read-only element)
36
Experiment No: 10
Develop a webpage for creating session and persistent cookies. Observe the
effects with Browser cookie settings.
Resources required:
Hardware Software
Computer 1)Notepad editor
System 2)Any Web Browser
Practical Significance:
A cookie is a small piece of information that a web site writes to your hard disk
when you visit the site.
Theoretical Background
A JavaScript can be used to create cookies whenever someone visits the web
page that contains the script. A JavaScript can also be used to read cookies
stored on a user’s computer, and it uses the information stored in a cookie to
personalize the web page that a user visit.
Cookies are usually small text files, given ID tags that are stored on your
computer browser directory or program data subfolders.
There are two types of cookies namely: session cookie and persistent cookie.
1. Session cookie are created temporarily in your browser’s subfolder while you
are visiting a website. Once you leave the site, the session cookie is deleted.
2.Persistant Cookie files remain in your browser’s subfolder and are activated
again once you visited the website that created that particular cookie.
The text of a cookie must contain a name-value pair, which is a name and value
of the information. When you write your JavaScript, you decide on the name and
the value.
You cannot include semicolons, commas, or white space in the name or the value
unless you precede these characters with the escape character (\). The escape
character tells the browser that the semicolon, comma, or white space is part of
the name or value and not a special character.
You simply assign the cookie to the window.document.cookie object. The browser
automatically writes the cookie to memory when it reads this assignment
statement in your JavaScript, unless you set an expiration date for the cookie,
which then causes the cookie to be written to the computer’s hard disk.
Every cookie has four parts: a name, an assignment operator, a value, and a
semicolon.
The semicolon is a delimiter and not part of the value. A delimiter is a character
that indicates where something ends, which in this case is the end of the cookie.
This statement creates a cookie, where CustomerName is the name and ABC is
the value:
37
window.document.cookie = "CustomerName= ABC;"
Program:
<html>
<head>
<title>Write Cookie</title>
<script>
function WriteCookie()
{
with (document.CookieWriter)
{
document.cookie =
"CustomerName="+ customer.value+";"
alert("Cookie Written")
}
}
</script>
</head>
<body>
<form name="CookieWriter" action="" >
Enter your name:
<input type="text" name="customer"
onchange="WriteCookie()"/>
</FORM>
</body>
</html>
You can extend the life of a cookie beyond the current browser session by setting
an expiration date and saving the expiration date within the cookie. The
expiration date is typically an increment of the current date.
A date is stored in a variable of a Date data type.
<html>
<head>
<title>Write Cookie with Expiration Date</title>
<script>
function WriteCookie()
{
var expireDate = new Date
expireDate.setMonth(expireDate.getMonth()+3)
38
with (document.CookieWriter)
{
var CustomerName = customer.value
document.cookie = "CustomerName1="+
CustomerName+";expires="+expireDate.toGMTString()
alert("Cookie Written")
}
}
</script>
</head>
<body>
<form name="CookieWriter" action="" >
Enter your name: <input type="text"
name="customer" onchange="WriteCookie()" />
</FORM>
</body>
</html>
Exercise:
39
Experiment No: 11
Develop a Web Page for placing the window on the screen and working
with child window.
Resources required:
Hardware Software
Computer 1)Notepad editor
System 2)Any Web Browser
Practical Significance:
Window object
Window object is a top-level object in Client-Side JavaScript.
Window object represents the browser's window.
It represents an open window in a browser.
It supports all browsers.
The document object is a property of the window object. So, typing
window.document.write is same as document.write.
All global variables are properties and functions are methods of the window
object.
Theoretical Background
Property Description
Document It returns the document object for the window (DOM).
Frames It returns an array of all the frames including iframes in the current
window.
Closed It returns the Boolean value indicating whether a window has been
closed or not.
History It returns the history object for the window.
innerHeig It sets or returns the inner height of a window's content area.
ht
innerWidt It sets or returns the inner width of a window's content area.
h
Length It returns the number of frames in a window.
Location It returns the location object for the window.
Name It sets or returns the name of a window.
40
Navigator It returns the navigator object for the window.
Opener It returns a reference to the window that created the window.
outerHeig It sets or returns the outer height of a window, including
ht toolbars/scrollbars.
outerWidt It sets or returns the outer width of a window, including
h toolbars/scrollbars.
Parent It returns the parent window of the current window.
Screen It returns the screen object for the window.
screenX It returns the X coordinate of the window relative to the screen.
screenY It returns the Y coordinate of the window relative to the screen.
Self It returns the current window.
Status It sets the text in the status bar of a window.
Top It returns the topmost browser window that contains frames.
Method Description
alert() It displays an alert box.
confirm() It displays a dialog box.
prompt() It displays a dialog box that prompts the visitor for input.
setInterval() It calls a function or evaluates an expression at specified
intervals.
setTimeout() It evaluates an expression after a specified number of
milliseconds.
clearInterval() It clears a timer specified by setInterval().
clearTimeOut( It clears a timer specified by setTimeout().
)
close() It closes the current window.
open() It opens a new browser window.
createPopup() It creates a pop-up window.
focus() It sets focus to the current window.
blur() It removes focus from the current window.
moveBy() It moves a window relative to its current position.
moveTo() It moves a window to the specified position.
41
resizeBy() It resizes the window by the specified pixels.
resizeTo() It resizes the window to the specified width and height.
print() It prints the content of the current window.
scrollBy() It scrolls the content by the specified number of pixels.
scrollTo() It scrolls the content to the specified coordinates.
Program: Open a new window and close that window on button click event using
open( ) and close ( ).
<html>
<body>
<script>
var myWindow;
function openWin()
{
myWindow = window.open("", "myWindow", "width=200,height=100");
myWindow.document.write("<p>Hello Everyone.Welcome to new
window.</p>");
}
function closeWin()
{
myWindow.close();
}
</script>
</body>
</html>
Output:
After clicking on “open myWindow” button, new window will be open.
Click on “Close myWindow” button, newly open window will be closed.
42
Window position:
A new window always displayed on the screen at the location which is
specified by user and location is specified by setting the left and top
properties of new window as shown below:
window.open("http://vpt.edu.in", "windowName", top=500,left=500,width=40
0,height=400");
<html>
<body>
<div id="demo"></div>
<script>
var txt = "";
txt += "<p>innerWidth: " + window.innerWidth + "</p>";
txt += "<p>innerHeight: " + window.innerHeight + "</p>";
txt += "<p>outerWidth: " + window.outerWidth + "</p>";
txt += "<p>outerHeight: " + window.outerHeight + "</p>";
document.getElementById("demo").innerHTML = txt;
</script>
</body> </html>
Output:
43
Window provides two methods which also deal with positioning of windows
named scrollBy() and moveTo() method.
scrollBy(): The scrollBy() method scrolls the document by the specified
number of pixels.
Syntax: window.scrollBy(xnum, ynum)
<html>
<head>
<style>
body
{
width: 5000px;
}
button
{
position: fixed;
}
</style>
</head>
<body>
<p>Click the button to scroll the document window by 100px
horizontally.</p>
<p>Look at the horizontal scrollbar to see the effect.</p>
<button onclick="scrollWin()">Click me to scroll
horizontally!</button><br><br>
<script>
function scrollWin()
{
window.scrollBy(100, 0);
}
</script>
</body>
</html>
Output:
44
The moveTo() method moves a window's left and top edge to the specified
coordinates.
Syntax: window.moveTo(x, y)
The focus() method is used to give focus to an element (if it can be focused).
Syntax: HTMLElementObject.focus()
Code: simple example of moveTo ( )
<html>
<body>
<button onclick="openWin()">Create new window</button>
<button onclick="moveWinTo()">Move new window</button>
<button onclick="moveWinBy()">
Move the new window by 75 * 50px
</button>
<script>
var myWindow;
function openWin()
{
myWindow = window.open("", "", "width=250, height=250");
}
function moveWinTo()
{
myWindow.moveTo(150, 150);
myWindow.focus();
}
function moveWinBy()
{
myWindow.moveBy(75, 50);
myWindow.focus();
}
</script>
</body>
</html>
Output:
45
Worrking with child windows:
The only thing needs to take care is to pass proper dimension for window so that
newly created window will not appear one upon another.
<html>
<head>
<title>window </title>
<script type="text/javascript">
function show()
{
for( i=0; i< 250 ; i=i+50)
{
var x=i+50;
var y=i+50;
winobj=window.open('','win' +i, 'top='+x+ ',left='+y+',width=300,height=200');
}
}
</script>
</head>
<body>
<input type="multiple" value="Show Multiple Windows" type="button"
onclick="show()"/>
46
</body>
</html>
Output:
Exercise:
Experiment No: 12
Develop a Web Page for validation of form fields using regular expressions.
Resources required:
47
Hardware Software
Computer 1)Notepad editor
System 2)Any Web Browser
Practical Significance:
A Regular Expression is a sequence of characters that constructs a search
pattern. When you search for data in a text, you can use this search pattern to
describe what you are looking for.
Theoretical Background
Syntax:
A regular expression is defined with the RegExp () constructor as:
var pattern = new RegExp(pattern, attributes);
or simply
var pattern = /pattern/attributes;
Here,
For example, you may want to make sure that users enter a valid email address
correctly in a sign-up form, complete with @ sign and a domain, like .com, before
sending their input to a server-side program for processing.
48
In the code example below, we'll check two simpler cases in a web form:
1) Write a code that accepts username and Aadhar card as input texts. When
the user enters Aadhar-card number, the javascript validates card number
and displays whether card number is valid or not.
49
3) Demonstrate the use of quantifiers.
50
Experiment No: 13
Resources required:
Hardware Software
Computer 1)Notepad editor
System 2)Any Web Browser
Practical Significance:
Rollover means a webpage changes when the user moves his or her mouse over
an object on the page. It is often used in advertising. There are two ways to
create rollover, using plain HTML or using a mixture of JavaScript and HTML.
Theoretical Background:
Though HTML can be used to create rollovers, it can only perform simple actions.
If you wish to create more powerful rollovers, you need to use JavaScript. To
create rollovers in JavaScript, we need to create a JavaScript function.
Image Rollover:
<html>
<head>
<title>JavaScript Image Rollovers</title>
</head>
<body>
<img src="blue.png" name="image1" onmouseover="src='car.jpg' "
onmouseout="src='blue.png' ">
</img>
</body>
</html>
TextRollover:
We can also create a rollover and rollback fo text using the onmouseover and
onmouseout.
<html>
<head>
<title>
51
text rollovers</title>
</head>
<body>
<table border="1" width="100%">
<tbody>
<tr valign="top">
<td width="50%">
<a><img height="500" src="blue.png" width="900" name="clr"></a></td>
<td><a onmouseover="document.clr.src='blue.png' ">
<b><u> Blue Color</u></b></a>
<br>
<a onmouseover="document.clr.src='red.png' ">
<b><u> Red Color</u></b></a>
<br>
<a onmouseover="document.clr.src='green.png' ">
<b><u> Green Color</u></b></a>
</td>
</tr>
</tbody>
</table>
</body>
</html>
Output:
Exercise:
1) Create a rollover effect that can change the color of its text.
2) Create a rollover effect that can change the image. (Set of 4 images)
Experiment No: 14
52
Develop a Web Page for implementing Menus.
Resources required:
Hardware Software
Computer 1)Notepad editor
System 2)Any Web Browser (prefer firefox)
Practical Significance:
A menu consists of a set of options which are presented to the user. Menus are
common in graphical user interface such as Windows or Mac OS.
Theoretical Background:
The Menu component provides the pull-down menu element that's common in
most graphical user interfaces (GUIs). Using a familiar GUI element will reduce
the interface learning curve of your web site or application for new users, as well
as help all users more easily find what they're looking for. Having menus that
contain links to sections at various levels in your web site can improve both the
navigation of the site and the real estate of your web pages.
There are various types menus are available in javascript:
1) Pull-down(drop-down) menu
2) Floating (Fixed) menu
3) Chain Select menu
4) Tab menu
5) Popup menu
6) Sliding menu
7) Highlighted menu
8) Folding tree menu
9) Context menu
10) Scrollable menu-vertical and horizontal
11) Side Bar menu
To create a menu, usually require cascading style sheet , html and javascript.
Example:
Following example provides four list elements as name of branches. When you
select a branch from list, selected branch will be displayed as output.
<html>
<body>
<p>Select Program from list:</p>
<select id="mySelect" onchange="myFunction()">
<option value="CO">Computer Engg</option>
<option value="IF">Information Technology</option>
<option value="EJ">Electronics and Tele</option>
53
<option value="CE">Chemical Engg</option>
</select>
<p id="demo"></p>
<script>
function myFunction()
{
var x = document.getElementById("mySelect").value;
document.getElementById("demo").innerHTML = "You selected: " + x;
}
</script>
</body>
</html>
Output:
Popup Menu:
A popup menu appears as the user moves the mouse cursor over a parent menu
item. The popup menu contains child menu items that are associated with the
parent menu item.
Code:
<html>
<head>
<style>
.dropbtn {
background-color: Blue;
color: white;
padding: 16px;
font-size: 16px;
border: none;
}
.dropdown {
position: relative;
display: inline-block;
}
.dropdown-content {
display: none;
54
position: absolute;
background-color: red;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
}
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
<h2>Hoverable Dropdown</h2>
<p>Move the mouse over the button to open the dropdown menu.</p>
<div class="dropdown">
<button class="dropbtn">Programs:</button>
<div class="dropdown-content">
<a href="#">CO</a>
<a href="#">IF</a>
<a href="#">EJ</a>
</div>
</div>
</body>
</html>
Output:
55
Exercise:
56
Experiment No: 15
Develop a Web Page for implementing Status Bar and Web Page
Protection.
Resources required:
Hardware Software
Computer 1)Notepad editor
System 2)Any Web Browser
Practical Significance:
You need to secure your website, which means putting protection in place to
keep out hackers, bugs, and other online nasties. Otherwise, your data could be
at risk, your site could crash.
Theoretical Background:
Status bar:
The status property of the Window interface was originally intended to set the
text in the status bar at the bottom of the browser window. However, the HTML
standard now requires setting window.status to have no effect on the text
displayed in the status bar.
Syntax:
window.status = string;
var value = window.status;
<html>
<head>
<title>JavaScript Status Bar</title></head>
<body>
<a href="http://www.vpt.edu.in"
onMouseOver="window.status='Vidyalankar';return true"
onMouseOut="window.status='';return true">
Vidyalankar
</a>
</body>
</html>
Output:
57
Note: “window.status” does not supported any browser.
There is nothing secret about your web page. Anyone with a little computer
knowledge can use a few mouse clicks to display your HTML code, including your
JavaScript, on the screen. In this, you'll learn how to hide your JavaScript and
make it difficult for malicious hackers to extract e-mail addresses from your web
page.
The following example shows you how to disable the visitor's right mouse button
while the browser displays your web page. All the action occurs in the JavaScript
that is defined in the <head> tag of the web page.
<html>
<head>
<script>
window.onload = function()
{
document.addEventListener("contextmenu", function(e)
{
e.preventDefault();
}, false);}
</script>
<body>
<h3>Right click on screen,Context Menu is disabled</h3>
</body>
</html>
Exercise:
Experiment No: 16
58
Develop a Web Page for implementing Slideshow, Banner.
Resources required:
Hardware Software
Computer 1)Notepad editor
System 2)Any Web Browser
Practical Significance:
The banner advertisement is the hallmark of every commercial web page. It is
typically positioned near the top of the web page, and its purpose is to get the
visitor's attention by doing all sorts of clever things.
A slideshow is similar in concept to a banner advertisement in that a slideshow
rotates multiple images on the web page. However, unlike a banner
advertisement, a slideshow gives the visitor the ability to change the image
that's displayed: the visitor can click the Forward button to see the next image
and the Back button.
Theoretical Background:
You load the banner advertisements into an array by declaring an Array() object
and initializing it with the file name of each banner advertisement. For example,
suppose you have three banner advertisements that are contained in the 1.jpg,
2.jpg, and 3.jpg files. Here's how you'd load them into an Array() object:
Example:
<html >
<head>
<title>Banner Ads</title>
<script>
</script>
</head>
<body onload="DisplayBanners()" >
<center>
<img src="1.jpg" width="400"
height="75" name="RotateBanner" />
</center>
</body>
</html>
Creating a slideshow:
<html>
<title>slideshow</title>
<body>
<h2 class="w3-center">Manual Slideshow</h2>
<div class="w3">
<img class="mySlides" src="y.jpg" style="width:50%">
<img class="mySlides" src="yy.jpg" style="width:50%">
<img class="mySlides" src="yyy.jpg" style="width:50%">
<img class="mySlides" src="yyyy.jpg" style="width:50%">
60
<script>
var slideIndex = 1;
showDivs(slideIndex);
function plusDivs(n)
{
showDivs(slideIndex += n);
}
function showDivs(n)
{
var i;
var x = document.getElementsByClassName("mySlides");
if (n > x.length)
{
slideIndex = 1
}
if (n < 1)
{
slideIndex = x.length
}
for (i = 0; i < x.length; i++)
{
x[i].style.display = "none";
}
x[slideIndex-1].style.display = "block";
}
</script>
</body>
</html>
Exercise:
2) Create a slideshow with group of four images, also simulate the next and
previous transition between slides in javascript.
61
Beyond Syllabus Experiments:
srcdoc HTM Specifies the HTML content of the page to show in the
L_co <iframe>
de
Exercise:
62
Work with jQuery
jQuery was originally created by John Resig in early 2006. The jQuery project is
currently run and maintained by a distributed group of developers as an open-
source project.
jQuery also gives you the ability to create an Ajax based application in a quick
and simple way. Big companies like Google, Microsoft and IBM are using the
jQuery for their applications.
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Document Ready Demo</title>
<link rel="stylesheet" type="text/css" href="/examples/css/style.css">
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
$("p").text("Hello VP!");
});
</script>
</head>
<body>
<p>Not loaded yet.</p>
</body>
</html>
Exercise:
63