Unit 1 CSS (Client Side Scripting)
Unit 1 CSS (Client Side Scripting)
Unit 1 CSS (Client Side Scripting)
A script is a small piece of program that can add interactivity to the website. For example, a script
could generate a pop-up alert box message, or provide a dropdown menu. This script could be
JavaScript or VBScript.
A script language is a subcategory of programming language with which you can write scripts.
Scripting languages need to be interpreted (Scanning the code line by line, not like compiler in one
go) instead of compiled. There is no scope of compiler in scripting languages. Scripting languages
are most widely used to create a website.
JavaScript, Perl, PHP, Python, VBScript are the most popular examples of scripting Languages.
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.
Features of JavaScript
JavaScript is a lightweight, interpreted programming language.
Interpreter Based Scripting Language
Case Sensitive
Designed for creating network-centric applications.
Integrated with HTML.
Open and cross-platform
Validating User’s Input : JavaScript is very useful while using forms. It has the capability to
validate user input for errors and also saves time. If the user leaves a required field empty or the
information is incorrect, JavaScript checks for them before sending the data over to the 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.
JavaScript Programming
Q] Explain <script> tag with example?
JavaScript can be implemented using JavaScript statements that are placed within the <script>...
</script> HTML tags in a web page.
You can place the <script> tags, containing your JavaScript, anywhere within your web page.
The <script> tag alerts the browser program to start interpreting all the text between these tags as
a script. A simple syntax of your JavaScript will appear as follows.
<script ...>
JavaScript code
</script>
The script tag takes two important attributes −
1. Language − This attribute specifies what scripting language you are using. Typically, its
value will be javascript. Although recent versions of HTML (and XHTML, its successor) have
phased out the use of this attribute.
2. Type – This attribute tells the browser that script is in plain text and text is organised in the
format of javascript.
So your JavaScript segment will look like −
<script language = "javascript" type = "text/javascript">
JavaScript code
</script>
But when formatted in a single line as follows, you must use semicolons −
<script language = "javascript" type = "text/javascript">
document.write("Hello"); document.write("Welcome to Arrow Academy")
</script>
Case Sensitivity
JavaScript is a case-sensitive language. This means that the language keywords, variables, function
names, and any other identifiers must always be typed with a consistent capitalization of letters.
So the identifiers Time and TIME will convey different meanings in JavaScript.
Comments in JavaScript
1JavaScript supports both C-style and C++-style comments, Thus −
Any text between a // and the end of a line is treated as a comment and is ignored by
JavaScript.
Any text between the characters /* and */ is treated as a comment. This may span multiple
lines.
Example
The following example shows how to use comments in JavaScript.
<script language = "javascript" type = "text/javascript">
// This is a comment. It is similar to comments in C++
/*
This is a multi-line comment in JavaScript
It is very similar to comments in C Programming
*/
</script>
JavaScript Placement
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.
Script in <body>...</body> section.
Script in <body>...</body> and <head>...</head> sections.
Script in an external file and then include in <head>...</head> section.
In the following section, we will see how we can place JavaScript in an HTML file in different ways.
Variable Declaration:
Before you use a variable in a JavaScript program, you must declare it.
Variables are declared with the var keyword as follows.
You can also declare multiple variables with the same var keyword as follows −
Variable Initialization:
Storing a value in a variable is called variable initialization.
You can do variable initialization at the time of variable creation or at a later point in time when you
need that variable.
</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 and type of a variable can change
during the execution of a program and JavaScript takes care of it automatically.
var:
1. A variable can be reassigned using var keyword
2. A variable can be redeclared using var keyword
let:
1. A variable can be reassigned using let keyword
2. A variable can not be redeclared using let keyword
Eg:
let b = 15.6;
b = “Academy” // Reassign
let b = 23.5 // Error
const:
In JavaScript, const is a keyword used to declare a variable that cannot be reassigned a new value. It
is similar to let, but the value of a const variable cannot be changed once it has been declared.
1. Variables defined with const cannot be Redeclared
2. Variables defined with const cannot be Reassigned
JavaScript const must be assigned a value when they are declared.
Example:
const PI = 3.14159265359;
Example 2:-
const PI = 3.141592653589793;
PI = 3.14; // This will give an error
PI = PI + 10; // This will also give an error
Global Variables − A global variable has global scope which means it can be defined anywhere in
your JavaScript code.
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 same
name.
If you declare a local variable or function parameter with the same name as a global variable, you
effectively hide the global variable.
Example:
<html>
<head>
</head>
</body>
</html>
1. You should not use any of the JavaScript reserved keywords as a variable name.
For example, break or boolean variable names are not valid.
4. JavaScript variable names are case-sensitive. For example, Name and name are two different
variables.
JavaScript provides different data types to hold different types of values. There are two types of data
types in JavaScript.
1. Primitive data type
2. Non-primitive (reference) data type
1.3 Objects
Real Life Objects, Properties, and Methods
In real life, a car is an object.
A car has properties like weight and color, and methods like start and stop:
All cars have the same properties, but the property values differ from car to car. All cars have the
same methods, but the methods are performed at different times.
Objects in JavaScript may be defined as, an unordered collection of related data of primitive
or reference types in the form of "key: value" pairs,
You access an object's properties and methods by using the dot syntax along with the object
name and its property or method.
B] Object Name
Each object is uniquely identified by a name or ID.
A web page contains many objects, some of which are the same kind of object. These objects can
be easily distinguishable by using its name or ID.
C] Property
A property is a data or value associated with an object.
Objects can have many data's associated with them depending on application of use.
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.
Hence, each object has its own set of properties. An object can be created with curly brackets
{...} with list of properties.
A property is a "key: value pair, where key is a string (also called a "property name"), and value
can be anything.
The following example creates a new JavaScript object with four properties:
syntax :
Spaces and line breaks are not important. An object definition can span multiple lines:
<script>
emp= {
id:102,
name:"Shyam Kumar",
salary:40000
}
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
2. Define and create a single object, with the keyword new. (By creating instance of Object)
Syntax:
var objectname=new Object();
Here, new keyword is used to create object.
Example:
<script>
var emp=new Object();
emp.id=101;
emp.name="Ravi Malik";
emp.salary=50000;
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
<!DOCTYPE html>
<html>
<head>
<title>Creating Object</title>
</head>
<body>
<script type="text/javascript">
/*Using Object Literal*/
emp = {name:"Akshay",id:17,salary:50000};
document.write("Name is "+emp.name+"<br>");
document.write("Id is "+emp.id+"<br>");
document.write("Salary is "+emp.salary+"<br>");
document.write("Name is "+teacher.name+"<br>");
document.write("Designation is "+teacher.designation+"<br>");
document.write("Salary is "+teacher.salary+"<br>");
function student(name,roll,marks)
{
this.name=name;
this.roll=roll;
this.marks= marks;
}
Example 1:
<html>
<head>
<title>Object</title>
</head>
<body>
<script>
var user = {
fname: " Computer ",
lname: " Engineering”
};
document.write(“User =” + user.fname +” “+ user. lname);
</script>
</body>
</html>
Output:
User – Computer Engineering
Example 2:
<html>
<head>
<title>Object</title>
</head>
<body>
<script>
var user = {
fname: " Computer ",
lname: " Engineering”
};
document.write(“User =” + user[“fname”] +” “+ user[“ lname”]);
</script>
</body>
</html>
Output:
User – Computer Engineering
Eg: Creating Object with properties, Method, array and object in it.
<html>
<head>
<title>Object</title>
</head>
<body>
<script>
var user = {
fname: "Arrow",
lname: "Academy",
age:25,
email:"arrowacademy@gmail.com",
fullname:function()
{
return this.fname+this.lname;
},
favmovies:["Dhoom","Sholay","3 Idiots"],
address:{city:"Ahmednagar", state:"Maharashtra"}
};
document.write("First Name is =" +user.fname+"<br>");
document.write("Last Name is =" +user.lname+"<br>");
document.write("Age is =" +user.age+"<br>");
document.write("Email is =" +user.email+"<br>");
document.write("Favaourite Movies are =" +user.favmovies[1]+"<br>");
document.write("Address is "+user.address.city+" "+user.address.state+"<br>");
document.write("Full Name is =" +user.fullname()+"<br>");
</script>
</body>
</html>
In JavaScript, we use the prompt() function to ask the user for input.
As a parameter, we input the text we want to display to the user.
Once the user presses “ok,” the input value is returned.
prompt returns the user input as a string, but if you want the user input to return a number instead
of a string, you can convert the string to an integer using parseInt()
<html>
<head>
</head>
<body>
<script type = "text/javascript">
var name = prompt("What is your name?");
var num1 = parseInt(prompt("Enter First Number"));
var num2 = parseInt(prompt("Enter Second Number"));
var sum = num1 + num2
document.write("Name is "+name);
document.write("Your Favourite Number is "+sum);
</script>
</body>
</html>
Arithmetic Operators
Comparison Operators
Logical (or Relational) Operators
Assignment Operators
Conditional (or ternary) Operators
Lets have a look on all operators one by one.
1) Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations on the operands.
Assume variable A holds 10 and variable B holds 20, then −
Sr. Operator & Description Example
2 - (Subtraction): Subtracts the second operand from the first Ex: A - B will give -10
Example:-
<!DOCTYPE html>
<html>
<head>
<title>Arithmetic Operators</title>
</head>
<body>
<script type="text/javascript">
var a=10,b=2;
var add=a+b
var sub=a-b
var mul=a*b
document.write("Addition is"+add+"<br>");
document.write("Subtraction is",sub+"<br>");
document.write("Multiplication is",mul+"<br>");
document.write("Division is",div+"<br>");
document.write("Remainder is",rem+"<br>");
document.write("Exponent is",exp+"<br>");
</script>
</body>
</html>
2) Assignment Operators
JavaScript supports the following assignment operators −
Sr. Operator & Description Example
= (Simple Assignment )
Ex: C = A + B will assign the
1 Assigns values from the right side operand to the left side
value of A + B into C
operand
3) Comparison Operators
JavaScript supports the following comparison operators −
Assume variable A holds 10 and variable B holds 20, then −
Sr. Operator & Description Example
= = (Equal)
1 Ex: (A == B) is not
Checks if the value of two operands are equal or not, if yes, then the
true.
condition becomes true.
!= (Not Equal)
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.
4) Logical Operators
Assume variable A holds 10, variable B holds 20, variable C holds 30, then −
Sr. Operator & Description Example
|| (Logical OR)
2 If any of its arguments are true, it returns true, otherwise it Ex: (A>B || B < C) is false.
returns false.
! (Logical NOT)
3 If a condition is true, then the Logical NOT operator will Ex: ! (A && B) is false.
make it false and vice versa.
5) Bitwise Operators
Assume variable A holds 2 and variable B holds 3, then −
Sr. Operator & Description Example
| (BitWise OR)
2 It performs a Boolean OR operation on each bit of its integer Ex: (A | B) is 3.
arguments.
^ (Bitwise XOR)
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
operand two is true, but not both.
~ (Bitwise Not)
4 Ex: (~B) is -4.
It is a unary operator and operates by reversing all the bits in the
2. Or
A=10001
B=11001
-------------------
1 1 0 0 1 (25)
3. XOR
A=10001
B=11001
---------------------
= 01000 (8)
Example:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script type="text/javascript">
var A = 17,B=25;
document.write("Result of AND operation is "+(A&B));
document.write("<br>");
document.write("Result of OR operation is "+(A|B));
document.write("<br>");
document.write("Result of XOR operation is "+(A^B));
document.write("<br>");
document.write("Result of NOT operation is "+(~A));
document.write("<br>");
document.write("Result of Leftshift operation is "+(A<<2));
document.write("<br>");
document.write("Result of Rightshift operation is "+(A>>2));
</script>
</body>
</html>
6) Ternary Operator
JavaScript includes special operator called ternary operator ?: that assigns a value to a variable
based on some condition. This is like short form of if-else condition.
Syntax:
<condition> ? <value1> : <value2>;
Ternary operator starts with conditional expression followed by ? operator. Second part (after ? and
before : operator) will be executed if condition turns out to be true. If condition becomes false then
third part (after :) will be executed.
Example:
var a=10,b=25;
large=a>b?a:b;
document.write("Largest Number is ",large);
A] if..else statement
Flow Chart of if-else
1) if statement
The if statement is the fundamental control statement that allows JavaScript to make decisions and
execute statements conditionally.
Syntax
if (expression)
{
Statement(s) to be executed if expression is true
}
Here a JavaScript expression is evaluated. If the resulting value is true, the given statement(s) are
executed. If the expression is false, then no statement would be executed. Most of the times, you
will use comparison operators while making decisions.
<html>
<body>
<script type = "text/javascript">
var age = 20;
if( age > 18 )
{
document.write("Qualifies for driving ");
}
</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
}
Here JavaScript expression is evaluated. If the resulting value is true, the given statement(s) in the
‘if’ block, are executed. If the expression is false, then the given statement(s) in the else block are
executed.
Example
Try the following code to learn how to implement an if-else statement in JavaScript.
<html>
<body>
<script type = "text/javascript">
var age = 15;
Output
Does not qualify for driving
The if...else if... statement is an advanced form of if…else that allows JavaScript to make a correct
decision out of several conditions.
Syntax
The syntax of an if-else-if statement is as follows −
if (expression 1)
{
Statement(s) to be executed if expression 1 is true
}
else if (expression 2)
{
Statement(s) to be executed if expression 2 is true
}
else if (expression 3)
{
Statement(s) to be executed if expression 3 is true
}
else
{
Statement(s) to be executed if no expression is true
}
It is just a series of if statements, where each if is a part of the else clause of the previous statement.
Statement(s) are executed based on the true condition, if none of the conditions is true, then
the else block is executed.
Example
Try the following code to learn how to implement an if-else-if statement in JavaScript.
<script type="text/javascript">
var m1=65,m2=60,m3=35,tot,per;
tot = m1+m2+m3;
per=tot/3;
</script>
Example:
<!DOCTYPE html>
<html>
<head>
<title>Nested If Else</title>
<script type="text/javascript">
var a=10,b=40,c=30;
if(a>b)
{
if(a>c)
{
document.write("Largest number is "+a)
}
else
{
document.write("largest number is "+c)
B) switch statement
The JavaScript switch statement is used in decision making.
The switch statement evaluates an expression and executes the corresponding body that matches
the expression's result.
Syntax:
switch (variable/expression)
{
case value1:
// body of case 1
break;
case value2:
// body of case 2
break;
case valueN:
// body of case N
break;
default:
// body of default
}
Notes:
Flowchart:
</body>
</html>
Output
Entering switch block
Second Class
Exiting switch block
Example 2
<!DOCTYPE html>
<html>
<head>
<title>Switch</title>
<script type = "text/javascript">
default:
document.write("Wrong Arithmetic Operator")
break;
}
</script>
</head>
<body>
</body>
</html>
Loop in JavaScript
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.
while (expression)
{
Statement(s) to be executed if expression is true
Flow Chart
Example:
<html>
<body>
document.write("Loop stopped!");
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...
Syntax
do
{
Statement(s) to be executed;
} while (expression);
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...
Syntax
for (initialization; test condition; iteration statement)
{
Statement(s) to be executed if test condition is true
}
Example
<html>
<body>
<script type = "text/javascript">
var count;
document.write("Starting Loop" + "<br />");
Output
Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4
break statement
The break statement is used to terminate from the loop immediately. When a break statement is
encountered inside a loop, the loop iteration stops there, and control returns from the loop
immediately to the first statement after the loop.
Example:
<script type="text/javascript">
var count;
document.write("Starting Loop" + "<br />");
for(count = 0; count < 10; count++)
{
if(count==5)
{
break
}
document.write("Current Count : " + count );
document.write("<br />");
}
</script>
Output:
Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4
continue statement
The continue statement in Java is used to skip the current iteration of a loop.
<script type="text/javascript">
var count;
document.write("Starting Loop" + "<br />");
}
</script>
Output:
Starting Loop
Current Count: 0
Current Count: 1
Current Count: 2
Current Count: 3
Current Count: 4
Current Count: 6
Current Count: 7
Current Count: 8
Current Count: 9
1. Array literals
In Javascript, an array literal is a list of expressions, each of which represents an array element,
enclosed in a pair of square brackets ' [ ] ' . When an array is created using an array literal, it is
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. Integers literals
An integer must have at least one digit (0-9).
No comma or blanks are allowed within an integer.
It does not contain any fractional part.
It can be either positive or negative if no sign precedes it is assumed to be positive.
In JavaScript, integers can be expressed in three different bases.
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
4. Boolean literals
The Boolean type has two literal values: true and false
5. Object 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:
Syntax Rules
There is a colon (:) between property name and value.
A comma separates each property name/value from the next.
There will be no comma after the last property name/value pair.
A string literal is zero or more characters, either enclosed in single quotation (') marks or double
quotation (") marks.
You can also use + operator to join strings.
The following are the examples of string literals :
string1 = "computer"
string1 = 'engineering.com'
string1 = "1000"
string1 = "google" + ".com"
prompt()
The Javascript window.prompt() method is used to display a dialog box with an optional
message prompting the user to input some text.
It is often used if the user wants to input a value before entering a page. It returns a string
containing the text entered by the user, or null.
Syntax:
prompt(message, default)
message argument is optional and specifies the text to display in the dialog box.
default argument is also optional and specifies the default input text.
Return value: The input value is returned if the user clicks the ‘OK’ button. If not so
then null is returned.
Example:
var name = prompt("Please enter your name", "Arrow");
document.write("Name is "+name);
parseInt
The parseInt method parses a value as a string and returns the integer.
Syntax
parseInt(string, radix)
Parameters
Parameter Description
string Required.
The value to be parsed.
parseFloat function
The parseFloat() function is used to accept a string and convert it into a floating-point number. If the
input string does not contain a numeral value or If the first character of the string is not a number
then it returns NaN i.e, not a number.
<!DOCTYPE html>
<html>
<head>
<title> </title>
</head>
<body>
<script type="text/javascript">
var number = parseInt(prompt('Enter a positive integer: '));
if (number < 0) {
document.write('Error! Factorial for negative number does not exist.');
}
// if number is 0
else if (number === 0) {
document.write("The factorial is 1 ");
}
// if number is positive
else {
var fact = 1;
for (i = 1; i <= number; i++) {
fact *= i;
}
document.write("The factorial is "+fact);
}
</script>
</body>
</html>
01
Example 1
var emp = {name:"Akshay",id:17,salary:50000};
document.write("Name is "+emp.name+"<br>");
document.write("Id is "+emp.id+"<br>");
document.write("Salary is "+emp.salary+"<br>");
Example 2
var emp = {name:"Akshay",id:17,salary:50000};
document.write("Name is "+emp["name"]+"<br>");
document.write("Id is "+emp["id"]+"<br>");
document.write("Salary is "+emp["salary"]+"<br>");
Example Explained
Program:-
<script type="text/javascript">
var person = {fname:"Arrow", lname:"Academy", age:25};
person.nationality = "Indian";
var text ="";
for (var x in person)
{
text += person[x] + " ";
}
document.write(text);
</script>
Deleting Properties
The delete keyword deletes a property from an object:
delete person.lname
or
delete person["age"];
Program:-
<script type="text/javascript">
var person = {fname:"Arrow", lname:"Academy", age:25};
delete person.lname
var text ="";
for (let x in person)
{
text += person[x] + " ";
}
document.write(text);
</script>
The delete keyword deletes both the value of the property and the property itself.
After deletion, the property cannot be used before it is added back again.
The delete operator is designed to be used on object properties. It has no effect on variables or
functions.
The delete operator should not be used on predefined JavaScript object properties. It can crash your
application.
JavaScript Getter and Setter
In JavaScript, there are two kinds of object properties:
Data properties
Accessor properties
1. Data Property
Here's an example of data property that that is used to assign some data to object
var student =
{
// data property
2. Accessor Property
In JavaScript, accessor properties are methods that get or set the value of an object.
For that, we use these two keywords:
get- to define a getter method to get the property value
set - to define a setter method to set the property value
JavaScript Getter
In JavaScript, getter methods are used to access the properties of an object.
get keyword is used to define a getter method to get the property value
For example,
<script type="text/javascript">
var student = {
fname: "Arrow",
lname: "Academy",
// accessor property(getter)
get getName()
{
return this.fname + " "+ this.lname;
}
};
In the above program, a getter method getName() is created to access the property of an object.
To create a getter method, the get keyword is used.
And also when accessing the value, we access the value as a property.
student.getName;
When you try to access the value as a method, an error occurs.
document.write(student.getName()); // error
JavaScript Setter
In JavaScript, setter methods are used to change the values of an object.
For example,
<script type="text/javascript">
var student =
{
fname: "Arrow",
//accessor property(setter)
set changeName(newName)
{
this.fname = newName;
}
};
document.write(student.fname); // Arrow
document.write(student.fname); // Akshay
</script>
In the above example, the setter method is used to change the value of an object.
To create a setter method, the set keyword is used.
As shown in the above program, the value of fname is Arrow.
Then the value is changed to Akshay.
student.changeName = “Akshay”;
Note: Setter must have exactly one formal parameter.