0% found this document useful (0 votes)
7 views

Css All CH Notes

D

Uploaded by

ammilalkumre5
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Css All CH Notes

D

Uploaded by

ammilalkumre5
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 64

Basics of JavaScript Programming Basics of JavaScript Programming

Script What is JavaScript ?


 A script is a small piece of program that can add interactivity to the website. For example, a JavaScript is a dynamic computer programming language.
script could generate a pop-up alert box message, or provide a dropdown menu. This script could
It is lightweight and most commonly used as a part of web pages, whose implementations allow
be JavaScript or VBScript.
client-side script to interact with the user and make dynamic pages.
 A script language is a simple programming language with which you can write scripts. A
scripting language is a form of programming language that is usually interpreted rather than It is an interpreted programming language with object-oriented capabilities.
compiled. JavaScript was first known as LiveScript, but Netscape changed its name to JavaScript, possibly
 Conventional programs are converted permanently into executable files before they are run. because of the excitement being generated by Java.
In contrast, programs in scripting language are interpreted one command at a time. Scripting
JavaScript can be used to trap user-initiated events such as button clicks, link navigation, and
languages are often written to facilitate enhanced features of Web sites.
other actions that the user initiates explicitly or implicitly.
 JavaScript, Perl, PHP, Python, VBScript are the most popular examples of scripting Languages.

What is Client side Script?


Features of JavaScript
A client-side script is a small program (or set of instructions) that is embedded (or inserted)
into a web page. It is processed within the client browser instead of the web server.
 JavaScript is a lightweight, interpreted programming language.
The client side script downloads at the client end from the server along with the HTML web
 Interpreter Based Scripting Language
page it is embedded in. The web browser interprets and executes the code and then displays
 Case Sensitive
the results on the monitor.
 Designed for creating network-centric applications.
The script that executes on the user’s computer system is called client. It is embedded (or
 Integrated with HTML.
inserted) within the HTML document or can be stored in an external separate file (known as
 Open and cross-platform
external script).
 Validating User’s Input : JavaScript is very useful while using forms. It has the capability to
The script files are sent to the client machine from the web server (or severs) when they are
validate user input for errors and also saves time. If the user leaves a required field empty or
requested. The client’s web browser executes the script, then displays the web page, including
the information is incorrect, JavaScript checks for them before sending the data over to the
any visible output from the script.
server.

Advantages of JavaScript
 Speed: Client-side JavaScript is very fast because it can be run immediately within the
client-side browser.
 Simplicity: JavaScript is relatively simple to learn and implement.
 Popularity: JavaScript is used everywhere on the web.
 Interoperability: JavaScript plays nicely with other languages and can be used in a huge
variety of applications.
 Server Load: Being client-side reduces the demand on the website server.
 Gives the ability to create rich interfaces.
 Less server interaction − You can validate user input before sending the page off to the
server. This saves server traffic, which means less load on your server.
 Immediate feedback to the visitors
 Increased interactivity − You can create interfaces that react when the user hovers
over them with a mouse or activates them via the keyboard.
Client side scripts may also have some instructions for the web browser to follow in response to
certain user actions, such as pressing a page button. They can often be looked if client want to
view the source code of web page.

Client Side Scripting (Unit 1) -By Yash Sawant (TYCO) Client Side Scripting (Unit 1) -By Yash Sawant (TYCO)
Basics of JavaScript Programming Basics of JavaScript Programming

Limitations of JavaScript Whitespace and Line Breaks


We cannot treat JavaScript as a full-fledged programming language. It lacks the following JavaScript ignores spaces, tabs, and newlines that appear in JavaScript programs. You can use
important features – spaces, tabs, and newlines freely in your program and you are free to format and indent your
programs.
 Client-Side Security: Because the code executes on the users’ computer, in some cases it can
Semicolons are Optional
be exploited for malicious purposes. This is one reason some people choose to disable
Javascript. Simple statements in JavaScript are generally followed by a semicolon character, just as they
are in C, C++, and Java.
 Client-side JavaScript does not allow the reading or writing of files. This has been kept for
security reason. JavaScript, however, allows you to omit this semicolon if each of your statements are placed on
a separate line.
 JavaScript cannot be used for networking applications because there is no such support
available. For example, the following code could be written without semicolons.
<script language = "javascript" type = "text/javascript">
 JavaScript doesn't have any multi-threading or multiprocessor capabilities.
document.write("Hello")
document.write("Welcome to SPC Academy")
Where to write Javascript code: </script>
1. Directly in Browser Console
2. In HTML file But when formatted in a single line as follows, you must use semicolons −
3. In separate Javascript File and linking this file in HTML file <script language = "javascript" type = "text/javascript">
Tools to run JavaScript Code: document.write("Hello"); document.write("Welcome to SPC Academy")
JavaScript Editors: Notepad,Notepad++, VS, Sublime, Eclipse, Atom </script>
Browser: Chrome,Firefox,Safari,Edge Note − It is a good programming practice to use semicolons.

JavaScript Programming Case Sensitivity


Q] Explain <script> tag with example? JavaScript is a case-sensitive language. This means that the language keywords, variables,
JavaScript can be implemented using JavaScript statements that are placed within function names, and any other identifiers must always be typed with a consistent capitalization
the <script>... </script> HTML tags in a web page. of letters.

You can place the <script> tags, containing your JavaScript, anywhere within your web page, So the identifiers Time and TIME will convey different meanings in JavaScript.
but it is normally recommended that you should keep it within the <head> tags.
Comments in JavaScript
The <script> tag alerts the browser program to start interpreting all the text between these
JavaScript supports both C-style and C++-style comments, Thus −
tags as a script. A simple syntax of your JavaScript will appear as follows.
<script ...>  Any text between a // and the end of a line is treated as a comment and is ignored by
JavaScript code JavaScript.
</script>  Any text between the characters /* and */ is treated as a comment. This may span
The script tag takes two important attributes − multiple lines.
1. Language − This attribute specifies what scripting language you are using. Typically, its Example
value will be javascript. Although recent versions of HTML (and XHTML, its successor) The following example shows how to use comments in JavaScript.
have phased out the use of this attribute. <script language = "javascript" type = "text/javascript">
// This is a comment. It is similar to comments in C++
2. Type – This attribute tells the browser that script is in plain text and text is organised in /*
the format of javascript. This is a multi-line comment in JavaScript
So your JavaScript segment will look like − It is very similar to comments in C Programming
<script language = "javascript" type = "text/javascript"> */
</script>
JavaScript code
</script>

Client Side Scripting (Unit 1) -By Yash Sawant (TYCO) Client Side Scripting (Unit 1) -By Yash Sawant (TYCO)
Basics of JavaScript Programming Basics of JavaScript Programming

JavaScript Enabling b) JavaScript in <body>...</body> section


All the modern browsers such as Internet Explorer, Firefox, chrome, and Opera come with built- If you need a script to run as the page loads so that the script generates content in the page, then
in support for JavaScript. Frequently, you may need to enable or disable this support manually. the script goes in the <body> portion of the document. In this case, you would not have any
function defined using JavaScript. Take a look at the following code.
JavaScript in Internet Explorer <html>
Here are simple steps to turn on or turn off JavaScript in your Internet Explorer − <head>
</head>
 Follow Tools → Internet Options from the menu.
 Select Security tab from the dialog box. <body>

 Click the Custom Level button.


<script type = "text/javascript">
 Scroll down till you find Scripting option.
document.write("Hello World")
 Select Enable radio button under Active scripting.
 Finally click OK and come out </script>

JavaScript Placement </body>


</html>
There is a flexibility given to include JavaScript code anywhere in an HTML document. However
the most preferred ways to include JavaScript in an HTML file are as follows −
 Script in <head>...</head> section. c) JavaScript in <body> and <head> Sections

 Script in <body>...</body> section. You can put your JavaScript code in <head> and <body> section altogether as follows −
<html>
 Script in <body>...</body> and <head>...</head> sections.
<head>
 Script in an external file and then include in <head>...</head> section. <script type = "text/javascript">
In the following section, we will see how we can place JavaScript in an HTML file in different
ways. function sayHello()
{
a) JavaScript in <head>...</head> section alert("Welcome to spc World")
}
If you want to have a script run on some event, such as when a user clicks somewhere, then you </script>
will place that script in the head as follows − </head>
<html>
<head> <body>
<script type = "text/javascript">
function sayHello() <script type = "text/javascript">
{
alert("WELCOME TO spc World") document.write("Hello World")
}
</script> </script>
</head>
<body> <input type = "button" onclick = "sayHello()" value = "Say
<input type = "button" onclick = "sayHello()" value = "Say Hello"/> Hello" />
</body> </body>
</html> </html>

d) JavaScript in External File

Client Side Scripting (Unit 1) -By Yash Sawant (TYCO) Client Side Scripting (Unit 1) -By Yash Sawant (TYCO)
Basics of JavaScript Programming Basics of JavaScript Programming

As you begin to work more extensively with JavaScript, you will be likely to find that there are
cases where you are reusing identical JavaScript code on multiple pages of a site.
JavaScript Variables
You are not restricted to be maintaining identical code in multiple HTML files. The script tag JavaScript includes Variables which are defined as named memory locations. Variable stores a
provides a mechanism to allow you to store JavaScript in an external file and then include it into single data value that can be changed later.
your HTML files.
Here is an example to show how you can include an external JavaScript file in your HTML code Variable Declaration:
using script tag and its src attribute. Before you use a variable in a JavaScript program, you must declare it.
<html> Variables are declared with the var keyword as follows.
<head>
<script type = "text/javascript" src = <script type = "text/javascript">
"C:\Users\Akshay\Desktop\akshay.js"> var money;
</script> var name;
</head> </script>

<body> You can also declare multiple variables with the same var keyword as follows −
<input type = "button" onclick = "sayHello()" value = "Say
Hello" /> <script type = "text/javascript">
</body> var money, name;
</html> </script>

A variable declared without a value will have the value undefined.


To use JavaScript from an external file source, you need to write all your JavaScript source code
in a simple text file with the extension ".js" and then include that file as shown above. For
Variable Initialization:
example, you can keep the following content in filename.js file and then you can
Storing a value in a variable is called variable initialization.
use sayHello function in your HTML file after including the filename.js file.
You can do variable initialization at the time of variable creation or at a later point in time when
function sayHello() you need that variable.
{
<script type = "text/javascript">
alert("Welcome to Arrow")
} var name = "Ali";
document.write("I am creating javascript external code<br>"); var money;
money = 2000.50;

</script>

Note − Use the var keyword only for declaration or initialization, once for the life of any
variable name in a document. You should not re-declare same variable twice.

JavaScript is untyped language. This means that a JavaScript variable can hold a value of any data
type. Unlike many other languages, you don't have to tell JavaScript during variable declaration
what type of value the variable will hold. The value type of a variable can change during the
execution of a program and JavaScript takes care of it automatically.

Client Side Scripting (Unit 1) -By Yash Sawant (TYCO) Client Side Scripting (Unit 1) -By Yash Sawant (TYCO)
Basics of JavaScript Programming Basics of JavaScript Programming

JavaScript Data Types


JavaScript Variable Scope JavaScript provides different data types to hold different types of values. There are two types of
The scope of a variable is the region of your program in which it is defined. JavaScript variables data types in JavaScript.
have only two scopes.
1. Primitive data type
Global Variables − A global variable has global scope which means it can be defined anywhere 2. Non-primitive (reference) data type
in your JavaScript code.
1. JavaScript primitive data types
JavaScript primitive data types are data types that refer to a single value.
Local Variables − A local variable will be visible only within a function where it is defined.
Within the body of a function, a local variable takes precedence over a global variable with the
There are five types of primitive data types in JavaScript. They are as follows:
same name.
If you declare a local variable or function parameter with the same name as a global variable, Data Type Description Example
you effectively hide the global variable.
Example: String represents sequence of characters e.g. "hello" var str = “Hello”;
<script type = "text/javascript">
Number represents numeric values e.g. 100 var n = 100;
var a = 25; // Declare a global variable
function fun( ) Boolean represents boolean value either false or true var x =true;
{
var a = 10; // Declare a local variable Undefined represents undefined value var x = undefined
document.write("Value of a is",a);
} Null represents null i.e. no value at all var x = null
fun();
</script> 2. JavaScript non-primitive data types
This produces the following result − The data types that are derived from primitive data types of the JavaScript language are known
Value of a is 10 as non-primitive data types.
It is also known as derived data types.
Rules for JavaScript Variable Names: It contains single or multiple key-value pair/s.

1. You should not use any of the JavaScript reserved keywords as a variable name. For example, The non-primitive data types are as follows:
break or boolean variable names are not valid. - Object
- Array
2. JavaScript variable names should not start with a numeral (0-9). - RegExp
They must begin with a letter or an underscore character.
For example, 123test is an invalid variable name but _123test is a valid one.

3. JavaScript variable names are case-sensitive. For example, Name and name are two different
variables.

Client Side Scripting (Unit 1) -By Yash Sawant (TYCO) Client Side Scripting (Unit 1) -By Yash Sawant (TYCO)
Basics of JavaScript Programming Basics of JavaScript Programming

1.3 Objects  Hence, each object has its own set of properties. An object can be created with curly
brackets {...} with list of properties.
Real Life Objects, Properties, and Methods
 A property is a "key: value pair, where key is a string (also called a "property name"), and
In real life, a car is an object.
value can be anything.
A car has properties like weight and color, and methods like start and stop:

D] Creating a JavaScript Object


Object Properties Methods
With JavaScript, you can define and create your own objects. There are different ways to create
new objects:
car.name = Fiat car.start()
 Define and create a single object, using an object literal.
car.model = 500 car.drive()  Define and create a single object, with the keyword new.
 Define an object constructor, and then create objects of the constructed type.
car.weight = 850kg car.brake()
1. Using an Object Literal

car.color = white car.stop() This is the easiest way to create a JavaScript Object. Using an object literal, you both define and
create an object in one statement. An object literal is a list of name:value pairs inside curly
All cars have the same properties, but the property values differ from car to car. All cars have braces {}.
the same methods, but the methods are performed at different times.
The following example creates a new JavaScript object with four properties:
A] JavaScript Objects syntax :
object={property1:value1,property2:value2...... propertyN:valueN}
 JavaScript is an object-based language. Everything is an object in JavaScript. As you can see, property and value is separated by : (colon).
 All primitive data types can contain only a single thing (either a string or a number). In Example:
contrast, objects are used to store collections of data and more complex entities. <script>
 JavaScript objects are collections of properties and methods. emp={id:102,name:"Shyam Kumar",salary:40000}
document.write(emp.id+" "+emp.name+" "+emp.salary);
 A property is a value or set of values that is a member of an object </script>
 A method is a function that is a member of an object.
Spaces and line breaks are not important. An object definition can span multiple lines:
 Objects in JavaScript may be defined as, an unordered collection of related data of <script>
primitive or reference types in the form of "key: value" pairs, emp= {
 You access an object's properties and methods by using the dot syntax along with the id:102,
object name and its property or method. name:"Shyam Kumar",
salary:40000
B] Object Name }
 Each object is uniquely identified by a name or ID. document.write(emp.id+" "+emp.name+" "+emp.salary);
 A web page contains many objects, some of which are the same kind of object. These objects </script>
can be easily distinguishable by using its name or ID.
2. Using the JavaScript Keyword new
C] Property
 A property is a data or value associated with an object. Syntax:

 Objects can have many data's associated with them depending on application of use.
var objectname=new Object();
 For example, a form object can have a title, a width and a height as properties whereas a
window object can have a background color, a width and height as properties.
Here, new keyword is used to create object.

Client Side Scripting (Unit 1) -By Yash Sawant (TYCO) Client Side Scripting (Unit 1) -By Yash Sawant (TYCO)
Basics of JavaScript Programming Basics of JavaScript Programming

Example: fname: " Computer ",


<script> lname: " Engineering”
var emp=new Object(); };
emp.id=101; document.write(“User =” + user.fname +” “+ user. lname);
emp.name="Ravi Malik"; </script>
emp.salary=50000; </body>
document.write(emp.id+" "+emp.name+" "+emp.salary); </html>
</script> Output:
User – Computer Engineering
3. By using an Object constructor
Here, you need to create function with arguments. Each argument value can be assigned in the F] Method
current object by using this keyword. A method is a set of statements (actions) performed by an object when it receives a message.
The this keyword refers to the current object. On a form when you click on Submit button, the form is submitted to server side application.
Example: Here Submit is an object, and clicking on it causes the button to process a method.
<script>
function emp(id,name,salary) Example:
{
this.id=id; <script>
this.name=name; var person = {
this.salary=salary; firstName: "John",
} lastName : "Doe",
e=new emp(103,"Vimal Jaiswal",30000); fullName : function()
document.write(e.id+" "+e.name+" "+e.salary); {
</script> return this.firstName + " " + this.lastName;
}
E] Dot Syntax:
 The properties & methods associated with any object can be accessed by using the object };
name with dot syntax. document.write(“User Name is:” + person.fullname());
 E.g. user.fname, user.lname & user.fullName( ). </script>

In the following code user object is created with two properties: The this Keyword
1 The first property has the name fname and the value "Computer" In a function definition, this refers to the "owner" of the function.
2. The second one has the name lname and the value "Engineering". In the example above, this is the person object that "owns" the fullName function.
In other words, this.firstName means the firstName property of this object.

You can access the object properties in following two ways:


1. user.fname;
2. user[“fname”]

Example:
<html>
<head>
<title>Object</title>
</head>
<body>
<script>
var user = {

Client Side Scripting (Unit 1) -By Yash Sawant (TYCO) Client Side Scripting (Unit 1) -By Yash Sawant (TYCO)
Basics of JavaScript Programming Basics of JavaScript Programming

1.5 JavaScript Operator 2) Assignment Operators


JavaScript operators are symbols that are used to perform operations on operands. JavaScript supports the following assignment operators −

JavaScript supports the following types of operators. Sr. Operator & Description Example

 Arithmetic Operators = (Simple Assignment )


Ex: C = A + B will assig n
 Comparison Operators 1 Assigns values from the right side operand to the left side
the value of A + B into C
 Logical (or Relational) Operators operand
 Assignment Operators
+= (Add and Assignment)
 Conditional (or ternary) Operators Ex: C += A is equivalent to
2 It adds the right operand to the left operand and assigns the
Lets have a look on all operators one by one. C=C+A
result to the left operand.

1) Arithmetic Operators −= (Subtract and Assignment)


Ex: C -= A is equivalent to
3 It subtracts the right operand from the left operand and
Arithmetic operators are used to perform arithmetic operations on the operands. C=C-A
assigns the result to the left operand.
Assume variable A holds 10 and variable B holds 20, then −
*= (Multiply and Assignment)
Sr. Operator & Description Example Ex: C *= A is equivalent to
4 It multiplies the right operand with the left operand and
C=C*A
1 + (Addition): Adds two operands Ex: A + B will give 30 assigns the result to the left operand.

2 - (Subtraction): Subtracts the second operand from the first Ex: A - B will give -10 /= (Divide and Assignment)
Ex: C /= A is equivalent to
5 It divides the left operand with the right operand and assigns
C=C/A
3 * (Multiplication): Multiply both operands Ex: A * B will give 200 the result to the left operand.

4 / (Division): Divide the numerator by the denominator Ex: B / A will give 2 %= (Modules and Assignment)
Ex: C %= A is equivalent
6 It takes modulus using two operands and assigns the result to
5 % (Modulus): Outputs the remainder of an integer division Ex: B % A will give 0 to C = C % A
the left operand.

6 ++ (Increment): Increases an integer value by one Ex: A++ will give 11 Ex. C**=A is equivalent to
7 **=
C=C*A
7 -- (Decrement): Decreases an integer value by one Ex: A-- will give 9

Ex. A**B will give A


8 ** (Exponentiation)
raised to power B

Client Side Scripting (Unit 1) -By Yash Sawant (TYCO) Client Side Scripting (Unit 1) -By Yash Sawant (TYCO)
Basics of JavaScript Programming Basics of JavaScript Programming

3) Comparison Operators 4) Logical Operators


JavaScript supports the following comparison operators − Assume variable A holds 10, variable B holds 20, variable C holds 30, then −
Assume variable A holds 10 and variable B holds 20, then − Sr. Operator & Description Example
Sr. Operator & Description Example && (Logical AND)
Ex: (A<B && B < C) is
= = (Equal) 1 If both the operands are true, then the condition becomes
true.
1 Checks if the value of two operands are equal or not, if yes, then the Ex: (A == B) is not true . true, otherwise it returns false.
condition becomes true. || (Logical OR)
2 If any of its arguments are true, it returns true, otherwise it Ex: (A>B || B < C) is false.
!= (Not Equal)
returns false.
2 Checks if the value of two operands are equal or not, if the values Ex: (A != B) is true.
are not equal, then the condition becomes true. ! (Logical NOT)
3 If a condition is true, then the Logical NOT operator will Ex: ! (A && B) is false.
> (Greater than)
make it false and vice versa.
3 Checks if the value of the left operand is greater than the value of Ex: (A > B) is not true.
the right operand, if yes, then the condition becomes true.
5) Bitwise Operators
< (Less than)
4 Checks if the value of the left operand is less than the value of the Ex: (A < B) is true. Assume variable A holds 2 and variable B holds 3, then −
right operand, if yes, then the condition becomes true. Sr. Operator & Description Example

>= (Greater than or Equal to) & (Bitwise AND)


5 Checks if the value of the left operand is greater than or equal to the Ex: (A >= B) is not true . 1 It performs a Boolean AND operation on each bit of its integer Ex: (A & B) is 2.
value of the right operand, if yes, then the condition becomes true. arguments.

<= (Less than or Equal to) | (BitWise OR)


6 Checks if the value of the left operand is less than or equal to the Ex: (A <= B) is true. 2 It performs a Boolean OR operation on each bit of its integer Ex: (A | B) is 3.
value of the right operand, if yes, then the condition becomes true. arguments.

Ex: A=5 and B=”5” ^ (Bitwise XOR)


7 === (equal value and equal type)
Then A ===B is False It performs a Boolean exclusive OR operation on each bit of its integer
3 Ex: (A ^ B) is 1.
arguments. Exclusive OR means that either operand one is true or
Ex: A=5 and B=”5” operand two is true, but not both.
8 !== (Not equal value or Not equal type)
Then A !==B is True
~ (Bitwise Not)
4 It is a unary operator and operates by reversing all the bits in the Ex: (~B) is -4.
operand.

<< (Left Shift)


It moves all the bits in its first operand to the left by the number of
5 places specified in the second operand. New bits are filled with zeros. Ex: (A << 1) is 4.
Shifting a value left by one position is equivalent to multiplying it by 2,
shifting two positions is equivalent to multiplying by 4, and so on.

>> (Right Shift)


6 Binary Right Shift Operator. The left operand’s value is moved right by Ex: (A >> 1) is 1.
the number of bits specified by the right operand.

Client Side Scripting (Unit 1) -By Yash Sawant (TYCO) Client Side Scripting (Unit 1) -By Yash Sawant (TYCO)
Basics of JavaScript Programming Basics of JavaScript Programming

6) Ternary Operator 1) if statement


JavaScript includes special operator called ternary operator :? that assigns a value to a variable The if statement is the fundamental control statement that allows JavaScript to make decisions
based on some condition. This is like short form of if-else condition. and execute statements conditionally.
Syntax:
<condition> ? <value1> : <value2>; Syntax
Ternary operator starts with conditional expression followed by ? operator. Second part ( after if (expression)
? and before : operator) will be executed if condition turns out to be true. If condition becomes {
false then third part (after :) will be executed. Statement(s) to be executed if expression is true
Example: }
var a = 10, b = 5; Here a JavaScript expression is evaluated. If the resulting value is true, the given statement(s)
var c = a > b? a : b; // value of c would be 10 are executed. If the expression is false, then no statement would be executed. Most of the times,
var d = a > b? b : a; // value of d would be 5 you will use comparison operators while making decisions.

Conditional Statements Example


While writing a program, there may be a situation when you need to adopt one out of a given set Try the following example to understand how the if statement works.
of paths. In such cases, you need to use conditional statements that allow your program to make
correct decisions and perform right actions. <html>
<body>
JavaScript supports conditional statements which are used to perform different actions based
<script type = "text/javascript">
on different conditions.
var age = 20;
if( age > 18 )
A] if..else statement {
document.write("Qualifies for driving ");
Flow Chart of if-else }
</script>
</body>
</html>

Output
Qualifies for driving

2) if...else statement

Syntax
if (expression)
{
Statement(s) to be executed if expression is true
}
else
{
Statement(s) to be executed if expression is false
JavaScript supports the following forms of if..else statement − }
 if statement
Here JavaScript expression is evaluated. If the resulting value is true, the given statement(s) in
 if...else statement the ‘if’ block, are executed. If the expression is false, then the given statement(s) in the else
 if...else if... statement. block are executed.

Client Side Scripting (Unit 1) -By Yash Sawant (TYCO) Client Side Scripting (Unit 1) -By Yash Sawant (TYCO)
Example Example
Try the following code to learn how to implement an if-else-if statement in JavaScript.
Try the following code to learn how to implement an if-else statement in JavaScript.
<html>
<!DOCTYPE html>
<body>
<html>
<script type = "text/javascript">
<head>
var age = 15;
<title>First Page</title>
<script type = "text/javascript">
if( age > 18 )
{
var m1=30,m2=40,m3=35,m4=34,m5=30;
document.write("<b>Qualifies for driving</b>");
var total=m1+m2+m3+m4+m5;
}
var per=total/5
else
document.write("Total is "+total)
{
document.write("<br>")
document.write("<b>Does not qualify for driving</b>");
document.write("Percentage is "+per)
}
document.write("<br>")
</script>
</body>
if(per>70)
</html>
{
document.write("Distinction")
Output }
Does not qualify for driving
else if(per>60)
3) if...else if... statement {
document.write("First Class")
The if...else if... statement is an advanced form of if…else that allows JavaScript to make a correct }
decision out of several conditions. else if(per>50)
{
Syntax document.write("Second Class")
}
The syntax of an if-else-if statement is as follows −
else if(per>40)
if (expression 1)
{
{
document.write("Pass")
Statement(s) to be executed if expression 1 is true
}
}
else
else if (expression 2)
{
{
document.write("Fail")
Statement(s) to be executed if expression 2 is true
}
}
else if (expression 3)
{
</script>
Statement(s) to be executed if expression 3 is true
</head>
}
<body>
else
</body>
{
</html>
Statement(s) to be executed if no expression is true
}
It is just a series of if statements, where each if is a part of the else clause of the previous
statement. Statement(s) are executed based on the true condition, if none of the conditions is
true, then the else block is executed.

Client Side Scripting (Unit 1) -By Yash Sawant (TYCO) Client Side Scripting (Unit 1) -By Yash Sawant (TYCO)
4) nested if else statement B) switch statement
Nested if statements mean if statement inside another if statement. The JavaScript switch statement is used in decision making.
Syntax: The switch statement evaluates an expression and executes the corresponding body that
if (condition1) matches the expression's result.
{ Syntax:
// Executes when condition1 is true switch (variable/expression)
if (condition2) {
{
case value1:
// Executes when condition2 is true
} // body of case 1
} break;
case value2:
Example: // body of case 2
<!DOCTYPE html> break;
<html> case valueN:
<head> // body of case N
<title>Nested If Else</title> break;
<script type="text/javascript"> default:
var a=10,b=40,c=30; // body of default
if(a>b) }
{
if(a>c) The switch statement evaluates a variable/expression inside parentheses ().
{  If the result of the expression is equal to value1, its body is executed.
document.write("Largest number is "+a)  If the result of the expression is equal to value2, its body is executed.
}
 This process goes on. If there is no matching case, the default body executes.
else
{
Notes:
document.write("largest number is "+c)
 The break statement is optional. If the break statement is encountered, the switch statement
}
ends.
}
 If the break statement is not used, the cases after the matching case are also executed.
else
 The default clause is also optional.
{
if(b>c)
{ Flowchart:
document.write("Largest number is "+b)
}
else
{
document.write("Largest number is "+c)
}
}
</script>
</head>
<body>
</body>
</html>

Client Side Scripting (Unit 1) -By Yash Sawant (TYCO) Client Side Scripting (Unit 1) -By Yash Sawant (TYCO)
Example: Example 2
<html> <!DOCTYPE html>
<body> <html>
<script type = "text/javascript"> <head>
var grade = 'd'; <title>Switch</title>
document.write("Entering switch block<br />"); <script type = "text/javascript">
switch (grade) {
case 'A': document.write("Good job<br />");
var operator = '+';
break;
var number1=23,number2=10,result;
case 'B': document.write("Pretty good<br />");
document.write("Entering switch block<br />");
break;
case 'C': document.write("Passed<br />"); switch(operator)
break; {
case 'D': document.write("Not so good<br />"); case '+':
break; result = number1 + number2;
case 'E': document.write("Failed<br />"); document.write(result)
break; break;
default: document.write("Unknown grade<br />") case '-':
} result = number1 - number2;
document.write("Exiting switch block"); document.write(result)
</script> break;
</body>
case '*':
</html>
result = number1 * number2;
Output document.write(result)
Entering switch block break;
Good job case '/':
Exiting switch block result = number1 / number2;
document.write(result)
break;
case '%':
result = number1 % number2;
document.write(result)
break;

default:
document.write("Wrong Arithmetic Operator")
break;
}

</script>
</head>
<body>
</body>
</html>

Client Side Scripting (Unit 1) -By Yash Sawant (TYCO) Client Side Scripting (Unit 1) -By Yash Sawant (TYCO)
Loop in JavaScript
Example:
While writing a program, you may encounter a situation where you need to perform an action
over and over again. In such situations, you would need to write loop statements to reduce the
number of lines. <html>
<body>
1) The while Loop
The purpose of a while loop is to execute a statement or code block repeatedly as long as
an expression is true. Once the expression becomes false, the loop terminates. <script type = "text/javascript">
var count = 0;
Syntax:
document.write("Starting Loop ");
while (expression)
while (count < 10) {
{
document.write("Current Count : " + count + "<br />");
Statement(s) to be executed if expression is true
count++;
}
}

 A while loop evaluates the condition inside the parenthesis (). document.write("Loop stopped!");
 If the condition evaluates to true, the code inside the while loop is executed. </script>
 The condition is evaluated again.
 This process continues until the condition is false. <p>Set the variable to different value and then try...</p>
 When the condition evaluates to false, the loop stops. </body>
</html>
Flow Chart
Output
Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4
Current Count : 5
Current Count : 6
Current Count : 7
Current Count : 8
Current Count : 9
Loop stopped!
Set the variable to different value and then try...

Client Side Scripting (Unit 1) -By Yash Sawant (TYCO) Client Side Scripting (Unit 1) -By Yash Sawant (TYCO)
2) The do...while Loop </script>
<p>Set the variable to different value and then try...</p>
The do...while loop is similar to the while loop except that the condition check happens at the
</body>
end of the loop. This means that the loop will always be executed at least once, even if the
</html>
condition is false.
Flow Chart
Output
Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4
Loop Stopped!
Set the variable to different value and then try...

3) The 'for' loop


The 'for' loop is the most compact form of looping. It includes the following three important
parts −
 The loop initialization where we initialize our counter to a starting value. The
initialization statement is executed before the loop begins.
Syntax  The test statement which will test if a given condition is true or not. If the condition is
do true, then the code given inside the loop will be executed, otherwise the control will come
{ out of the loop.
Statement(s) to be executed;  The iteration statement where you can increase or decrease your counter.
} while (expression); You can put all the three parts in a single line separated by semicolons.
Flow Chart

Note − Don’t miss the semicolon used at the end of the do...while loop.
Example:
Try the following example to learn how to implement a do-while loop in JavaScript.
<html>
<body>
<script type = "text/javascript">
<!--
var count = 0;

document.write("Starting Loop" + "<br />");


do {
document.write("Current Count : " + count + "<br
/>");
count++;
} Syntax
for (initialization; test condition; iteration statement)
while (count < 5); {
document.write ("Loop stopped!"); Statement(s) to be executed if test condition is true
//--> }

Client Side Scripting (Unit 1) -By Yash Sawant (TYCO) Client Side Scripting (Unit 1) -By Yash Sawant (TYCO)
Example break statement
The break statement is used to terminate from the loop immediately. When a break statement is
<html> encountered inside a loop, the loop iteration stops there, and control returns from the loop
<body> immediately to the first statement after the loop.
<script type = "text/javascript"> Example:
var count; <script type="text/javascript">
document.write("Starting Loop" + "<br />"); var count;
document.write("Starting Loop" + "<br />");
for(count = 0; count < 10; count++)
for(count = 0; count < 10; count++)
{
{
document.write("Current Count : " + count );
if(count==5)
document.write("<br />");
{
}
break
document.write("Loop stopped!");
}
</script>
document.write("Current Count : " + count );
<p>Set the variable to different value and then try...</p>
</body> document.write("<br />");
</html> }
</script>

Output
Starting Loop Output:
Current Count : 0 Starting Loop
Current Count : 1 Current Count : 0
Current Count : 2 Current Count : 1
Current Count : 3 Current Count : 2
Current Count : 4
Current Count : 3
Current Count : 5
Current Count : 4
Current Count : 6
Current Count : 7
Current Count : 8 continue statement
Current Count : 9
The continue statement in Java is used to skip the current iteration of a loop.
Loop stopped!
Set the variable to different value and then try...
<script type="text/javascript">
var count;
document.write("Starting Loop" + "<br />");

for(count = 0; count < 10; count++)


{
if(count==5)
{
continue
}
document.write("Current Count : " + count );
document.write("<br />");

}
</script>

Client Side Scripting (Unit 1) -By Yash Sawant (TYCO) Client Side Scripting (Unit 1) -By Yash Sawant (TYCO)
Output: 3. Floating number literals
Starting Loop A floating number has the following parts.
Current Count: 0  A decimal integer.
Current Count: 1  A decimal point ('.').
Current Count: 2  A fraction.
Current Count: 3 Example:
Current Count: 4 8.2935
Current Count: 6 -14.72
Current Count: 7
4. Boolean literals
Current Count: 8
The Boolean type has two literal values: true and false
Current Count: 9

5. Object literals
JavaScript Values or Literals: An object literal is zero or more pairs of comma-separated list of property names and
associated values, enclosed by a pair of curly braces.
In JavaScript an object literal is declared as follows:
1. Array literals
In Javascript, an array literal is a list of expressions, each of which represents an array element, 1. An object literal without properties:
enclosed in a pair of square brackets ' [ ] ' . When an array is created using an array literal, it is var student = { }
initialized with the specified values as its elements, and its length is set to the number of
arguments specified. If no value is supplied it creates an empty array with zero length. 2. An object literal with a few properties :
var student =
Creating an empty array : {
var fruits = [ ]; First-name : "Akshay",
Creating an array with four elements. Last-name : "Rayy",
var fruits = ["Orange", "Apple", "Banana", "Mango"] Roll-No : 12
};
2. Integers literals
An integer must have at least one digit (0-9). Syntax Rules
No comma or blanks are allowed within an integer. There is a colon (:) between property name and value.
It does not contain any fractional part. A comma separates each property name/value from the next.
It can be either positive or negative if no sign precedes it is assumed to be positive. There will be no comma after the last property name/value pair.
In JavaScript, integers can be expressed in three different bases. 6. String literals

1. Decimal ( base 10) A string literal is zero or more characters, either enclosed in single quotation (') marks or
Decimal numbers can be made with the digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 and there will be no double quotation (") marks.
leading zeros. You can also use + operator to join strings.
Example: 123 The following are the examples of string literals :

2. Hexadecimal ( base 16) string1 = "computer"


Hexadecimal numbers can be made with the digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 and letters A, B, C, D, string1 = 'engineering.com'
E, F or a, b, c, d, e, f. A leading 0x or 0X indicates the number is hexadecimal. string1 = "1000"
Example: 0x123 string1 = "google" + ".com"

3. Octal (base 8)
Octal numbers can be made with the digits 0, 1, 2, 3, 4, 5, 6, 7. A leading 0 indicates the number
is octal.
Example: 0123

Client Side Scripting (Unit 1) -By Yash Sawant (TYCO) Client Side Scripting (Unit 1) -By Yash Sawant (TYCO)
Array,Function and String
Main Event
Event is something that causes JavaScript to execute the code. JavaScript Array
JavaScript's interaction with HTML is handled through events that occur when the user or the An array is a special type of variable, which can store multiple values using special syntax.
browser manipulates a page. Every value is associated with numeric index starting with 0. The following figure illustrates
When the page loads, it is called an event. how an array stores values.
When the user clicks a button, that click to is an event.
Other examples include events like pressing any key, closing a window, resizing a window, etc.
Each available event has an event handler, which is a block of code (usually a JavaScript
function) that runs when the event fires.
Execution of appropriate code on occurrence of event is called event handling. JavaScript Array

Array Initialization
An array in JavaScript can be defined and initialized in two ways, array literal and Array
constructor.
a) Array Literal
Array literal syntax is simple. It takes a list of values separated by a comma and enclosed in
square brackets.

Syntax:
var array_name = [element0, element1, element2,... elementN];

The following example shows how to define and initialize an array using array literal
syntax.

Example:
var stringArray = ["one", "two", "three"];
var numericArray = [1, 2, 3, 4];
var mixedArray = [1, "two", "three", 4];

JavaScript array can store multiple element of different data types. It is not required to store
value of same data type in an array.

b) Array Constructor
You can initialize an array with Array constructor syntax using new keyword.
The Array constructor has following three forms.
Syntax:

var arrayName = new Array ( ); //creates new array with no element.

Var arrayName = new Array ( Number length ); //creates new array with specified length

Client Side Scripting (Unit 1) -By Yash Sawant (TYCO) Client Side Scripting (Unit 2) -By Yash Sawant (TYCO)
Array,Function and String Array,Function and String

Defining / Initializing Array elements length property


Array can be initialized in two ways: Array includes “length” property which returns number of elements in the array.
1) Declaration and initialization can be done in one step as follow. Example
var fruits = [“Banana”, “Orange”, “Apple”, “Mango”];
Syntax. fruits.length; // the length of fruits is 4

Var arrayName = new Array (element1, element2, element3, elementN); // creates new
array with elements specified in the bracket Looping the Array
Use for loop to access all the elements of an array using length property.
Example:
var mixed Array = new Array(1, "two", 3, "four"); Example: Access Array using for Loop

2) Array can be declared first and we can define the elements later. For this array make <script type=”text/javascript”>
use of index. var Arr = new Array("one", "two", "three", "four");
for (var i = 0; i < Arr.length ; i++)
Example {
document.write(Arr[i]);
var stringArray = new Array(); // Array Declaration }
stringArray[0] = "one"; //Array Initialization </script>
stringArray[1] = "two";
stringArray[2] = "three"; Adding an Array Element
stringArray[3] = "four"; 1. push() method
The JavaScript array push() method adds one or more elements to the end of the given array.
This method changes the length of the original array.
Array can only have numeric index (key). Index cannot be of string or any other data type.
Syntax
Accessing Array Elements The push() method is represented by the following syntax:
array.push(element1,element2 ... elementn)
An array elements (values) can be accessed using index (key). Specify an index in square bracket Let's see some examples of push() method
with array name to access the element at particular index. Index of an array starts from zero in
JavaScript. Example 1
<script>
Example: var arr=["AngularJS","Node.js"];
document.writeln("Length before invoking push(): "+arr.length+"<br>");
var stringArray = new Array("one", "two", "three", "four"); arr.push("JQuery","Bootstrap");
document.writeln("Length after invoking push(): "+arr.length+"<br>");
stringArray[0]; // returns "one" document.writeln("Update array: "+arr);
stringArray[1]; // returns "two" </script>
stringArray[2]; // returns "three"
stringArray[3]; // returns "four" Output:

Length before invoking push(): 2


Length after invoking push(): 4
Update array: AngularJS, Node.js, JQuery, Bootstrap

Client Side Scripting (Unit 2) -By Yash Sawant (TYCO) Client Side Scripting (Unit 2) -By Yash Sawant (TYCO)
Array,Function and String Array,Function and String

2. Using length property The Compare Function


New element can also be added to an array using the length property: The purpose of the compare function is to define an alternative sort order.
The compare function should return a negative, zero, or positive value, depending on the
Example arguments:
var fruits = ["Banana", "Orange", "Apple", "Mango"]; function (a, b)
fruits[fruits.length] = "Lemon"; // adds a new element (Lemon) to fruits {
return a – b
}
Array sort() method
The JavaScript array sort() method is used to arrange the array elements in some order. By When the sort() function compares two values, it sends the values to the compare function,
default, sort() method follows the ascending order. and sorts the values according to the returned (negative, zero, positive) value.
Syntax If the result is negative a is sorted before b.
The sort() method is represented by the following syntax: If the result is positive b is sorted before a.
array.sort() If the result is 0 no changes are done with the sort order of the two values.

Example 1 Example:
Let's see a simple example to sort the array of string elements. The compare function compares all the values in the array, two values at a time (a, b).
<script type="text/javascript"> When comparing 40 and 100, the sort() method calls the compare function(40, 100).
var fruits=["Mango","Apple","WaterMelon","Pineapple"] The function calculates 40 - 100 (a - b), and since the result is negative (-60), the sort
var result=fruits.sort(); function will sort 40 as a value lower than 100.
document.write(result)
</script> Example
Output: Arrange the elements in ascending order using function.
Apple,Mango,Pineapple,WaterMelon <script>
var arr=[20,40,100,80,50];
var result=arr.sort(function (a,b)
{
Numeric Sort return a-b;
});
By default, the sort() function sorts values as strings. document.writeln(result);
This works well for strings ("Apple" comes before "Banana"). </script>
However, if numbers are sorted as strings, "25" is bigger than "100", because "2" is bigger than Output:
"1". 20,40,50,80,100
Because of this, the sort() method will produce incorrect result when sorting numbers.
<script type="text/javascript">
var arr=[100,25,200,30,45] Reversing an Array
var result=arr.sort(); The reverse() method reverses the elements in an array. You can use it to sort an array in
document.write(result) descending order:
</script> Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
Output: fruits.sort(); // First sort the elements of fruits
100,200,25,30,45 fruits.reverse(); // Then reverse the order of the elements

You can fix this by providing a compare function:

Client Side Scripting (Unit 2) -By Yash Sawant (TYCO) Client Side Scripting (Unit 2) -By Yash Sawant (TYCO)
Array,Function and String Array,Function and String

Example Array concat() Method


Arrange the elements in descending order using function.
The JavaScript array concat() method combines two or more arrays and returns a new string.
<script>
This method doesn't make any change in the original array.
var arr=[20,40,100,80,50];
var result=arr.sort(function (a,b)
Syntax:
{
array.concat(arr1,arr2, ...,arrn)
return b-a;
});
Parameter:
document.writeln(result);
arr1,arr2, .. ,arrn - It represent the arrays to be combined.
</script>

Return :
Output:
A new array object that represents a joined array.
100,80,50,40,20

Example 1
Combining Array elements into a string: Here, we will print the combination of two arrays.
Array join() method
<script>

The JavaScript array join() method combines all the elements of an array into a string and var arr1=["C","C++","Python"];
return a new string. We can use any type of separators to separate given array elements. var arr2=["Java","JavaScript","Android"];
Syntax
var result=arr1.concat(arr2);
array.join(separator)
document.writeln(result);
Separator - It is optional. It represent the separator used between array elements. </script>
Returns a new string contains the array values with specified separator.
Output:
Example 1: C,C++,Python,Java,JavaScript,Android
<script type="text/javascript">
var fruits=["Mango","Apple","WaterMelon","Pineapple"] Example 2
var result=fruits.join(); Here, we will print the combination of three arrays.
document.write(result)
</script> <script>
Output: var arr1=["C","C++","Python"];
Mango,Apple,WaterMelon,Pineapple var arr2=["Java","JavaScript","Android"];
var arr3=["Ruby","Kotlin"];
Example 2 var result=arr1.concat(arr2,arr3);
In this example, we will separate the array elements using '-' separator. document.writeln(result);
<script type="text/javascript"> </script>
var fruits=["Mango","Apple","WaterMelon","Pineapple"] Output:
var result=fruits.join('-');
document.write(result) C,C++,Python,Java,JavaScript,Android,Ruby,Kotlin
</script>

Client Side Scripting (Unit 2) -By Yash Sawant (TYCO) Client Side Scripting (Unit 2) -By Yash Sawant (TYCO)
Array,Function and String Array,Function and String

Array slice ( ) method Changing Elements of Array


The JavaScript array slice() method extracts the part of the given array and returns it.
The slice() method selects the elements starting at the given start argument, and ends at, but
Array shift() method
does not include, the given end argument.
The JavaScript array shift() method removes the first element of the given array and returns
This method doesn't change the original array.
that element. This method changes the length of the original array.
Syntax
Syntax
The shift() method is represented by the following syntax:
array.slice(start,end)
1. array. shift()
Return
Parameter
The first element of an array.
start - It is optional. It represents the index from where the method starts to extract the
Example
elements.
<script type="text/javascript">
end - It is optional. It represents the index at where the method stops extracting elements.
var fruits=["Mango","Apple","WaterMelon","Pineapple"]
var result=fruits.shift();
Return
document.write(result)
A new array contains the extracted elements.
</script>
Output:
Example
Mango
<script>
var arr = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var result = arr.slice(1, 3); Array pop() method
document.writeln(result); The JavaScript array pop() method removes the last element from the given array and return
</script> that element. This method changes the length of the original array.
Syntax
Output: array.pop()
Orange,Lemon
Return
If the end argument is omitted, like in the first examples, the slice() method slices out the rest The last element of given array.
of the array. Example 1
<script type="text/javascript">
Example
<script> var arr=["Mango","Apple","WaterMelon","Pineapple"]
var arr = ["Banana", "Orange", "Lemon", "Apple", "Mango"]; document.writeln("Orginal array: "+arr+"<br>");
var result = arr.slice(1); document.writeln("Extracted element: "+arr.pop()+"<br>");
document.writeln(result); document.writeln("Remaining elements: "+ arr);
</script> </script>
Output:
Output: Original array: Mango,Apple,WaterMelon,Pineapple
Orange,Lemon,Apple,Mango Extracted element: Pineapple
Remaining elements: Mango,Apple,WaterMelon

Client Side Scripting (Unit 2) -By Yash Sawant (TYCO) Client Side Scripting (Unit 2) -By Yash Sawant (TYCO)
Array,Function and String Array,Function and String

Example 2 For In Over Arrays


In this example, we will pop all the elements from the given array. The JavaScript for in statement can also loop over the properties of an Array:
Syntax
<script> for (variable in array)
var arr=["Mango","Apple","WaterMelon","Pineapple"] {
var len=arr.length; code
for(var x=1;x<=len;x++) }
{
document.write("Extracted element: "+arr.pop()+"<br>"); Example:
} <script type="text/javascript">
</script> var numbers = [45, 4, 9, 16, 25];
for (key in numbers)
{
Output: document.write(key+":"+numbers[key]+"<br>"); }
Extracted element: Pineapple </script>
Extracted element: WaterMelon
Extracted element: Apple Output:
Extracted element: Mango
0:45
The For In Loop 1:4
The JavaScript for in statement loops through the properties of an Object:
2:9
3:16
Syntax 4:25
for (key in object)
{ Associative Array in JavaScript
// code block to be executed
}
Associative arrays are dynamic objects.
An Associative array is a set of key-value pairs and dynamic objects which the user modifies as
In each iteration of the loop, a key is assigned to the key variable. The loop continues for all
needed.
object properties.
When user assigns values to keys with datatype Array, it transforms into an object and loses
Note: Once you get keys, you can easily find their corresponding values.
the attributes and methods of Array.
It uses string instead of a number as an index.
Example
The length attribute has no effect because the variable is no longer of Array type.
<script type="text/javascript">
An associative array is declared or dynamically created.
var person = {fname:"Spc", lname:"Academy", age:25};for
We can create it by assigning a literal to a variable.
(x in person)
{
<name of the array> = { key1: 'value1', key2: 'value2', key3: 'valu3'…..}
document.write(x+":"+person[x]);
var employee=[“Akshay”,”Saideep”,”Anushka”]
}
</script>
Example:
var employee = {101:"Akshay", 102:"Saideep", 103:"Anusha"}
Example Explained
The for in loop iterates over a person object
Unlike simple arrays, here we use curly braces instead of square brackets.
In each iteration key is assigned to variable x.
This has implicitly created a variable of type Object.
These keys are used to access the value of the key.
The content is accessed by keys, whatever the method used to declare the array.
The value of the key is person[x]

Client Side Scripting (Unit 2) -By Yash Sawant (TYCO) Client Side Scripting (Unit 2) -By Yash Sawant (TYCO)
Array,Function and String Array,Function and String

Example : To access numeric Keys Function


 A function is a group of statements that perform specific tasks.
<script type="text/javascript">
 We can write the functions in the JavaScript for bringing the modularity in the script.
var employee = {101:"Akshay", 102:"Saideep", 103:"Anusha"}
var x = employee[101];  Separate functions can be created for each separate task.
document.write(x);
</script> Defining a Function
 We can define the function anywhere in the script either in head or body section or in both.
Example: To access string keys But it is standard practice to define the function in the head section and call that function
<script type="text/javascript"> from the body section
var employee = {"one":"Akshay", "two":"Saideep", "three":"Anusha"}  The declaration of a function start with the function keyword, followed by the name of the
var x = employee["one"]; function you want to create, followed by parentheses i.e. ( ) and finally place your function's
document.write(x); code between curly brackets {}.
</script>
Syntax for declaring a function without arguments:
An associative array is also an object
So we can create an associative array with the Object reserved word, then and assign keys and function functionName( )
values: {
// Code to be executed
}
<script type="text/javascript">
var employee = new Object(); Example:
employee["one"] = "Akshay"; // Defining function
employee["two"] = "Sai"; function sayHello( )
employee["three"] = "Amol"; {
for(var i in employee) alert("Hello, welcome to Spc!");
{ }
document.write(i + "=" + employee[i] + '<br>');
} Note: A function name must start with a letter or underscore character not with a number,
</script> optionally followed by the more letters, numbers, or underscore characters. Function names are
case sensitive, just like variable names.
Attributes of a JavaScript object are also keys
What is specific to objects in JavaScript is that attributes are also keys as we shall see in the Adding Parameters to Functions
demonstration. You can specify parameters when you define your function to accept input values at run time.
Thus, the same array can be created more simply: The parameters work like placeholder variables within a function; they're replaced at run time
by the values (known as argument) provided to the function at the time of invocation.
<script type="text/javascript"> Parameters are set on the first line of the function inside the set of parentheses, like this:
var employee = new Object();
employee.one = "Akshay"; function functionName(parameter1, parameter2, parameter3)
employee.two = "Sai"; {
employee.three = "Amol"; // Code to be executed
for(var i in employee) }
{ 1. Function with return_value and with no parameters
document.write(i + "=" + employee[i] + '<br>'); 2. Function with return_value and with parameter
} 3. Function with no return_value and with no parameters
</script> 4. Function with no return_value and with parameters

Client Side Scripting (Unit 2) -By Yash Sawant (TYCO) Client Side Scripting (Unit 2) -By Yash Sawant (TYCO)
Array,Function and String Array,Function and String

Example B] Calling a Function with Argument


The displaySum() function in the following example takes two numbers as arguments, simply In JavaScript, we can pass an argument to the function. Following JavaScript shows how to
add them together and then display the result in the browser. pass an argument to the function. In the following program I have written a simple function for
addition of two numbers. The values of two numbers are 10 and 20 respectively. Inside this
// Defining function function the addition of these two arguments is carried out and result is displayed on the
function displaySum (num1, num2) Browser page.
{ <!DOCTYPE html>
var total = num1 + num2; <html>
alert(total); <head>
} <script type = "text/javascript">
function add(a,b)
// Calling function {
displaySum(6, 20); // 0utputs: 26 c=a+b
displaySum(-5, 17); // 0utputs: 12 document.write("Addition "+c)
}
Calling a Function </script>
Defining a function does not execute it. Defining it simply names the function and specifies </head>
what to do when the function is called. <body>
Once a function is defined it can be called (invoked) from anywhere in the document, by typing <script type = "text/javascript">
its name followed by a set of parentheses. add(30,20);
Syntax: functionName( ); </script>
</body>
</html>
A] Calling a Function without an Argument
A function is called without passing any argument. In this case, all the required variables are
declared and used within that function. Following program shows how to call a functionwithout
C] Calling Function from HTML
passing an argument.
<!DOCTYPE html> For calling a function from HTML normally, JavaScript events are used. For example thefunction
<html> will be called in response to an event such as web page is loaded or unloaded by the browser.
<head> <!DOCTYPE html>
<script type = "text/javascript"> <html>
function add() <head>
{ <title></title>
var a = 10; <script type="text/javascript">
var b = 20;
c=a+b function sum() //function definition
document.write("Addition "+c) {
} var a=10,b=20;
</script> var tot=a+b;
</head> alert("Total is" + tot)
<body> }
<script type = "text/javascript"> </script>
add() </head>
</script>
<body onload= "sum()">
</body> </body>
</html> </html>

Client Side Scripting (Unit 2) -By Yash Sawant (TYCO) Client Side Scripting (Unit 2) -By Yash Sawant (TYCO)
Array,Function and String Array,Function and String

D] Function Calling another Function Scope of Variable and Argument


We can call one function from another function. This is called nested functions. In the following
 Scope is the block or area of program in which particular variable or argument is accessible.
code, there is a call for function difference() from function sum().
 The scope is defined using two types of variables - Local Scope and Global Scope.
<!DOCTYPE html>
.
<html>
Local Scope
<head>
If a variable is defined inside a function then that variable is a local variable and its scope is a
<title></title>
local scope. That also means, that the local variable is accessible only within a function in
which it is defined. It is not accessible outside that function.
<script type="text/javascript">
Following program shows the use of local variable.
JavaScript Example for Demonstrating scope of Local Variable
function sum(a,b)
{
<!DOCTYPE html>
var tot = a+b;
<html>
document.write("Total is" + tot)
<head>
difference(a,b);
<script type = "text/javascript">
}
function A()
function difference(a,b)
{
{
var a =100 //local variable
var result = a-b;
document.write ("from function A (): a is" + a)
document.write("<br>Difference is" + result)
}
function B()
}
{
</script>
document.write ("from function B (): a is" + a) // variable a is not accessible
</head>
}
<body>
</script>
<script type="text/javascript">
</head>
sum(50,34);
<body>
</script>
<script type = "text/javascript">
</body>
A( )
</html>
B( )
</script>
Returning Values from a Function </body>
A function can return a value back to the script that called the function as a result using the </html>
return statement. The value may be of any type, including arrays and objects. Output:
from function A (): a is100
The return statement usually placed as the last line of the function before the closing curly
bracket and ends it with a semicolon, as shown in the following example. Explanation:
(1) We have created two functions namely A() and B().
Example (2) Inside the A() function variable ‘a’ is declared and initialized to the value 100. The value of
function sum(a, b) this variable is displayed. Here variable ‘a’ is accessible.
{ (3) Inside the B() function, we are trying to display the value of same variable a. But the output
return a + b; does not display value of variable ‘a’ through function B(). This is because variable a is a local
} variable declared in function A(). Hence its scope is upto the function A(). Outside this function,
the variable a is not accessible.
var result = sum(1, 2);
alert( result );

Client Side Scripting (Unit 2) -By Yash Sawant (TYCO) Client Side Scripting (Unit 2) -By Yash Sawant (TYCO)
Array,Function and String Array,Function and String

Global Variable JavaScript String


A variable is called global variable, if it is defined outside the function. The variable having
The JavaScript string is an object that represents a sequence of characters.
global scope is accessible by any function.
JavaScript strings are used for storing and manipulating text.
Following example illustrates the use of global variable.
There are 2 ways to create string in JavaScript
JavaScript Example for Demonstrating the scope of Global Variable
1. By string literal
<!DOCTYPE html>
2. By string object (using new keyword)
<html>
<head>
1) By string literal
<script type = "text/javascript">
The string literal is created using double quotes.
var a =100//global variable
syntax:
function A()
var stringname="string value";
Let's see the simple example of creating string literal.
{
<script>
document.write ("from function A (): a is" + a)
var str="This is string literal";
}
document.write(str);
function B()
</script>
{
Output:
document.write ("<br> from function B (): a is" + a)
This is string literal
}
</script>
2) By string object (using new keyword)
</head>
Syntax:
<body>
var stringname=new String("string literal");
Here, new keyword is used to create instance of string.
<script type = "text/javascript"> Example:
<script>
A( )
B( ) var stringname=new String("hello javascript string");
</script> document.write(stringname);
</script>
</body>
Output:
</html>
hello javascript string
Output
from function A (): a is100
from function B (): a is100

Client Side Scripting (Unit 2) -By Yash Sawant (TYCO) Client Side Scripting (Unit 2) -By Yash Sawant (TYCO)
Array,Function and String Array,Function and String

JavaScript String Methods  Joining a String


Manipulating a String
1) using + operator.
Manipulating a string means, changing one string to another, joining two strings, changing the
string from upper case to lower case or from lower case to upper For Example
There are some commonly used methods of string <!DOCTYPE html>
<html>
<script type = "text/javascript">
Methods Description var firstName="AAA"
var lastName="BBB"
charAt() It provides the char value present at the specified index. var name=firstName+lastName
charCodeAt() It provides the Unicode value of a character present at the specified index. alert(name);
</script>
concat() It provides a combination of two or more strings. <body>
</body>
indexOf() It provides the position of a char value present in the given string. </html>
It provides the position of a char value present in the given string by Output: AAABBB
lastIndexOf()
searching a character from the last position.

It searches a specified regular expression in a given string and returns its


2) using concat() Method
search()
position if a match occurs. The JavaScript string concat() method combines two or more strings and returns a new
string. This method doesn't make any change in the original string.
replace() It replaces a given string with the specified replacement.

It is used to fetch the part of the given string on the basis of the specified Syntax
substr() string.concat(str1,str2,...,strn)
starting position and length.
Parameter
It is used to fetch the part of the given string on the basis of the specified str1,str2,...,strn - It represent the strings to be combined.
substring()
index. Return
It is used to fetch the part of the given string. It allows us to assign positive Combination of strings.
slice() Example 1:
as well negative index.
<script>
toLowerCase() It converts the given string into lowercase letter. var x="Spc";
var y=".com";
toLocaleLowerCase It converts the given string into lowercase letter on the basis of host?s
var z=" Tutorials";
() current locale.

toUpperCase() It converts the given string into uppercase letter. </script>


Output:
toLocaleUpperCase It converts the given string into uppercase letter on the basis of host?s Javatpoint.com Tutorials
() current locale.

toString() It provides a string representing the particular object.

valueOf() It provides the primitive value of string object.

It splits a string into substring array, then returns that newly created
split()
array.

trim() It trims the white space from the left and right side of the string.

Client Side Scripting (Unit 2) -By Yash Sawant (TYCO) Client Side Scripting (Unit 2) -By Yash Sawant (TYCO)
Array,Function and String Array,Function and String

Example 1
 Retrieving character from given Position: <script>
var x="Javatpoint";
charAt() Method document.writeln(x.charCodeAt(3));
The JavaScript string charAt() method is used to find out a character present at the specified </script>
index in a string. Output:
The index number starts from 0 and goes to n-1, where n is the length of the string. 97
Syntax
String.charAt(index) Example 2
Parameter In this example, we will not pass any index number with the method. In such case, it will
index - It represent the position of a character. return the Unicode value of first character.
Returns <script>
A char value var x="Javatpoint";
Example 1 document.writeln(x.charCodeAt());//It will return Unicode value of 'J'
<script> </script>
var str="Javatpoint"; Output:
document.writeln(str.charAt(4)); 74
</script>
Output:
t  Retrieving a Position of character in given String:
Example 2 1) indexOf() method
<script> The JavaScript string indexOf() method is used to search the position of a particular
var str="Javatpoint"; character or string in a sequence of given char values. This method is case-sensitive.
document.writeln(str.charAt()); //print first character The index position of first character in a string is always starts with zero. If an element is not
</script> present in a string, it returns -1.
Output:
J Syntax
indexOf(ch,index)
 Findig a Unicode of a character: It start searching the element from the provided index value and then returns the index
position of specified char value.
charCodeAt() Method index - It is optional which represent the index position from where search starts.
A computer can understand only numbers and characters.
Unicode is a standard that assigns a number to every character, number and symbol. Example 1
The JavaScript string charCodeAt() method is used to find out the Unicode value of a Here, we will print the position of a single character.
character at the specific index in a string.
<script>
The index number starts from 0 and goes to n-1, where n is the length of the string. It returns var web="Learn JavaScript on Javatpoint";
NaN if the given index number is either a negative number or it is greater than or equal to the document.write(web.indexOf('a'));
length of the string. </script>
Syntax Output:
string.charCodeAt(index) 2
Parameter
index - It represent the position of a character.
Return
A Unicode value

Client Side Scripting (Unit 2) -By Yash Sawant (TYCO) Client Side Scripting (Unit 2) -By Yash Sawant (TYCO)
Array,Function and String Array,Function and String

Example 2 Example:
In this example, we will provide the index value from where the search starts. <script>
var str="Javatpoint";
<script> document.writeln(str.substr(0,4));
var web="Learn JavaScript on Javatpoint"; </script>
document.write(web.indexOf('a',3));
</script> Output:
Output: Java
7

2) search() Method
The JavaScript string search() method is used to search the regular expression in the given 2) JavaScript String substring() Method
string. This method returns -1, if match is not found. The JavaScript string substring() method fetch the string on the basis of provided index and
returns the new sub string. It works similar to the slice() method with a difference that it
Syntax doesn't accepts negative indexes. This method doesn't make any change in the original string.
string.search(regexp)
Parameter Syntax
regexp - It represents the regular expression which is to be searched. string.substring(start,end)
Return Parameter
The position of searched character. start - It represents the position of the string from where the fetching starts.
end - It is optional. It represents the position up to which the string fetches.
Example: Return: Part of the string.
<script> Example
var str="JavaScript is a scripting language. Scripting languages are often interpreted"; <script>
document.writeln(str.search("scripting")); var str="Javatpoint";
</script> document.writeln(str.substring(0,4));
Output: </script>
16 Output:
Java

 Copying a substring 3) JavaScript String slice() Method


1) substr() Method
The JavaScript string slice () method is used to fetch the part of the string and returns the new
The JavaScript string substr() method fetch the part of the given string and return the new
string. It is required to specify the index number as the start and end parameters to fetch the
string. The number of characters to be fetched depends upon the length provided with the
part of the string. The index starts from 0. It allows us to assign positive as well negative index.
method. This method doesn't make any change in the original string.

Syntax
Syntax
string.slice(start,end)
string.substr(start,length)
Parameter
Parameter
start - It represents the position of the string from where the fetching starts.
start - It represents the position of the string from where the fetching starts.
end - It is optional. It represents the position up to which the string fetches.
length - It is optional. It represents the number of characters to fetch.
Return
Return: Part of the string.
Part of the string

Client Side Scripting (Unit 2) -By Yash Sawant (TYCO) Client Side Scripting (Unit 2) -By Yash Sawant (TYCO)
Array,Function and String Array,Function and String

Example 1 Example
Here, we will print the part of the string by passing starting and ending index. In the following example, various cases of strings such as only strings, strings with
numbers, etc have been taken and sent through the parseInt() function. Later on, their
<script>
integer values, if present, have displayed as shown in the output.
var str = "SpcAcademy";
document.writeln(str.slice(2,5));
</script> <!DOCTYPE html>
<html>
Output: <head>
row <meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
Example 2 <title></title>
Here, we will provide starting index only. In such case, the method fetches the string up to its
<script>
length.
var a = "10";
<script> document.write("value is " + parseInt(a)+"<br>");
var str = "SpcAcademy"; var b = "420-23-567";
document.writeln(str.slice(4)); document.write('value is ' + parseInt(b)+"<br>");
</script> var c = "string";
Output: document.write("value is " + parseInt(c)+"<br>");
wAcademy var d = "2String"
document.write("value is " + parseInt(d)+"<br>");
Example 3
</script>
In this example, we will provide negative number as an index. In such case, the method starts
fetching from the end of the string.
</head>
<script> <body>
var str = "SpcAcademy"; </body>
document.writeln(str.slice(-5)); </html>
</script>
Output
Output: value is 10
ademy value is 420
value is NaN
Convert a string into integer value is 2
To convert a string to an integer parseInt() function is used in javascript. parseInt() function
returns NaN( not a number) when the string doesn’t contain number.
If a string with a number is sent then only that number will be returned as the output.
This function won't accept spaces.
If any particular number with spaces is sent then the part of the number that presents before
space will be returned as the output.

syntax
parseInt(value);
This function takes a string and converts it into an integer. If there is no integer present in the
string, NaN will be the output.

Client Side Scripting (Unit 2) -By Yash Sawant (TYCO) Client Side Scripting (Unit 2) -By Yash Sawant (TYCO)
Array,Function and String Array,Function and String

 Changing case of String  Dividing Text


1) toLowerCase() Method
The JavaScript string toLowerCase() method is used to convert the string into lowercase String split()
letter. This method doesn't make any change in the original string. As the name implies, the split() method in JavaScript splits the string into the array of
Syntax substrings, puts these substrings into an array, and returns the new array. It does not change
string.toLowerCase() the original string.
Return
String in lowercase letter. Syntax
Example 1 string.split(separator, limit)
<script>
var str = "SPCACADEMY"; separator: It is an optional parameter. It specifies the point where the split should take place.
document.writeln(str.toLowerCase()); If it has multiple characters, then the sequence of the entire character must be found to split.
</script>
If the separator is not present in the given string, or if it is omitted, then the entire string
Output: becomes a single array element. In these cases, the returned array contains a single element
consisting of the entire string.
Spcacademy

If the separator is present at the beginning or the end of the string, then it still has the effect of
2) toUpperCase() Method splitting. The returned array consists of an empty string of zero length that appears at the
beginning or the last position of the returned array.
The JavaScript string toUpperCase() method is used to convert the string into uppercase letter.
This method doesn't make any change in the original string.
limit: It is also an optional parameter. It is a non-negative integer that specifies the number of
limits. It defines the higher limit on the number of splits to be found in the given string. If it is
Syntax
given, it splits the string at each occurrence of the specified separator. It stops when the limit
string.toUpperCase()
entries have been placed in the array.
Return
String in uppercase letter.
An array can contain fewer entries than the given limit. It happens when the end of the string
Example
is reached before the limit is reached.
<script>
var str = "javatpoint";
Let's understand the split() method using some examples.
document.writeln(str.toUpperCase());
</script>
Example1
Output:
In this example, the split() function splits the string str wherever the whitespace (" ") occurs and
JAVATPOINT
returns an array of strings. Here, we are using the limit argument and providing the value of the
limit argument to 3.

<script>
var str = 'Welcome to the Spc Computer Academy'
var arr = str.split(" ", 3);
document.write(arr);
</script>

Output
Welcome,to,the

Client Side Scripting (Unit 2) -By Yash Sawant (TYCO) Client Side Scripting (Unit 2) -By Yash Sawant (TYCO)
Array,Function and String

Form and Event Handling


Example2
In this example, we are using the letter 't' as the separator of the given string. The split() function
Form
will make an array of strings by splitting the given string at each occurrence of the letter 't'. A form is a section of a document which contains controls such as text fields, password fields,
Here, we are not specifying the limit argument.z checkboxes, radio buttons, submit button, menus etc.
An HTML form facilitates the user to enter data that is to be sent to the server for processing
<script> such as name, email address, password, phone number, etc. .
var str = 'Welcome to the Spc Academy' We use HTML form element in order to create the JavaScript form.
var arr = str.split("t");
document.write(arr); Typical form control objects -- also called "widgets" -- include the following:
</script>  Text box for entering a line of text
Output  Push button for selecting an action
Welcome ,o ,he Spc Academy  Radio buttons for making one selection among a group of options
 Check boxes for selecting or deselecting a single, independent option
Example 3
In this example, we are omitting the separator parameter. In the output, we can see that the The typical form looks like this.
returned array contains a single element consists of the given string. <html>
<head>
<script> <title>Switch</title>
var str = "Welcome to the Spc Academy" <script type="text/javascript">
var arr = str.split(); function fun()
document.write(arr); {
</script> alert("Hello, Your form is submitted")
}
Output </script>
Welcome to the Spc Academy </head>

<body>
<form name="Myform" action="" method="get">
Enter Something in Textbox
<input type="text" name="ID">
<input type="button" name="button" value="Back" onclick="fun()">
</form>
</body>
</html>

Output:

Client Side Scripting (Unit 2) -By Yash Sawant (TYCO) Client Side Scripting (Unit 3) -By Yash Sawant (TYCO)
Form and Event Handling Form and Event Handling

 form name="myform"
Notes on GET:
Defines and names the form. Elsewhere in the JavaScript you can reference this form by  Appends the form data to the URL, in name/value pairs
the name myform.  NEVER use GET to send sensitive data! (the submitted form data is visible in the URL!)
 The length of a URL is limited (2048 characters)
 action=""  GET is good for non-secure data, like query strings in Google

The action tag defines the action that the browser will take to tackle the form when it is
Notes on POST:
submitted. Here, we have taken no action.  Appends the form data inside the body of the HTTP request (the submitted form data is
The action attribute specifies a URL that will process the form submission.
not shown in the URL)
As this example is not designed to submit anything, the URL for the CGI program is
 POST has no size limitations, and can be used to send large amounts of data.
omitted.
 Form submissions with POST cannot be bookmarked.

 method="get"
4. onsubmit
It defines the method data is passed to the server when the form is submitted.
The purpose of the HTML onsubmit attribute is to execute the code specified, when the
associated form is submitted. HTML onsubmit attribute supports form element. There is no
 input type="text" defines the text box object. This is standard HTML markup.
default value of HTML onsubmit attribute.
Syntax
 input type="button" defines the button object. This is standard HTML markup except for
<form onsubmit="value" > .... </form>
the onClick handler.
Example:
<form name="myform" action="" method="get" onsubmit="alert('Form is submitted')">
 onclick="fun( )" is an event handler -- it handles an event, in this case clicking thebutton.
When the button is clicked, JavaScript executes the expression within the quotes. It calls
function fun(). <head>
<title>Switch</title>
<script type="text/javascript">
HTML Form Attributes
function fun()
1. Name:
The name attribute specifies the name of a form. The name attribute is used to reference {
elements in a JavaScript, or to reference form data after a form is submitted. alert("Hello, Your form is submitted")
Syntax
<form name="text"> }
</script>
2. The Action Attribute
The action attribute defines the action to be performed when the form is submitted. </head>
Usually, the form data is sent to a file on the server when the user clicks on the submit button. <body>
<form name="Myform" action="" method="get" onsubmit="fun()">
Tip: If the action attribute is omitted, the action is set to the current page.
Enter Something in Textbox
3. The Method Attribute
<input type="text" name="ID">
The method attribute specifies the HTTP method to be used when submitting the form data.
The form-data can be sent as URL variables (with method="get") or as HTTP post transaction <input type="submit" name="button" value="Submit">
(with method="post"). </form>
The default HTTP method when submitting form data is GET.
Example </body>
<form action="/action_page.php" method="get">
Example
<form action="/action_page.php" method="post">

Client Side Scripting (Unit 3) -By Yash Sawant (TYCO) Client Side Scripting (Unit 3) -By Yash Sawant (TYCO)
Form and Event Handling Form and Event Handling

 HTML Form Input Types


In HTML <input type=" "> is an important element of HTML form. The "type" attribute of input
element can be various types, which defines information field. Such as <input type="text"
3. <input type="button">:
The <input> type "button" defines a simple push button, which can be programmed to control a functionally on
name="name"> gives a text box.
any event such as, click event.
Following is a list of all types of <input> element of HTML.
1. <input type="text">:
<input> element of type "text" are used to define a single-line input text field. Example:
Example: <!DOCTYPE html>
<html>
<!DOCTYPE html>
<body>
<html>
<h2>The button Element</h2>
<body> <input type="button" value= "ClickMe!" onclick="alert('Hello World!')">
<h3>Input "text" type:</h3> </body>
<form> </html>
<label>Enter first name</label><br>
<input type="text" name="firstname"><br><br> Output:
<label>Enter last name</label><br>
<input type="text" name="lastname"><br>
<p>Note:The default maximum character lenght is 20 </p>
</form>
</body>
4. <input type="submit">:
</html>
The <input> element of type "submit" defines a submit button to submit the form to the server when the "click"
event occurs.
Output: Example:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form>
<label>Enter User name</label><br>
<input type="text" name="firstname"><br>
<label>Enter Password</label><br>
<input type="Password" name="password"><br>
2. Textarea <br><input type="submit" value="submit">
</form>
The HTML <textarea> tag is used to define a multi-line text input control. </body>
</html>
It can hold unlimited number of characters and the texts are displayed in a fixed-width font
(usually courier). Output:

Output:

After clicking on submit button, this will submit the form to server and will redirect the page
to action value.

Client Side Scripting (Unit 3) -By Yash Sawant (TYCO) Client Side Scripting (Unit 3) -By Yash Sawant (TYCO)
Form and Event Handling Form and Event Handling

5. <input type="radio">: 6. <input type="checkbox">:


The <input> type "radio" defines the radio buttons, which allow choosing an option between a The <input> type "checkbox" are displayed as square boxes which can be checked or unchecked to select the choices
set of related options. At a time only one radio button option can be selected at a time. from the given options.
 Using input type="radio" we can place radio button on the web page. Note: The "radio" buttons are similar to checkboxes, but there is an important difference
 We can create a group of some radio button component. between both types: radio buttons allow the user to select only one option at a time, whereas
checkbox allows a user to select zero to multiple options at a time.
<!DOCTYPE html>
<html> <!DOCTYPE html>
<body> <html>
<head>
<h2>Radio Buttons</h2>
<title></title>
<form>
</head>
<h3>Select your gender</h3> <body>
<input type="radio" id="male" name="gender" > <h2>Checkboxes</h2>
<label>Male</label><br> <form>
<input type="radio" id="female" name="gender"> <input type="checkbox" id="vehicle1" name="vehicle1" value="Bike">
<label>Female</label><br> <label for="vehicle1"> I have a bike</label><br>
<input type="radio" id="other" name="gender"> <input type="checkbox" id="vehicle2" name="vehicle2" value="Car">
<label for="vehicle2"> I have a car</label><br>
<label>Other</label>
<input type="checkbox" id="vehicle3" name="vehicle3" value="Boat">
<br><br>
<label for="vehicle3"> I have a boat</label><br><br>
<h3>Select your favourite color</h3> <input type="submit" value="Submit" onclick="alert('form submitted')">
<input type="radio" id="green" name="color"> </form>
<label>Green</label><br> </body>
<input type="radio" id="orange" name="color" > </html>
<label>Orange</label><br>
<input type="radio" id="white" name="color" > Output:
<label>White</label>
</form>
</body>
</html>

Output:

Client Side Scripting (Unit 3) -By Yash Sawant (TYCO) Client Side Scripting (Unit 3) -By Yash Sawant (TYCO)
Form and Event Handling Form and Event Handling

7. Select element Use <select> with <optgroup> tags:


The <select> element is used to create a drop-down list. <form>
The <select> element is most often used in a form, to collect user input. <label for="cars">Choose a car:</label>
The name attribute is needed to reference the form data after the form is submitted (if you omit <select name="cars" id="cars">
the name attribute, no data from the drop-down list will be submitted).
<optgroup label="Swedish Cars">
The id attribute is needed to associate the drop-down list with a label.
<option value="volvo">Volvo</option>
The <option> tags inside the <select> element define the available options in the drop-down list.
<option value="saab">Saab</option>
<!DOCTYPE html> </optgroup>
<html> <optgroup label="German Cars">
<body> <option value="mercedes">Mercedes</option>
<h1>The select element</h1> <option value="audi">Audi</option>
<p>The select element is used to create a drop-down list.</p> </optgroup>
<form> </select>
<label>Choose a car:</label> </form>
<select name="cars" id="cars">
<option value="Maruti">Maruti</option> 8. <input type="email">
<option value="BMW">BMW</option>
<option value="Lexus">Lexus</option> The <input type="email"> defines a field for an e-mail address.
<option value="Audi">Audi</option> The input value is automatically validated to ensure it is a properly formatted e-mail address.
To define an e-mail field that allows multiple e-mail addresses, add the "multiple" attribute.
</select>
<br><br>
<input type="submit" value="Submit">
</form> 9. <input type="password">
</body>
<input> elements of type password provide a way for the user to securely enter a password.
</html>
The element is presented as a one-line plain text editor control in which the text is masked so
that it cannot be read, usually by replacing each character with a symbol such as the asterisk
Output: ("*") or a dot ("•").

</head>
<body>
<form>
<label for="email">Email:</label>
<input type="email" id="email" name="email"><br><br>
<label for="pwd">Password:</label>
<input type="password" id="pwd" name="pwd" minlength="6" maxlength="8"><br><br>
<input type="submit" value="SignIn" >
</form>
</body>
</html>

Client Side Scripting (Unit 3) -By Yash Sawant (TYCO) Client Side Scripting (Unit 3) -By Yash Sawant (TYCO)
Form and Event Handling Form and Event Handling

10. <input type="reset"> Program to use all elements


<!DOCTYPE html>
<html>
The <input type="reset"> defines a reset button which resets all form values to its initial <body>
values. <form>
<label for="T1">First Name :</label><br>
<form> <input type="text" name="First Name" id="T1"><br><br>
<label for="email">Enter your email:</label> <label for="T2">Middle Name :</label><br>
<input type="email" id="email" name="email"><br><br> <input type="text" name="Middle Name" id="T2"><br><br>
<label for="T3">Last Name :</label><br>
<input type="text" name="Last Name" id="T3"><br><br>
<label for="pin">Enter a PIN:</label>
<label for="T1">Phone Number :</label><br>
<input type="text" id="pin" name="pin" maxlength="4"><br><br>
<input type="text" name="phone" id="T4" minlength="10" maxlength="10" size="10"/> <br> <br>

<input type="reset" value="Reset" onclick="alert('Reset Values')">


<input type="submit" value="Submit" onclick="alert('Submitted')"> Select Gender<br>
</form> <input type="radio" name="gender" value="Male" id="R1">
<label for="R1">Male</label><br>
<input type="radio" name="gender" value="Female" id="R2">
<label for="R2">Female</label><br>
<input type="radio" name="gender" value="Other" id="R3">
<label for="R3">Other</label><br><br>

<label>Select Year</label>
<select name="Year" id="S1">
<option value="FY">FY</option>
<option value="SY">SY</option>
<option value="TY">TY</option>
</select><br><br>

<label>Select Subjects of this semester</label><br>


<input type="checkbox" name="Subjects" id="C1" value="JavaScript">
<label for="C1">JavaScript</label><br>
<input type="checkbox" name="Subjects" id="C2" value="OSY">
<label for="C2">OSY</label><br>
<input type="checkbox" name="Subjects" id="C3" value="STE">
<label for="C3">STE</label><br>
<input type="checkbox" name="Subjects" id="C4" value="AJP">
<label for="C4">AJP</label><br><br>

<label>Address</label><br>
<textarea name="Address" rows="5" cols="20"></textarea><br><br>
<label for="E1">Eamil ID</label><br>
<input type="email" name="Email Id" id="E1"><br><br>
<label for="P1">Password</label><br>
<input type="Password" name="Password"><br><br>
<input type="Submit" name="Register" value="Register" onsubmit="alert('Form submitted
Successfully')">
<input type="reset" name="Resset" value="Reset" onclick="alert('Form Reset')">
</form>
</body>
</html>

Client Side Scripting (Unit 3) -By Yash Sawant (TYCO) Client Side Scripting (Unit 3) -By Yash Sawant (TYCO)
Form and Event Handling Form and Event Handling

 getElementById ( ) Method
The getElementById() method returns the element that has the ID attribute with the specified
value.
This method is one of the most common methods in the HTML, and is used almost every time
you want to manipulate, or get info from, an element on your document.
Returns null if no elements with the specified ID exists.
An ID should be unique within a page. However, if more than one element with the specified ID
exists, the getElementById() method returns the first element in the source code.

Syntax
getElementById(T1)

Example 1:
<!DOCTYPE html>
<html>
<body>
<p>Click the button to change the color of button.</p>
<input type="button" id="b1" value="click" onclick="myFunction()">
<script>
function myFunction()
{
document.getElementById("b1").style.background = "red";
}
</script>
</body>
</html>

Output:

 innerHTML property

Each HTML element has an innerHTML property that defines both the HTML code and the text
that occurs between that element’s opening and closing tag.
By changing element’s innerHTML after some user interaction, we can make much more
interactive pages.
For this, we must give some id to the element and then place that id in getElementById
function.

Example :

<!DOCTYPE html>
<html>
<body>

Client Side Scripting (Unit 3) -By Yash Sawant (TYCO) Client Side Scripting (Unit 3) -By Yash Sawant (TYCO)
Form and Event Handling Form and Event Handling

<form>
<p id="demo">Click the button to change the text in this paragraph.</p> 1. onfocus
<input type="button" name="Try it" onclick="myFunction()" value="Try it">
</form> The onfocus event occurs when an element gets focus.
<script>

<!DOCTYPE html>
function myFunction()
<html>
{
<head>
document.getElementById("demo").innerHTML = "Hello World"; <title></title>
} </head>
</script> <body>
</body> <script type="text/javascript">
</html> function myFunction()
{

Output: alert('Use Capital Letters');


}
</script>
<label for "T1"> Enter Name</label>
<input type="text" name="T1" id="T1" onfocus="myFunction()">
When you clicks on Try it button, text changes to Hello World. </body>
</html>

Example 2:

<!DOCTYPE html>
<html>
FORM EVENTS <body>
Event is something that causes JavaScript to execute the code. <p>When the input field gets focus, a function is triggered which changes the background-
JavaScript's interaction with HTML is handled through events that occur when the user or the color.</p>
browser manipulates a page. Enter your name:
When the page loads, it is called an event. <input id="t1" type="text" onfocus="myFunction()">
When the user clicks a button, that click too is an event. <script>
function myFunction()
Other examples include events like pressing any key, closing a window, resizing a window, etc.
{
document.getElementById("t1").style.background = "yellow";
Event Handler:
}
Each available event has an event handler, which is a block of code (usually a JavaScript </script>
function) that runs when the event fires. </body>
Execution of appropriate code on occurrence of event is called event handling. </html>
Output:
Form Events:
1. onfocus
2. onchange
3. onblur
4. onselect

Client Side Scripting (Unit 3) -By Yash Sawant (TYCO) Client Side Scripting (Unit 3) -By Yash Sawant (TYCO)
Form and Event Handling Form and Event Handling

 onselect  onchange
Execute a JavaScript after some text has been selected in an <input> element:
Supported HTML tags: <input type="file">, <input type="password">, <input Example 1:
type="text">, and <textarea> <!DOCTYPE html>
<html>
Example: <body>
<!DOCTYPE html>
<html> <p>Modify the text in the input field, then click outside the field to fire the onchange event.
<body> </p>

Some text: Enter some text:


<input type="text" value="Select Some Text" onselect="myFunction()"> <input type="text" name="txt" value="Hello" onchange="myFunction(this.value)">
<script>
function myFunction() <script>
{ function myFunction(val)
alert("You have selected some text!"); {
} alert("The input value has changed. The new value is: " + val);
</script> }
</body> </script>
</html>
</body>
</html>
Output
Output:

Example 2:
<!DOCTYPE html>
<html>
<body>
<p>This example demonstrates how to assign an "onchange" event to an input element.</p>
Enter your name:
<input type="text" id="fname" onchange="myFunction()">
<p>When you leave the input field, a function is triggered which transforms the input text to
upper case.</p>
<script>
function myFunction()
{
var x = document.getElementById("fname");
x.value = x.value.toUpperCase();
}
</script>
</body>
</html>

Client Side Scripting (Unit 3) -By Yash Sawant (TYCO) Client Side Scripting (Unit 3) -By Yash Sawant (TYCO)
Form and Event Handling Form and Event Handling

Output: </script>
</body>
</html>

Output:

 onblur
The onblur event occurs when an object loses focus.
The onblur event is the opposite of the onfocus event.

<!DOCTYPE html>
<html>
<body>
<p>Write something in the input field, and then click outside the field to lose focus (blur).</p>
<input type="text" id="fname" onblur="myFunction()" > Example2: mouseover and mouseout events
<script>
function myFunction() <!DOCTYPE html>
{ <html>
alert("Input field lost focus."); <body>
} <p>This example demonstrates how to assign red color when the mouse is over Register
</script> button and assign Green color when the mouse is moved out from Register button </p>

</body>
</html> <input type="button" id="b1" value ="register" onmouseover="mouseOver()"
onmouseout="mouseOut()">
 mouseover and mouseout events <script>
function mouseOver()
Example1: mouseover and mouseout events
{
document.getElementById("b1").style.color = "Red";
<html>
}
<head>
function mouseOut()
<h1> Javascript Events </h1>
{
<h2 onmouseover="mouseoverevent()" onmouseout="onmouseoutevent()"> Keep cursor over
document.getElementById("b1").style.color = "Green";
me</h2>
}
</script>
</head>
</body>
<body>
</html>
<script language="Javascript" type="text/Javascript">
Output
function mouseoverevent()
{
alert("Welcome to Spc");
}
function onmouseoutevent()
{
alert("Welcome Spc World");
}

Client Side Scripting (Unit 3) -By Yash Sawant (TYCO) Client Side Scripting (Unit 3) -By Yash Sawant (TYCO)
Form and Event Handling Form and Event Handling

 onmouseup and onmousedown Event

<!DOCTYPE html>
<html>
<body>

<p id="myP" onmousedown="mouseDown()" onmouseup="mouseUp()">


Click the text! When the mouse button is pressed down over this paragraph, it sets the color of
the text to red. When the mouse button is released, it sets the color of the text to green.
</p>

<script>
function mouseDown()
{
document.getElementById("myP").style.color = "red"; Key Events
}

function mouseUp() onkeyup


{ This event occurs when the user has released the key. It will occur even if the key released
document.getElementById("myP").style.color = "green"; does not produce a character value.
}
</script> <!DOCTYPE html>
<html>
</body> <body>
</html>
<p>A function is triggered when the user releases a key in the input field. The function
Output: transforms the character to upper case.</p>
Enter your name: <input type="text" id="fname" onkeyup="myFunction()">
<script>
function myFunction()
{
var x = document.getElementById("fname");
 onmousemove x.value = x.value.toUpperCase();
<html> }
<head> </script>
<script> </body>
function sayHello() { </html>
alert("You are moving the mouse")
} Output:
</script>
</head>
<body>
<p> When you move cursor inside textarea, it gves alert</p>
<label>Comment</label>
<textarea name="Comment" onmousemove = "sayHello()">
</textarea>
</body>
</html>

Client Side Scripting (Unit 3) -By Yash Sawant (TYCO) Client Side Scripting (Unit 3) -By Yash Sawant (TYCO)
Form and Event Handling Form and Event Handling

 onkeydown Changing attribute values dynamically


This event occurs when the user has pressed down the key. It will occur even if the key pressed In javascript, we can change the value of any elements dynamically.
does not produce a character value. For example: If element is loaded with default value at the time of page load, then the values can be
<!DOCTYPE html> changed at runtime and we can notify to user about the modification of form element by alert.
<html> The onchange event occurs when the user changes value of an element.
<body>
Example 1:
<!DOCTYPE html>
<p>A function is triggered when the user is pressing a key in the input field.</p>
<html>
<input type="text" onkeydown="myFunction()">
<body>
<script>
function myFunction()
<p>Modify the text in the input field, then click outside the field to fire the onchange
{
event.</p>
alert("You pressed a key inside the input field");
}
Enter some text:
</script>
<input type="text" name="txt" value="Hello" onchange="myFunction(this.value)">
</body>
<script>
</html>
function myFunction(val)
{
Output:
alert("The input value has changed. The new value is: " + val);
}
</script>

</body>
 onkeypress </html>

This event occurs when the user presses a key that produces a character value. These include Output:
keys such as the alphabetic, numeric, and punctuation keys. Modifier keys such as ‘Shift’,
‘CapsLock’, ‘Ctrl’ etc. do not produce a character, therefore they have no ‘keypress’ event
attached to them.

<!DOCTYPE html>
<html>
<body>
<p>A function is triggered when the user is pressing a key in the input field.</p>
<input type="text" onkeypress="myFunction()">
<script>
function myFunction() {
alert("You pressed a key inside the input field");
}
</script>
</body>
</html>
Output:

Client Side Scripting (Unit 3) -By Yash Sawant (TYCO) Client Side Scripting (Unit 3) -By Yash Sawant (TYCO)
Form and Event Handling Form and Event Handling

Changing Option List Dynamically Output:

Example 1
<html>
<head>
<p>Change option List according to User Selection </p>
<script language ="javascript" type="text/javascript">
function DisplayList(ElementValue)
{
with (document.forms.frm1) Q] Write a HTML script which displays 2 radio buttons to the users for fruits and
{ vegetables and 1 option list. When user select fruits radio button option list should
if (ElementValue == 1) present only fruits names to the user & when user select vegetable radio button option
{ list should present only vegetable names to the user
op1[0].text = "WPD"
op1[0].value = 1 <html>
op1[1].text = "PIC" <head>
op1[1].value = 2
op1[2].text = "Maths" <title>HTML Form</title>
op1[2].value = 3
<script language="javascript" type="text/javascript">
}
if (ElementValue == 2) function updateList(ElementValue)
{
{
op1[0].text = "OOP"
op1[0].value = 1 with(document.forms.myform)
op1[1].text = "DSU"
{
op1[1].value = 2
op1[2].text = "DBMS" if(ElementValue == 1)
op1[2].value = 3
} {
} optionList[0].text="Mango";
}
</script> optionList[0].value=1;
</head> optionList[1].text="Banana";
<body>
<form name="frm1"> optionList[1].value=2;
<select name="op1" size="3"> optionList[2].text="Apple";
<option Value=1> WPD
<option Value=2>PIC optionList[2].value=3;
<option Value=3>Maths }
</select>
<br> if(ElementValue == 2)
<input type="radio" name="subjects" checked="true" value=1 onclick = {
"DisplayList(this.value)"> First Year
<input type="radio" name="subjects" value=2 onclick="DisplayList(this.value)">Second Year optionList[0].text="Potato";
<br> optionList[0].value=1;
<input name="Submit" value="Submit" type="submit">
</form> optionList[1].text="Cabbage";
</body>
optionList[1].value=2;
<html>
optionList[2].text="Onion";

Client Side Scripting (Unit 3) -By Yash Sawant (TYCO) Client Side Scripting (Unit 3) -By Yash Sawant (TYCO)
Form and Event Handling Form and Event Handling

optionList[2].value=3;
}  Evaluating Checkbox Selection
} <html>
<head>
}
<title>Evaluating Checkboxes</title>
</script> <h3>Select the subjects</h3>
<script language="Javascript" type="text/javascript">
</head> function show()
<body> {
var x='You Selected '
<form name="myform" action="" method="post"> with (document.forms.frm1)
<p> {
if (a.checked == true)
<select name="optionList"> {
<option value="1">Mango</option> x+=a.value + " "
}
<option value="2">Banana</option> if (b.checked == true)
<option value="3">Apple</option> {
x+=b.value + " "
</select> }
<br><br> if (c.checked == true)
{
<input type="radio" name="grp1" value=1 checked="true" x+=c.value + " "
}
onclick="updateList(this.value)">Fruits
if (d.checked == true)
<input type="radio" name="grp1" value=2 {
x+=d.value + " "
onclick="updateList(this.value)">Vegetables
}
<br> if (e.checked == true)
{
<input name="Submit" value="Submit" type="submit">
x+=e.value + " "
</p> }
}
</form>
document.write(x)
</body> }
</script>
</html> </head>
<body>
<form name="frm1" action="" method="post">
<P>
<input type="checkbox" name="a" value="PIC">C
<br>
<input type="checkbox" name="b" value="C++">C++
<br>
<input type="checkbox" name="c" value="java">JAVA
<br>
<input type="checkbox" name="d" value="php">PHP
<br>
<input type="checkbox" name="e" value="jscript">JAVASCRIPT
<br><br>

Client Side Scripting (Unit 3) -By Yash Sawant (TYCO) Client Side Scripting (Unit 3) -By Yash Sawant (TYCO)
Form and Event Handling Form and Event Handling

<input type="reset" name="r1" value="Show" onclick="show()" >  Changing a label dynamically


</P>
</form>
<html>
</body>
<head>
</html>
<title>Changing Labels</title>
<script language="Javascript" type="text/javascript">
Output: function show(ElementValue)
{
with (document.forms.frm1)
{
if (ElementValue == 'State')
{
b1.value = 'City'
op1[0].text = 'Maharshtra'
op1[0].value = 1
op1[1].text = 'Gujarat'
op1[1].value = 2
op1[2].text = 'Andra Pradesh'
op1[2].value = 3
}
if (ElementValue == 'City')
{
b1.value = 'State'
op1[0].text = 'Ahmednagar'
op1[0].value = 1
op1[1].text = 'Pune'
op1[1].value = 2
op1[2].text = 'Mumbai'
op1[2].value = 3
}
}
}
</script>
</head>
<body>
<form name="frm1">
<select name="op1" size="3">
<option value=1>Maharashtra
<option value=2>Gujarat
<option value=3>Andra Pradesh
</select>
<br><br>
<input name="Submit" value="Submit" type="submit">
<input type="reset" name="b1" value="City" onclick="show(this.value)">
</form>
</body>
</html>

Client Side Scripting (Unit 3) -By Yash Sawant (TYCO) Client Side Scripting (Unit 3) -By Yash Sawant (TYCO)
Form and Event Handling Form and Event Handling

Manipulating form elements  Disabling Elements


1. Disabled form fields or elements values don’t post to the server for processing.
<html>
2. Disabled form fields or elements don’t get focus.
<head> 3. Disabled form fields or elements are skipped while tab navigation.
<script language="Javascript" type="text/javascript">
function addEmail()
{ <html>
<head>
with (document.forms.myform)
<script language="Javascript" type="text/javascript">
{ function disable()
if (Fname.value.length > 0 && Lname.value.length > 0 ) {
{ document.forms.myform.Fname.disabled=true;
Email.value = Fname.value.charAt(0)+ Lname.value +'@xyz.com'; }
document.write(Email.value) function enable()
} {
} document.forms.myform.Fname.disabled=false;
} }
</script> </script>
</head>
</head>
<body>
<body>
<form name="myform" action="" method="post">
<form name="myform" action="" method="post"> First Name: <input type="text" name="Fname">
First Name: <input type="text" name="Fname"> <br> <input type="button" name="b1" value="Disable" onclick="disable()">
Last Name: <input type="text" name="Lname"><br> <input type="button" name="b2" value="Enable" onclick="enable()">
Email: <input type="hidden" name= "Email" id="T1"><br> </form>
<input name="submit" value="submit" type="button" onclick="addEmail()"> </body>
</form> </html>
</body>
</html></html> OUTPUT

Output

Client Side Scripting (Unit 3) -By Yash Sawant (TYCO) Client Side Scripting (Unit 3) -By Yash Sawant (TYCO)
Form and Event Handling Cookies and Browser Data

 Read Only Elements Cookies:


Read Only form fields or elements values post to the server for processing. A cookie is a small text file that a web site saves on your PC, mobile phone or other device, containing
Read Only form fields or elements get focus. information about your browsing on that site.
Read Only form fields or elements are included while tab navigation. Cookies are necessary to facilitate browsing and make it more convenient; they do not harm your
computer.
<!DOCTYPE html>
<html>
<head> Why are cookies used on this website?
<title></title> Cookies are an essential part of how our website operates. The main purpose of our cookies is to
<script type="text/javascript"> improve your browsing experience.
function readonly() For example, to remember your preferences (language, country, etc.) during browsing and on future
{
visits.
document.forms.frm1.Fname.readOnly=true;
} The information collected in cookies also enables us to improve our website, for example, by
</script> estimating user numbers and ways users use the site, adapting the site to individual user's interests,
</head> speeding up searches, etc.
<body> Sometimes, if we have obtained your consent(permission), we can use cookies, tags or other similar
<form name="frm1"> instruments to obtain information that enables us to show you advertising based on your navigation
Enter Name <input type="text" name="Fname">
habits on our own web site, those of other suppliers or in other ways.
<input type="button" name="b1" value= "Read Only" onclick="readonly()">
</form>
</body>
</html> Basics of Cookies
 Cookies is a small piece of data stored in a file on your computer.
Output  The information present in the cookies is accessed by the web browser
A cookie contains the information as a string generally in the form of a name-value pair
separated by semi-colons.
 It maintains the state of a user and remembers the user's information among all the web
pages.
 Cookie is a small text file which contains following data:
- A name-value pair containing the actual data
- An expiry date after which it is no longer valid
- The domain and path of the server

Client Side Scripting (Unit 3) -By Yash Sawant (TYCO) Client Side Scripting (Unit 4) -By Yash Sawant (TYCO)
Cookies and Browser Data Cookies and Browser Data

 How Cookies Works? Example Write a JavaScript for creating a cookie for the user name.
o When a user sends a request to the server, then each of that request is treated as a new request
sent by the different user. <html>
o So, to recognize the old user, we need to add the cookie with the response from the server to <head>
browser at the client-side.
o Now, whenever a user sends a request to the server, the cookie is added with that request <script type = "text/javascript">
automatically. Due to the cookie, the server recognizes the users. function WriteCookie()
{
if( document.myform.customer.value == "" )
{
alert("Enter some value!");
return;
}
cookievalue = escape(document.myform.customer.value) + ";";
document.cookie="name=" + cookievalue;
Cookies remembers the information about the user in the following ways -
document.write ("Setting Cookies : " + "name=" + cookievalue );
Step 1: When the user visits the web page his/her name can be stored in a cookie
}
Step 2: Next time when the user visits the page, the cookie remembers his/her name.
</script>
</head>
There are two types of cookies: Session cookies and persistent cookies
<body>
Session Cookies : Session cookies is a cookie that remains in temporary memory only
<form name = "myform" action = "">
while user is reading and navigating the web site. The cookie is automatically deleted
Enter name: <input type = "text" name = "customer"/>
when the user exits the browser application.
<input type = "button" value = "Set Cookie" onclick = "WriteCookie()">
</form>
Persistent Cookies : A persistent cookie is a cookie that is assigned an expiration date. A
</body>
persistent cookie is written to the computer's hard disk and remains there until the
</html>
expiration date has been reached; then it is deleted.

Now your machine has a cookie called name. You can set multiple cookies using multiple key =
Creating Cookies value pairs separated by comma.
JavaScript can create, read or delete a cookie using document.cookie property
The simplest way to create a cookie is to assign a string value to the document.cookie object,  Reading a Cookie Value
which looks like this.
document.cookie = "key1 = value1;key2 = value2;expires = date"; It is a common practice to create a cookie and then read the value of the created cookie.
The document.cookie string will keep a list of NAME=VALUE pairs separated by semicolons, name
document.cookie = "username=Spc"; is the name of a cookie and value is its string value.
Using the split() function the string of cookies is break into key and values.
Here the expires attribute is optional. The split() method finds the = character in the cookie, and then take all the characters to the left of
If you provide this attribute with a valid date or time, then the cookie will expire on a given date the= and store them into array [0].
or time and thereafter, the cookies' value will not be accessible. Next the split() method takes all the characters from the right of the = up to semicolon ( ; ) but not
Including the semicolon, and assign those characters to array[1]
Note − Cookie values may not include semicolons, commas, or whitespace. For this reason, you may Thus we can obtain the name value pair in array[0] and array[1] respectively.
want to use the JavaScript escape() function to encode the value before storing it in the cookie. If
you do this, you will also have to use the corresponding unescape() function when you read the Following example illustrates how to read the cookies value.
cookie value.

Client Side Scripting (Unit 4) -By Yash Sawant (TYCO) Client Side Scripting (Unit 4) -By Yash Sawant (TYCO)
Cookies and Browser Data Cookies and Browser Data

Setting Cookies Expiry Date


<html>
<head> You can extend the life of a cookie beyond the current browser session by setting an expiration date
<script type = "text/javascript"> and saving the expiry date within the cookie. This can be done by setting the
function ReadCookie() ‘expires’ attribute to a date and time.
{ Example
var allcookies = document.cookie;
Try the following example. It illustrates how to extend the expiry date of a cookie by 1 Month.
document.write ("All Cookies : " + allcookies );
<html>
// Get all the cookies pairs in an array <head>
cookiearray = allcookies.split(';'); <script type = "text/javascript">

function WriteCookie() {
// Now take key value pair out of this array var now = new Date();
for(var i=0; i<cookiearray.length; i++) now.setMonth( now.getMonth() + 1 );
{ cookievalue = escape(document.myform.customer.value) + ";"
name = cookiearray[i].split('=')[0];
value = cookiearray[i].split('=')[1]; document.cookie = "name=" + cookievalue;
document.write ("Key is : " + name + " and Value is : " + value); document.cookie = "expires=" + now.toUTCString() + ";"
document.write ("Setting Cookies : " + "name=" + cookievalue );
} }
}
//--> </script>
</script> </head>
</head>
<body>
<form name = "myform" action = "">
<body>
Enter name: <input type = "text" name = "customer"/>
<form name = "myform" action = ""> <input type = "button" value = "Set Cookie" onclick = "WriteCookie()"/>
<p> click the following button and see the result:</p> </form>
<input type = "button" value = "Get Cookie" onclick = "ReadCookie()"/> </body>
</form> </html>
</body>
</html>

Note − There may be some other cookies already set on your machine. The above code will display
all the cookies set on your machine.

Client Side Scripting (Unit 4) -By Yash Sawant (TYCO) Client Side Scripting (Unit 4) -By Yash Sawant (TYCO)
Cookies and Browser Data Cookies and Browser Data

Deleting a Cookie It is possible to open a new browser window from a currently running JavaScript .
For that purpose the window object is used.
Sometimes you will want to delete a cookie so that subsequent attempts to read the cookie return This window object has various useful properties and methods.
nothing. To do this, you just need to set the expiry date to a time in the past. The window.open() method is used to open a new browser window or a new tab depending on
Example the browser setting and the parameter values.

Try the following example. It illustrates how to delete a cookie by setting its expiry date to one
Syntax
month behind the current date.
Window.open(URL,name,style)
<html>
<head>
<script type = "text/javascript">
function WriteCookie() {
var now = new Date(); URL Optional. Specifies the URL of the page to open. If no URL is specified, a new
now.setMonth( now.getMonth() - 1 ); window/tab with about:blank is opened
cookievalue = escape(document.myform.customer.value) + ";"
name Optional. Specifies the target attribute or the name of the window. The following values
document.cookie = "name=" + cookievalue; are supported:
document.cookie = "expires=" + now.toUTCString() + ";"
 _blank - URL is loaded into a new window, or tab. This is default
document.write("Setting Cookies : " + "name=" + cookievalue );
 _parent - URL is loaded into the parent frame
}
</script>  _self - URL replaces the current page
</head>
style Optional. A comma-separated list of items, no whitespaces. The following values are
<body> supported:
<form name = "myform" action = "">
Enter name: <input type = "text" name = "customer"/>
<input type = "button" value = "Set Cookie" onclick = "WriteCookie()"/> fullscreen=yes|no|1|0 Whether or not to display the browser in full-
</form> screen mode. Default is no.
</body>
</html> height=pixels The height of the window. Min. value is 100

left=pixels The left position of the window. Negative values


not allowed

menubar=yes|no|1|0 Whether or not to display the menu bar

resizable=yes|no|1|0 Whether or not the window is resizable.

scrollbars=yes|no|1|0 Whether or not to display scroll bars. IE, Firefox


& Opera only

status=yes|no|1|0 Whether or not to add a status bar

titlebar=yes|no|1|0 Whether or not to display the title bar.

toolbar=yes|no|1|0 Whether or not to display the browser toolbar.

4.2 Browser top=pixels The top position of the window. Negative values
not allowed

Opening a Window

Client Side Scripting (Unit 4) -By Yash Sawant (TYCO) Client Side Scripting (Unit 4) -By Yash Sawant (TYCO)
Cookies and Browser Data Cookies and Browser Data

width=pixels The width of the window. Min. value is 100 Example 3: Open Specified URL

<!DOCTYPE html>
<html>
Example 1: Open an about:blank page in a new window/tab
<body>
<p>Click the button to open a new browser window.</p>
<!DOCTYPE html>
<button onclick="myFunction()">Try it</button>
<html>
<script>
<body>
function myFunction() {
window.open("https://spccomputeracademy.business.site/");
<p>Click the button to open an about:blank page in a new browser window that is 200px
}
wide and 100px tall.</p>
</script>

<button onclick="myFunction()">Try it</button>


</body>
</html>
<script>
function myFunction() {
var myWindow = window.open("", "", "width=200,height=100");
} Window Position
</script>
We can set the desired position for the window.
</body> Using the left and top attribute values the window position can be set.
</html
<!DOCTYPE html>
<html>
Example 2: <body>
Replace the current window with a new window:
<p>Setting position of window.</p>
<!DOCTYPE html>
<html> <button onclick="myFunction()">Try it</button>
<body>
<script>
<p>Click the button to put the new window in the current window.</p> function myFunction() {
window.open("", "", "left=200,top=100,width=600,height=600");
<button onclick="myFunction()">Try it</button> }
</script>
<script>
function myFunction() { </body>
var myWindow = window.open("", "_self"); </html>
myWindow.document.write("<p>I replaced the current window.</p>");
}
</script>
4.2.4 Changing the content of window
</body> By writing some text to the newly created window we can change content of window
</html>

Client Side Scripting (Unit 4) -By Yash Sawant (TYCO) Client Side Scripting (Unit 4) -By Yash Sawant (TYCO)
Cookies and Browser Data Cookies and Browser Data

<html>  It is simple to open multiple windows. Using Open() method in a loop.


<body>
<p>Click the button to open a new tab </p> Example
<button onclick="NewTab()">
Open Window <html>
</button> <body>
<script> <p>Click the button to open a new tab </p>
function NewTab() { <button onclick="NewTab()">Open Window</button>
var mywin=window.open("","","width=200,height=200") <script>
mywin.document.write("<p>This line is written in current window</p>") function NewTab() {
} for(i=0;i<5;i++)
</script>
</body> {
</html> var mywin=window.open("","","width=100,height=100")}
}
4.2.5 Closing a Window </script>
</body>
The most simple operation about the window is to close it. It can be closed using the function </html>
close()

<!DOCTYPE html>
<html>
<body>

<button onclick="openWin()">Open "myWindow"</button>


<button onclick="closeWin()">Close "myWindow"</button>
Timers
<script>
var myWindow;
setTimeout( )
function openWin() {
myWindow = window.open("", "", "width=200,height=100"); <!DOCTYPE html>
myWindow.document.write("<p>This is 'myWindow'</p>"); <html lang="en">
} <head>
<title>JavaScript Execute a Function after Some Time</title>
function closeWin() { </head>
myWindow.close(); <body>
} <script type="text/JavaScript">
</script> function myFunction()
{
</body> alert('Hello World!');
</html> }
</script>

4.2.6 Multiple Window at a Glance


 It is possible to open up multiple windows at a time.

Client Side Scripting (Unit 4) -By Yash Sawant (TYCO) Client Side Scripting (Unit 4) -By Yash Sawant (TYCO)
Cookies and Browser Data Cookies and Browser Data

<br><br><br><br><br><br><br><br>
<button onclick="setTimeout(myFunction, 2000)">Click Me</button>
<p><strong>Note:</strong> Alert popup will be displayed 2 seconds after clicking the <P> ------------ Window Scrolled</p>
button.</p> </body>
</body> </html>
</html>

BROWSER LOCATION AND HISTORY

scrollTo() 1. window.location.pathname :
Gives complete path at which the web page is located.
<html> 2. window.location.hostname:
<head> Gives name of host on which the webpage is running. It gives domain name
3. window.location.protocol:
<script type = "text/javascript"> Gives the protocol used for the webpage. Such as HTTP, HTTPS
function scrollwindow()
{ Q Write a JavaScript code to get a pathname.
window.scrollTo(0,200);
} <html>
<head>
</script> <script type="text/javascript">
function display()
</head> {
<body> document.getElementById("ID").innerHTML = "This web page is at path:" +
window.location.pathname;
<p>click to scroll</p> }
<input type="button" value="Scroll Window" onclick="scrollwindow()"> </script>
<p>A</p> </head>
<body>
<br><br><br><br><br><br> <input type="button" value="GetPath" onclick="display()">
<p id="ID"></p>
<p>B</p>

<br><br><br><br><br><br>

<p>C</p>

<br><br><br><br><br><br>

<p>D</p>

<br><br><br><br><br><br>

<p>E</p>

Client Side Scripting (Unit 4) -By Yash Sawant (TYCO) Client Side Scripting (Unit 4) -By Yash Sawant (TYCO)
Cookies and Browser Data Cookies and Browser Data

</body> {
</html> window.history.back();
}
Q Write a JavaScript code to get the protocol. function next()
<html> {
<head> window.history.forward();
<script type="text/javascript"> }
function display() </script>
{ </head>
document.getElementById("ID").innerHTML = "The protocol of Web Page is:" + <body>
window.location.protocol;
} <input type="button" value="Previous" onclick="previous()">
</script> <input type="button" value="Next" onclick="next()">
</head>
<body> </body>
<p>Click the button to get the Protocol</p> </html>
<input type="button" value="GetProtocol" onclick="display()">
<p id="ID"></p>
</body>
</html>

Q Write a JavaScript code to get the hostname of webpage.

<html>
<head>
<script type="text/javascript">
function display()
{
document.getElementById("ID").innerHTML = "The hostname of Web Page is:" +
window.location.hostname;
}
</script>
</head>
<body>
<input type="button" value="GetHost" onclick="display()">
<p id="ID"></p>
</body>
</html>

History
<html>
<head>
<script type="text/javascript">
function previous()

Client Side Scripting (Unit 4) -By Yash Sawant (TYCO) Client Side Scripting (Unit 4) -By Yash Sawant (TYCO)
Regular Expressions, Rollover and Frames

Regular Expressions, Rollover and Frames Q] Write a program to check whether the string contains the given pattern or not.

<!DOCTYPE html>
JavaScript Regular Expressions <html>
A regular expression is a sequence of characters that forms a search pattern.
The search pattern can be used for text search and text replace operations. </head>
What Is a Regular Expression? <script type="text/javascript">
A regular expression is a sequence of characters that forms a search pattern. var p=/spc computer academy/i
When you search for data in a text, you can use this search pattern to describe what you are function testMatch()
searching for. {
A regular expression can be a single character, or a more complicated pattern. var str = T1.value;
Regular expressions can be used to perform all types of text search and text replace operations.
if(p.test(str))
Syntax {
/pattern/modifiers; alert("String " + str + " contains the given pattern")
}
Example else
var patt = /spc/i; {
Example explained:
alert("String " + str + " does not contains the given pattern")
/spc/i is a regular expression
spc is a pattern (to be used in a search). }
i is a modifier (modifies the search to be case-insensitive). }
</script>
</head>
Modifiers <body>
Modifiers are used to perform case-insensitive and global searches:
Modifier Description Enter string <input type="text" id="T1">
<button onclick="testMatch()">Try it</button>
g Perform a global match (find all matches rather than stopping after the first match) </body>
i Perform case-insensitive matching </html>

m Perform multiline matching

test()
The test() method tests for a match in a string.
This method returns true if it finds a match, otherwise it returns false.

Syntax

RegExpObject.test(string)

Client Side Scripting (Unit 5) -By Yash Sawant (TYCO) Client Side Scripting (Unit 5) -By Yash Sawant (TYCO)
Regular Expressions, Rollover and Frames Regular Expressions, Rollover and Frames

Brackets Quantifiers
Brackets ([]) have a special meaning when used in the context of regular expressions. They are The frequency or position of bracketed character sequences and single characters can be denoted
used to find a range of characters. by a special character. Each special character has a specific connotation. The +, *, ?, and $ flags all
follow a character sequence.
Sr.No. Expression & Description

1 [...] Sr.No. Expression & Description


Any one character between the brackets.
Ex: [abc] 1 p+
It matches any string containing one or more p's.
2 [^...]
Any one character not between the brackets. 2 p*
Ex: [^abc] It matches any string containing zero or more p's.

3 [0-9] 3 p?
It matches any decimal digit from 0 through 9. It matches any string containing at most one p.

4 [^0-9] 4 p{N}
Find any character NOT between the brackets (any non- It matches any string containing a sequence of N p's
digit)
5 p{2,3}
4 [a-z] It matches any string containing a sequence of two or three p's.
It matches any character from lowercase a through
lowercase z. 6 p{2, }
It matches any string containing a sequence of at least two p's.
5 [A-Z]
It matches any character from uppercase A through 7 p$
uppercase Z. It matches any string with p at the end of it.

6 [a-Z] 8 ^p
It matches any character from lowercase a through It matches any string with p at the beginning of it.
uppercase Z.

7 (x|y)
Find any of the alternatives specified

The ranges shown above are general; you could also use the range [0-3] to match any decimal digit ranging
from 0 through 3, or the range [b-v] to match any lowercase character ranging from b through v.

Client Side Scripting (Unit 5) -By Yash Sawant (TYCO) Client Side Scripting (Unit 5) -By Yash Sawant (TYCO)
Regular Expressions, Rollover and Frames Regular Expressions, Rollover and Frames

Metacharacter RegExp Methods


A metacharacter is simply an alphabetical character preceded by a backslash that acts to give the
combination a special meaning.

Metacharacter Description Method Description


. Find a single character, except newline or line terminator
test() Tests for a match in a string. It returns true or false.
\w Find a word character
A word character is a character from a-z, A-Z, 0-9, including the _ (underscore) Returns an array containing all of the matches, including capturing groups, or null if
match()
character. no match is found.

\W Find a non-word character Tests for a match in a string. It returns the index of the match, or -1 if the search
search()
fails.
\d Find a digit
Executes a search for a match in a string, and replaces the matched substring with a
replace()
\D Find a non-digit character replacement substring

\s Find a whitespace character Uses a regular expression or a fixed string to break a string into an array of
split()
substrings.
\S Find a non-whitespace character

\b Find a match at the beginning/end of a word, beginning like this: \bHI, end like
this: HI\b Matching Words

\B Find a match, but not at the beginning/end of a word The match() function is used to match a word in given string.
<!DOCTYPE html>
\0 Find a NULL character <html>
\0 returns the position where the NUL character was found. If no match is <body>
found, it returns -1.
<p>Enter some value in textbox and click on button to find characters NOT inside the
brackets.</p>
\n Find a new line character
\n returns the position where the newline character was found. If no match is
found, it returns -1.
<script>
\f Find a form feed character function myFunction() {
var patt1 = /student/gi;
\r Find a carriage return character var str = T1.value;
var result = str.match(patt1);
\t Find a tab character if(result!=null)
{
\v Find a vertical tab character alert(" Entered string contains word student");
\xxx Find the character specified by an octal number xxx
}
else
{
\xdd Find the character specified by a hexadecimal number dd
alert(" Entered string does not contain word student");
\udddd Find the Unicode character specified by a hexadecimal number dddd }
}
</script>
Enter string <input type="text" id="T1">
<button onclick="myFunction()">Try it</button>

</body>
</html>

Client Side Scripting (Unit 5) -By Yash Sawant (TYCO) Client Side Scripting (Unit 5) -By Yash Sawant (TYCO)
Regular Expressions, Rollover and Frames Regular Expressions, Rollover and Frames

Finding a Non Matching characters Enter string <input type="text" id="T1">


<button onclick="myFunction()">Try it</button>
The [^abc] expression is used to find any character NOT between the brackets.
^ symbol is placed at first position. </body>
Ex: [^abc] It finds any non matching character i.e. any character except a,b,c. </html>

<!DOCTYPE html>
<html> Matching Digits and Non Digits
<body>
The string may contain digits and non-digits i.e. characters other than digits.
<p>Enter some value in textbox and click on button to find characters NOT inside the Determining whether the string contains digits or non digits is a common task in any search
brackets.</p> pattern. Validating telephone number is one of the task where it requires Matching Digits.
This can be simplified by JavaScript by writing the regular expression.
If we want to search digits, then we use \d and if we want to search non-digits, then we use \D
<script>
function myFunction() { Example1 : To check whether string contains digits or not
var patt1 = /[^ht]/gi;
var str = T1.value; <!DOCTYPE html>
var result = str.match(patt1); <html>
alert("Non Matching characters are "+ result); </head>
} <script type="text/javascript">
</script> var p=/\d/i
Enter string <input type="text" id="T1"> function testMatch()
<button onclick="myFunction()">Try it</button> {
var str = T1.value;
</body> if(p.test(str))
</html> {
alert("String " + str + " contains the digits")
}
Entering Range of Characters: else
{
For matching any digit we need not have to enter every digit right from 0 to 9. alert("String " + str + " does not contains digits")
Similarly for matching letters we need not have to test with every single alphabet. We can achieve this by }
entering range of Characters. }
</script>
For example - to match a characters from ‘a’ to ‘d’ we must have a regular expression as [a-d]. Thus placing </head>
the range within a square bracket helps us to evaluate a complete range of set of characters. <body>
Enter string <input type="text" id="T1">
<!DOCTYPE html> <button onclick="testMatch()">Try it</button>
<html> </body>
<body> </html>

<p>Enter some value in textbox and click on button to find characters within the range.</p>

<script>
function myFunction() {
var patt1 = /[a-d]/gi;
var str = T1.value;
var result = str.match(patt1);
alert("characters within the range are "+ result);
}
</script>

Client Side Scripting (Unit 5) -By Yash Sawant (TYCO) Client Side Scripting (Unit 5) -By Yash Sawant (TYCO)
Regular Expressions, Rollover and Frames Regular Expressions, Rollover and Frames

Example 2 : To check whether string contains digits or not }


}
<!DOCTYPE html> </script>
<html> </head>
</head> <body>
<script type="text/javascript"> Enter string <input type="text" id="T1">
var p=/\D/g <button onclick="testMatch()">Try it</button>
function testMatch() </body>
{ </html>
var str = T1.value;
if(p.test(str)) Replacing a Text using Regular Expressions
{
alert("Enter only Numbers") By using replace function, we can replace the pattern in given string.
} The first parameter in the replace function is the string which is to be replaced and the second parameter is
else the string which replaces old string.
{ For example- Consider following JavaScript in which the word 'country' is replaced by 'India
alert("Correct Number")
}
}
</script> <!DOCTYPE html>
</head> <html>
<body> <head>
Enter Phone number <input type="text" id="T1"> <script type="text/javascript">
<button onclick="testMatch()">Try it</button> str="Welcome to Spc";
</body> document.write(str);
</html> function myfunction(str)
{
new_str=str.replace("Spc", "Spc Computer Academy");
Matching Punctuations and Symbols document.write(new_str);
• The special symbol w tells the browser to determine whether the text contains a letter, number, }
or an </script>
underscore. </head>
The W special symbol tells the browser to determine whether the text contains other than a letter, <body>
number, or an underscore. <br>
Using \W is equivalent to using [a-zA-Z0-9_]. The last_indicates underscore character. <input type="button" value="Replace" onclick="myfunction(str)">
</body>
Example to test whether string contains any punctuation or special symbols </html>

<!DOCTYPE html>
<html>
</head>
<script type="text/javascript">
var p=/\W/i
function testMatch()
{
var str = T1.value;
if(p.test(str))
{
alert("String " + str + " contains the special character")
}
else
{
alert("String " + str + " does not contain special character")

Client Side Scripting (Unit 5) -By Yash Sawant (TYCO) Client Side Scripting (Unit 5) -By Yash Sawant (TYCO)
Regular Expressions, Rollover and Frames Regular Expressions, Rollover and Frames

Frames The <frameset> Tag Attributes


HTML frames are used to divide your browser window into multiple sections where each section Following are important attributes of the <frameset> tag –
can load a separate HTML document.
A collection of frames in the browser window is known as a frameset. Sr Attribute & Description
The window is divided into frames in a similar way the tables are organized: into rows and
columns.
Using multiple views we can keep certain information visible and at the same time other views cols
are scrolled or replaced. Specifies how many columns are contained in the frameset and the size of each column.
You can specify the width of each column in one of the four ways −
Absolute values in pixels. For example, to create three vertical frames, use cols = "100,
500, 100".
A percentage of the browser window. For example, to create three vertical frames,
use cols = "10%, 80%, 10%".
1 Using a wildcard symbol.
For example, to create three vertical frames, use cols = "10%, *, 10%". In this case
wildcard takes remainder of the window.
As relative widths of the browser window.
For example, to create three vertical frames, use cols = "3*, 2*, 1*". This is an alternative
to percentages.
You can use relative widths of the browser window. Here the window is divided into
sixths: the first column takes up half of the window, the second takes one third, and the
third takes one sixth.
Creating Frames
rows
To use frames on a page we use <frameset> tag instead of <body> tag. This attribute works just like the cols attribute and takes the same values, but it is used
The <frameset> tag defines, how to divide the window into frames. The rows attribute of 2 to specify the rows in the frameset.
<frameset> tag defines horizontal frames and cols attribute defines vertical frames. For example, to create two horizontal frames, use rows = "10%, 90%".
Each frame is indicated by <frame> tag and it defines which HTML document shall open into the You can specify the height of each row in the same way as explained above for columns.
frame.
Example1: border
<frameset cols= “ 150, * ” > 3 This attribute specifies the width of the border of each frame in pixels.
For example, border = "5". A value of zero means no border.
will allow us to divide the window into two columns (i.e. in two vertical frames).
One frame occupying the size of 150 pixels and the other occupies the remaining portion of the frameborder
window. This attribute specifies whether a three-dimensional border should be displayed
4
between frames. This attribute takes value either 1 (yes) or 0 (no). For example
Example 2: frameborder = "0" specifies no border.
<frameset rows= " *, 120 ”>
will divide the window into two rows ( i.e. in two horizontal frames). framespacing
The second part of horizontal Frame will be of 120 pixels and upper horizontal frame will occupy This attribute specifies the amount of space between frames in a frameset. This can take
remaining portion of the window. 5 any integer value.
For example framespacing = "10" means there should be 10 pixels spacing between
Similarly we can also specify the frameset in percentage form. each frames.
For Example
<frameset rows=”30%, 70%”>

Client Side Scripting (Unit 5) -By Yash Sawant (TYCO) Client Side Scripting (Unit 5) -By Yash Sawant (TYCO)
Regular Expressions, Rollover and Frames Regular Expressions, Rollover and Frames

The <frame> Tag Attributes Example 1:


Following are the important attributes of <frame> tag –
<!DOCTYPE html>
<html>
Sr Attribute & Description
<head>
src <title>HTML Frames</title>
1 This attribute is used to give the file name that should be loaded in the frame. Its </head>
value can be any URL. For example, src = "/html/top_frame.htm" will load an HTML
file available in html directory. <frameset cols = "25%,50%,25%">
<frame name = "left" src = "pr4.html" />
name <frame name = "center" src = "pr4.html" />
This attribute allows you to give a name to a frame. It is used to indicate which frame <frame name = "right" src = "pr4.html" />
2 a document should be loaded into. This is especially important when you want to
create links in one frame that load pages into an another frame, in which case the <noframes>
second frame needs a name to identify itself as the target of the link. <body>Your browser does not support frames.</body>
</noframes>
frameborder </frameset>
3 This attribute specifies whether or not the borders of that frame are shown; it
overrides the value given in the frameborder attribute on the <frameset> tag if one </html>
is given, and this can take values either 1 (yes) or 0 (no).

marginwidth Example 2:
4 This attribute allows you to specify the width of the space between the left and
right of the frame's borders and the frame's content. The value is given in pixels. </html>
For example marginwidth = "10".
<!DOCTYPE html>
marginheight <html>
5 This attribute allows you to specify the height of the space between the top and
bottom of the frame's borders and its contents. The value is given in pixels. For <head>
example marginheight = "10". <title>HTML Target Frames</title>
</head>
noresize
By default, you can resize any frame by clicking and dragging on the borders of a <frameset cols = "200, *">
6 <frame name = "left" src = "pr4.html" />
frame. The noresize attribute prevents a user from being able to resize the frame. For
example noresize = "noresize". <frame name = "center" src = "pr4.html" />

scrolling <noframes>
This attribute controls the appearance of the scrollbars that appear on the frame. <body>Your browser does not support frames.</body>
7 </noframes>
This takes values either "yes", "no" or "auto". For example scrolling = "no" means it
should not have scroll bars. </frameset>

</html>

Client Side Scripting (Unit 5) -By Yash Sawant (TYCO) Client Side Scripting (Unit 5) -By Yash Sawant (TYCO)
Regular Expressions, Rollover and Frames Regular Expressions, Rollover and Frames

Rollover Multiple Actions for Rollover


Rollover means change in the appearance of the object, when user moves his or her mouse over an
object on the page <html>
The rollover effect is mainly used in web page designing for advertising purpose. <head>

Creating Rollover <script type="text/javascript">


function display1()
On many web pages, JavaScript rollovers are handled by adding an onmouseover and onmouseout
event on images. {
document.fruit.src='mango.jpeg'
(1) onmouseover is triggered when the mouse moves over an element document.getElementById('para').innerHTML="Trees of mango are larger than
(2) onmouseout is triggered when the mouse moves away from the element Pineapple"
}
Image Rollover
function display2()
<html>
<head> {
<title>Creating Rollover</title> document.fruit.src='pineapple.jpeg'
</head> document.getElementById('para').innerHTML="Trees of pineapple are smaller than
<body> mango"
<img src="mickey1.jpeg" boarder="0px" width="650px" height="550px" onmouseover="src= }
'mickey.jpeg'" onmouseout="src= 'mickey1.jpeg'">
</body> </script>
</html> </head>
<body>

Text Rollover
Text rollover is a technique in which whenever user rollover the text, JavaScript allows to change the page <a onmouseover="display1()">
element usually some graphics image. <br>
Carefully placed rollovers can enhance a visitors experience when browsing the web page. <b><u>mango</u></b>
<html> </a>
<body> <br>
<a> <a onmouseover="display2()">
<img src ="mango.jpeg" name="fruit" width="650px" height="550px"> <br>
</a> <b><u>Pineapple</u></b>
<a onmouseover="document.fruit.src='mango.jpeg'"> </a>
<br> <br><br><br>
<b><u>Mango</u></b> <a>
</a> <img src ="mango.jpeg" name="fruit" width="650px" height="550px">
<br><br><br> </a>
<p id="para">Trees of mango are larger than Pineapple </p>
<a onmouseover="document.fruit.src='banana.jpeg'">
<b><u>banana</u></b> </body>
</a> </html>
<br><br><br>
<a onmouseover="document.fruit.src='pineapple.jpeg'">
<b><u>pineapple</u></b>
</a>
<br><br/><br/>
</body>
</html>

Client Side Scripting (Unit 5) -By Yash Sawant (TYCO) Client Side Scripting (Unit 5) -By Yash Sawant (TYCO)

You might also like