Download as pdf or txt
Download as pdf or txt
You are on page 1of 144

WEB-TECHNOLOGY-II

3.1 Introduction:-
1. Web technologies refers to the way computers/devices communicate with each other using
markup languages.
2. It involves communication across the web, and creates, delivers or manages web content
using hypertext markup language (HTML).
3. A web page is a web document which is written in HTML (hypertext markup language) .
4. It is said to have brought the world into a small village where people and devices can
communicate to each other seamlessly.
5. WWW has allowed for the access of information that would have been impossible to find or
may have been difficult to find without the www.

1
WEB-TECHNOLOGY-II(continues…)
Introduction:-
1. Computers connected to the Internet can communicate with one another with a number of
protocols such as HTTP, SMTP (Simple Mail Transfer Protocol), FTP (File Transfer Protocol),
IRC (Internet relay chat), IM (instant messaging), Telnet, and P2P (peer-to-peer).
2. The World Wide Web is a system of interlinked hypertext documents and programs that can
be accessed via the Internet primarily by using HTTP.

2
WEB-TECHNOLOGY TERM
TERMS: 7. Protocol
1. Web page 8. Internet Protocol (IP) Address
2. HTML 9. HTTP
3. Web Server 10. XML :- A MARK UP LANGUAGE TO STORE
AND TRANSPORT DATA. IT IS SELF
4. Web Browser DESCRIPTIVE.
5. URL 11. Gateway :A gateway is a network node
that forms a passage between two
networks operating with different
transmission protocols
12. API:-

3
WEB-TECHNOLOGY TERM
TERMS:
1. API:-
It is a set of subroutine definitions, protocols, and tools for building software and applications.
API is some kind of interface which has a set of functions that allow programmers to access
specific features or data of an application, operating system or other services.
Web API as the name suggests, is an API over the web which can be accessed using HTTP
protocol. It is a concept and not a technology.

4
WEB-TECHNOLOGY TERM(continues…)
TERMS:
1. API:-
In the same way, if you want to say, program some 3D graphics, it is a lot easier to do it using an
API written in a higher-level language such as JavaScript or Python, rather than try to directly
write low level code (say C or C++) that directly controls the computer's GPU or other graphics
functions.
Example:-
1. the Twitter API allows you to do things like displaying your latest tweets on your website

5
WEB-TECHNOLOGY TERM(continues…)
TERMS:
API:-
Example:-
2. Map APIs like Mapquest and the Google Maps API allows you to do all sorts of things with
maps on your web pages.
3. The Facebook suite of APIs enables you to use various parts of the Facebook ecosystem to
benefit your app, for example by providing app login using Facebook login, accepting in-app
payments, rolling out targeted ad campaigns, etc.
4.The Telegram APIs allows you to embed content from Telegram channels on your website, in
addition to providing support for bots.
5. The YouTube API, which allows you to embed YouTube videos on your site, search YouTube,
build playlists, and more.

6
WEB-TECHNOLOGY TERM(continues…)
API:-
Example:-
APIs for drawing and manipulating graphics are supported in browsers-the most popular ones are
‘canvas’ and webGL which allow us to programmatically update the pixel data contained in an HTML
<canvas> element to draw 2D/3D scenes.
Device APIs are basically APIs for manipulating and retrieving data from modern device hardware in a
way that is useful for web apps.

7
WEB-TECHNOLOGY platforms
Platforms:-
Web Technologies include the following
platform to develop applications.
5. Java
1.
HTML (HyperText Markup Language) 6. VBScript

2. XML (Extensible Markup Language) 7. PHP

3. CSS (Cascading Style Sheets) 8. C#

4. JavaScript 9. ASP
10. ASP.NET

8
3.2 Server side and client side scripting
Script’:-‘script’ means a piece of code that runs on the server or client.
It is of two types:
1. Client side scripting
2. Server side scripting
1. Client-side scripting:-

❑ Client-side scripting simply means running scripts, such as JavaScript, on the client device, usually within a
browser.

❑ All kinds of scripts can run on the client side if they are written in JavaScript, because JavaScript is
universally supported. Other scripting languages can only be used if the user's browser supports them.

For example HTML,CSS,js,VBscript

9
]

3.2 Server side and client side scripting


server-side scripting:-
Server-side scripts run on the server instead of the client, often in order to deliver dynamic content to web
pages in response to user actions. Server-side scripts don't have to be written in JavaScript, since the server
may support a variety of language. For example php,asp,jsp etc

10
3.3 Internet technology
Meaning:-
->Internet Technologies is a technical field that covers the necessary skills to develop applications on
the Internet or Internet based systems, harnessing e-commerce, cloud, mobile, and Web based
technologies.
->The Internet is a vast network of networks that spans the entire globe.
->Data is transferred from computer to computer, and from network to network, using packet-switching
technology and a suite of Internet protocols called TCP/IP, after its two most important protocols.

11
Internet technology(continues…)
Meaning:-
1. When the Soviet Union launched the first earth-orbiting satellite (Sputnik) in 1957, the United States
awoke to the fact that they were being overtaken in the space race. One of the results of this
realisation was the establishment of the Advanced Research Projects Agency (ARPA) in 1958.
2. In 1969, ARPA set up a research project called ARPANET (Advanced Research Projects Agency
Network) to create a secure, de-centralised network capable of functioning when parts of the
network infrastructure were destroyed or disabled (for example, in the event of a nuclear war).

12
Internet technology(continues…)
Meaning:-
❑ The idea behind packet-switching was to break messages down into small blocks of data called
packets that could be sent across a network independently of one another, and if necessary via
different routes.
❑ The message would be reassembled by the receiver once all of the packets had arrived safely. If a
packet was lost or damaged, it could be re-transmitted, avoiding the need to re-transmit the
entire message from the beginning.
Note:-
[In the autumn of 1969 the first ARPANET computer was connected to the ARPANET's IMP node at the
University of California at Los Angeles (UCLA). Doug Engelbart's hypertext-project computer at Stanford
Research Institute (SRI) was the next. By the end of the year, the network also included the computers at
the University of California, Santa Barbara (UCSB) and the University of Utah, i.e. four in all. All the
computers used different operating systems and they were able to talk to each other across the network
with equal status. Some years later, RFC1000 tells the story of these days of the birth of the Internet, in
which enthusiastic students played an important part.]
13
Internet technology(continues…)
Meaning:-
❑ The protocols used to transfer data across the network had to be robust and flexible enough to be
able to deal with lost or damaged packets and adapt to the sudden loss of network links by finding
a new route between the two communicating end points.
❑ The protocols also had to work over a number of different underlying network technologies, and
on different operating systems and hardware platforms.

14
Internet technology(continues…)

Meaning:-
1.The first standard networking protocol developed for ARPANET was the Network Control Protocol
(NCP), which was deployed in December 1970 and successfully used by a number of ARPANET sites to
communicate with each other in October of the following year. By the end of 1971 there were fifteen
sites using NCP.
2.They consisted mainly of universities and scientific research centres, and included Carnegie Mellon
University, Harvard University, MIT, the RAND Corporation, Stanford University, and UCLA.

15
16
3.4 Javascript
Introduction:-
1. JavaScript is the most popular and widely used client-side scripting language.
2. Client-side scripting refers to scripts that run within your web browser. JavaScript is designed to add interactivity and
dynamic effects to the web pages by manipulating the content returned from a web server.
3. JavaScript was originally developed as LiveScript by Netscape in the mid 1990s.
4. It was later renamed to JavaScript in 1995, and became an ECMA standard in 1997. Now JavaScript is the standard client-
side scripting language for web-based applications, and it is supported by virtually all web browsers available today, such
as Google Chrome, Mozilla Firefox, Apple Safari, etc.
5. JavaScript is an object-oriented language, and it also has some similarities in syntax to Java programming language. But,
JavaScript is not related to Java in any way.
[What is a Scripting Language?]
[A script is a set of programming instructions that is interpreted at runtime.
A scripting language is a language that interprets scripts at runtime. Scripts are usually embedded into other
software environments.]

17
Javascript (continues…)
What can we do with ‘javascript’:-
Here are a lot more things we can do with JavaScript.
1. We can modify the content of a web page by adding or removing elements.
2. We can change the style and position of the elements on a web page.
3. We can monitor events like mouse click, hover, etc. and react to it.
4. We can perform and control transitions and animations.
5. We can create alert pop-ups to display info or warning messages to the user.
6. We can perform operations based on user inputs and display the results.
7. We can validate user inputs before submitting it to the server.

18
JS(continues…)
Working of JS

AST:-It stands for ‘Abstract Syntax Trees’ (AST). An AST is a JavaScript object
containing a tree representation of your source.
Parser:-Parsing means analyzing and converting a program into an internal
format such that a runtime environment can actually run.
19
Uses of JavaScript:-
Javascript (continues…)
1. Client-side validation.
2. Displaying date and time.
3. To validate the user input before submission of the form.
4. Open and close new windows.
5. To display dialog boxes and pop-up windows.
6. To change the appearance of HTML documents.
7. To create the forms that respond to user input without accessing the server.
Do you know?
[Server Side JavaScript (SSJS) is an extended version of JavaScript that enables back-end access to databases, file systems,
and servers. Server side javascript, is javascript code running over a server local resources , it's just like C# or Java, but the
syntax is based on JavaScript. A good example of this is Node.JS , with Node.JS you write javascript to program on the
server side,]

20
3.5 Adding javascript to HTML
There are typically three ways to add JavaScript to a web page:
1. Internal/Embedding the JavaScript code between a pair of <script> and </script> inside head
tag or <body> tag.
2. External Creating an external JavaScript file with the .js extension and then load it within the
page through the src attribute of the <script> tag.
3. Inline/Placing the JavaScript code directly inside an HTML tag using the special tag attributes
such as onclick, onmouseover, onkeypress, onload, etc.

21
Here's an example:

<!doctype>

<html>

Adding javascript to <head>

<script type="text/javascript">

HTML(continues…) function msg()

{
->we can also use these commands programs in
console section.
1.Internal/Embedding document.write("hello javascript");

javascript code between }


-->Essentially, the Console provides you with the
script tags:- </script>
ability to write, manage, and monitor JavaScript
on demand. It also helps to inspect particular id
</head>
->You can embed the JavaScript <body>
or element ,fix bugs etc.
code directly within your web <button onclick="msg()">click me</button>

pages by placing it between the </body>

<script> and </script> tags, </html>

between head tags.. [note: Either we put inside head section and get output. We may call this from body
section.
->The <script> tag indicates the Or
directly use inside the body part to know the output.]
browser that the contained
statements are to be interpreted ->From hereafter ‘We will use inside the body tag’.
as executable script and not ->It is not necessary to put all html tags for js. But it’d better if we use them.
HTML.
->Just put the js ccode inside script tag and use it.
->In this, we can also put code
inside <body> tag. 22
Here's an example:

Example:

<!DOCTYPE html>

Adding javascript to <html lang="en">

<head>
HTML(continues…) <meta charset="UTF-8">

<title>Inlining JavaScript</title>
2.Placing js codes inline:- </head>

->we can also place JavaScript <body>

<button onclick="alert('Hello World!')">Click Me</button>


code inline by inserting it directly
</body>
inside the HTML tag using the </html>
special tag attributes such as
onclick, onmouseover, [
onkeypress, onload, etc. Either we put inside head section and get output. We may call this from body section.
Or
directly use inside the body part to know the output.]

->simply call the js code from boy part, from script tag.
->From hereafter ‘We will use inside the body tag’.

23
Here's an example:

Now put the following code in side html files.

<!DOCTYPE html>
Adding javascript to <html lang="en">

HTML(continues…) <head>
<script src=“hello.js”>//we may put anywhere i.e. Inside body tag
3.
<title>Inlining JavaScript</title>
In this we create .js file and put the js code inside it.
Then we give </head>
Let's create a JavaScript file named "hello.js" and place <body>
the following code in it:
----------------------------------------------- <button onclick=hello()>Click Me</button>

Hello.js:- </body>

function hello() </html>

{ [Either we put inside head section and get output. We may


alert("Hello World!"); call this from body section.
} Or
directly use inside the body part to know the output.]
[note:
we do not need <script> to include
->From hereafter
in external file.
We will use inside the body tag.

24
Fundamentals of JS
Javascript fundamental:-
❑JavaScript is a programming language that allows you to implement complex features on a website, such as
dynamic elements or interactivity.
❑JavaScript is executed once the information from the HTML and CSS in the source code has been parsed and
constructed.
❑The JavaScript will then trigger any events or variables specified within it, the Document Object Model
(DOM) will be updated, and, finally, the JavaScript will be rendered in the browser.
DOM:DOM stands for Document Object Model. It is a programming interface that allows
us to create, change, or remove elements from the document. We can also add events to these elements to
make our page more dynamic.
❑The HTML and CSS will often form the foundations of a page’s structure, and any JavaScript will make the
final tweaks and alterations.

25
Fundamentals of JS
Javascript fundamental:-

General format of js code is:


<script>

code goes here;


</script>
Note:

Comments in JS:-

1.We can use either single line or multiline comment to describe our code.

Single line comments start with // or /* comments */

E.g. // it works for class

E.g. /* it will execute the loop

100 times

*/

26
Fundamentals of JS
Javascript fundamental:-

2.The statement is terminated with semi-colon. Putting a semicolon is


‘optional’.
3Our editor puts semi-colon itself. We may avoid it if we want.
4.Declare variable with keyword var. we also may use let but avoid it(var).
5.We may call particular function on demand.

27
Fundamentals of JS
Javascript fundamental:-

Some other fundamental parts of js are:


1.Identifers/variables
2.Reserved words
3.Data types
4.Operators
Etc. We will discuss about these all gradually as we move to next slide.

28
Fundamentals of JS
Javascript reserved words:-
Reserved words are pre-defined words existing the library. As we need them, we can use them
directly. We can not use tem as variable. Altogether we have 64 keywords. In new version, some have
been avoided.
Examples: Some keyword are given here.
abstract arguments await* boolean
break byte case catch
char class* const continue
debugger default delete do
double else enum* eval
export* extends* false final
finally float for function

29
Fundamentals of JS
Basic display and input methods/functions:-
Display methods/functions: There are many methods which can be used to display our data but
some popular are:
document.write()
document.writeln()
window.alert()
console.log()[it is used on console part only] etc

Input method:- Following are some popular methods.


prompt()
window.prompt()
HTML forms

30
Fundamentals of JS
output examples:

Using document.writeln():- Using window.alert:-


<html>
<body>
<body> <html>
<script> <body>
document.writeln("using wiriteln","<br>"); <body>
document.writeln("this is second line");//It <script>
does not create new line window.alert("you got an alert
message");//pop ups a message
//we need to use br or p tag. </script>
</script> </body>
</body> </html>
</html>

31
Fundamentals of JS
input examples:
Using prompt():- Using window.prompt:-

<html>
<body> <html>
<body> <body>
<script> <body>
var name; <script>
name=prompt("enter your name"); var name;
document.writeln("your name is",name); name=window.prompt("enter your name");
</script> document.writeln("your name is",name);
</body> </script>
</html> </body>
</html>

32
Fundamentals of JS
Using form:-
input examples: <html>
<body>
<body>
<form name="f1">
<label>first name is</label><input type="text" name="fname"><br>
<label>sur name is</label><input type="text" name="sname"><br>
<input type="submit" name="click me" onclick="display();">
</form>
<script>
function display()
{
name=document.f1.fname.value;
address=document.f1.sname.value;
document.write("your first name is",name,"<br>");
document.write("your sur name is",address);
}
</script>
</body>
</html>

33
3.6 JS data types
Data types:-
JavaScript provides different data types to hold different types of values. There are two types of data types in
JavaScript.
❑Primitive/primary data type:-
❑Non-primitive (reference/composite) data type:-
JavaScript is a dynamic type language, means you don't need to specify type of the variable because it is
dynamically used by JavaScript engine. You need to use var here to specify the data type. It can hold any type
of values such as numbers, strings etc.

Let's know about them.

34
JS data types(Primitive/primary)
Primitives Data types:-
All types except objects define immutable values (that is, values which can't be changed)
For example (and unlike in C), Strings are immutable. We refer to values of these types as "primitive
values".
Primitive data types can hold only one value at a time,
There are five types of primitive data types in JavaScript.
They are as follows:

35
JS data types(Primitive/primary types)
Primitives Data types:-

Data Type Description

String represents sequence of characters e.g. "hello"

Number represents numeric values e.g. 100

Boolean represents boolean value either false or true

Undefined represents undefined value(It means does not exists)

Null represents null i.e. no value at all(It means value is zero;It is an


intentional absence))

36
Data type examples
All primitives:-
<html>
<body>
<script>
var number=345;
var number1=45.67;
var name="ram sharma";
var s=true;
var n=null;
var num;
document.write("integer number=",number,"<br>");//prints value as number
document.write("decimal number=",number1,"<br>");
//prints value as fractional number
document.write("string=",name,"<br>");//prints name
document.write("boolean=",s,"<br>");//prints boolean
document.write("null=",n,"<br>");//prints null
document.write("undefined number=",num,"<br>");//prints undefineds
</script>
</body>
</html>

37
JS data types(reference/composite/objects)
Non-Primitives/object Data types:-
Meaning:-
1. In computer science, an object is a value in memory which is possibly referenced by an identifier.
2. In JavaScript, objects can be seen as a collection of properties.

3. With the object literal syntax, a limited set of properties are initialized; then properties can be added and
removed. Property values can be values of any type, including other objects, which enables building complex
data structures. Properties are identified using key values. A key value is either a String value or a Symbol value.
[Note:-An object literal is a list of zero or more pairs of property names and associated values of an object, enclosed
in curly braces ({}) and separated by colon.]
E.g.
var book = { "name": "Harry ", "author": "J. K. Rowling", "year": 2000 };

38
JS data types(reference/composite/objects)
Non-Primitives/object Data types:-
Data Type Description example

represents instance through which we can var person = {


Object access members
"first name": "Peter",

"current age": 28,

gender: "Male"

};

Array represents group of similar values var color = ["Red", "Yellow", "Green", "Orange"];

represents regular expression. It is used for let text = "Visit js";


RegExp search pattern. let n = text.search("js");
it prints 6.

39
Data type examples
array:-
<html>
<body>
<script>
temp=[74,12,13,18,100];creates an object named temp of type array
document.write(temp);//prints entire values
</script>
</body>
</html>

40
Data type examples
Object:-
<html>
<body>
<script>
emp=
{ //creates an object
fname:"ram", //fname is property; ram is a value
mname:"Shyam Kumar",
address:"ktm"
};
document.write("1st emp =",emp.fname," middle name=",emp.mname,"address= ",emp.address); //prints the output
//we use dot operator to access value
</script>
</body>
</html>

41
Data type examples
regexp:-
<html>
<body>
<script>
re = new RegExp(/'ab+c'/);//means re= /ab+C/
n=/ab+/.test(re);
document.write(n);//prints true
</script>
</body>
</html>

42
3.7 JS variables and operators
Js variables:-
Variables are fundamental to all programming languages. Variables are used to store data, like string of text, numbers, etc.
The data or value stored in the variables can be set, updated, and retrieved whenever needed. In general, variables are
symbolic names for values.

You can create a variable with the var keyword, whereas the assignment operator (=) is used to assign value to a variable,

Example: var varName = value; or var variable; variable =value;

[Note: 1.Default value is undefined unless it is assigned some value. Var keyword is optional

2. Duplicate variable declarations using var will not trigger an error, even in strict mode, and the variable will not lose its value, unless
another assignment is performed.

3. The scope of a variable declared with var is its current execution context and closures thereof, which is either the enclosing function and
functions declared within it, or, for variables declared outside any function, global.

4. var declarations, wherever they occur, are processed before any code is executed. This is called hoisting. So declare a variable at the top of
code.

43
JS variables and operators
Js variables:-
5.The design of var is confusing and error-prone. So ’let’ was created in modern versions of JavaScript, a new keyword for creating
variables that works somewhat differently to var, fixing its issues in the process.
E.g. var a;

6. You start by declaring a variable with the var (less recommended) or the let keyword, followed by the name you give to the
variable:
let b;
b=90;
7. If we want to assign some constant value, we have to use keyword ‘const’. It is also used to declare variable.
Difference is that we can not re-assign a new value to a variable.
◦ i.e const a=90; a=89; --------------→ It does not allow this.

[note: variables names are case sensitive. i.e. let b and let B are different.]

44
JS variables and operators
Js variables:-

a = 2;

var a;

// ...is implicitly understood as:

var a;

a = 2;

[note: declare the variable at the top, before you assign any value.]

45
JS variables and operators
Js variables:-
Rules:-
The general rules for constructing names for variables (unique identifiers) are:

Rules :-

❑Names can contain letters, digits, underscores, and dollar signs.

❑Names must begin with a letter

❑Names can also begin with $ and _ (but we will not use it in this tutorial)

❑Names are case sensitive (y and Y are different variables)

❑Reserved words (like JavaScript keywords) cannot be used as names

❑While declaring variable we may use var or let or const or nothing.

Note:

46
<script>
var name='Ram Shrestha';//we may use
double quote
document.write('name is',name+'<br>');
JS variables and var name=200;//number assignment
operators
document.write('name with number
Js variables’ examples:- is',name+'<br>');
var name=true;//Boolean assignment
document.write('name with boolean
Example for string, numbers, is',name+'<br>');
boolean:-

</script>
<!DOCTYPE html>
<head>
<title>Creating Variables in JavaScript</title>
</head>
<body>
JS variables and <script>

operators // Creating variables


var name = “samir";//we can use single quote.
Js variables’ examples:-
// we have to declare variable with var keyword. We can also use single quote
var age = 21;
var isMarried = false;
// Printing variable values
Example 1:-
document.write(name + "<br>");//Here ‘+’ is used to concatenate with variable.
//document.write() is a method/function to display content on browser.
document.write(age + "<br>");
document.write(isMarried);
</script>
</body>
</html>
javascript multiple variables at once:-
<!DOCTYPE html>
<head>
<title>Declaring Multiple Variables in JavaScript</title>

JS variables and </head>

operators <body>
<script>
Js variables’ examples:- // Declaring multiple Variables
var name = "Parak", age = 21, isMarried = false;
// Printing variable values
document.write(name + "<br>");

Example 2:- document.write(age + "<br>");


document.write(isMarried);
</script>
</body>
</html>

49
Re-Declaring JavaScript Variables:-

If you re-declare a JavaScript variable, it will not lose its value.


The variable carName will still have the value "Volvo" after the
JS variables and execution of these statements.
operators Example 3:
<!DOCTYPE html>
Js variables’ examples:-
<html>
<body>
<script>
Example 3:- var carname = "Volvo";
var carname;
document.write("car name is ",carname);
</script>
</body>
</html>
50
The let and const Keywords:- We use two new keywords let and const for declaring
variables.
<!DOCTYPE html>
<html>
<head>
<title>Declaring Variables with let and const Keywords in JavaScript</title>
</head>
JS variables and <body>

operators <script>
let fname='Ram Shrestha';
Js variables’ examples:- document.write('name is',fname+'<br>');
The let and const Keywords:- let sname=200;

We use two new keywords let for document.write('name with number is',sname+'<br>');
variable declaration and const for let namme=true;
constant value assignment for
variables. document.write('name with boolean is',namme+'<br>');
const naam="Ram kumar Maharjan";

Example 4:- //naam="Ritu sharma";//it does not work; It says, it has been already assigned a value.
document.write('name with constant value=',naam+'<br>');
</script>
</body>
</html>
51
JS operators
Definition:-
An operator is a mathematical symbol that produces a result based on two values (or variables). In the following table, you can see some of the simplest
operators, along with some examples to try in the JavaScript console.
For example, the addition (+) symbol is an operator that tells JavaScript engine to add two variables or values, while the equal-to (==), greater-than (>) or less-
than (<) symbols are the operators that tells JavaScript engine to compare two variables or values, and so on.
Types:- Following are the types.
1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Bitwise Operators
4. Logical Operators
5. Assignment Operators
6. Special Operators
7. String operator (+)
8. typeof operator
Let’s understand about them.

52
JS operators(Arithmetic…)
Definition:-
Arithmetic operator:-
The arithmetic operators are used to perform common arithmetical operations, such as addition, subtraction,
multiplication etc
Operator Description Example

+ Addition 10+2= 12

- Subtraction 20-9 = 11

* Multiplication 10*2= 20

/ Division 20/10 = 2

% Modulus (Remainder) 20%10 = 0

53
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Arithmetic Operators</title>
</head>
<body>
<script>

JS Arithmetic var x = 5;
var y = 4;

operators document.write(x + y); // Prints: 9


document.write("<br>");
document.write(x - y); // Prints: 1
Example:-
document.write("<br>");
document.write(x * y); // Prints: 20
document.write("<br>");
document.write(x / y); // Prints: 1.25
document.write("<br>");
document.write(x % y); // Prints: 1
</script>

Example :- </body>
</html>

54
JS operators(comparison/relational)
Comparison/relational operator:-
Definition:-
The JavaScript comparison operator compares the two operands. The comparison operators are as follows:

Operator Description Example

== Is equal to 10==20 = false

=== Identical (equal and of same type) 10==20 = false

!= Not equal to 10!=20 = true

!== Not Identical 20!==20 = false

> Greater than 20>10 = true

>= Greater than or equal to 20>=10 = true

< Less than 20<10 = false

<= Less than or equal to 20<=10 = false

55
<!DOCTYPE html>
<!DOCTYPE html>
<head>
<title>JavaScript Comparison Operators</title>
</head>
<body>
<script>
JS var x = 2;
var y = 3;
comparison/relational var z = "13";
document.write(x == z); // Prints: false
operators document.write("<br>");
document.write(x === z); // Prints: false
document.write("<br>");
document.write(x != y); // Prints: true
document.write("<br>");
document.write(x !== z); // Prints: true
document.write("<br>");
document.write(x < y); // Prints: true
document.write("<br>");
document.write(x > y); // Prints: false
document.write("<br>");
Example :- document.write(x <= y); // Prints: true
document.write("<br>");
document.write(x >= y); // Prints: false
</script>
</body>
</html>
56
JS operators(logical)
Logical operator:-
Definition:-
The logical operators are typically used to combine conditional statements.

Operator Name Example Result

&& And x && y True if both x and y are true

|| Or x || y True if either x or y is true

! Not !x True if x is not true

57
<!DOCTYPE html>
<head>
<title>JavaScript logical Operators</title>
</head>
<body>
<script>
var x = 2;
var y = 3;
var z = "13";
JS logical operators if(x==y)
{
document.write("both are same"+"<br");
}
else
{
document.write("both are different"+"<br");
}
</script>
</body>
Example :- </html>

58
JS operators
(increment & decrement)
Increment/operator:-
Definition:-The increment/decrement operators are used to increment/decrement a variable's value by 1.

Operator Name Effect

++x Pre-increment Increments x by one, then returns x

x++ Post-increment Returns x, then increments x by one

--x Pre-decrement Decrements x by one, then returns x

x-- Post-decrement Returns x, then decrements x by one

59
<!DOCTYPE html>
<head>
<title>
JavaScript Incrementing and Decrementing Operators
</title>
</head>
JS <body>
<script>
increment/decrement var x; // Declaring Variable
operators x = 10;
document.write(++x); // Prints: 11
document.write("<p>" + x + "</p>"); // Prints: 11
x = 10;
document.write(x++); // Prints: 10
document.write("<p>" + x + "</p>"); // Prints: 11
x = 10;
document.write(--x); // Prints: 9
document.write("<p>" + x + "</p>"); // Prints: 9
x = 10;
Example :- document.write(x--); // Prints: 10
document.write("<p>" + x + "</p>"); // Prints: 9
</script>
</body>
</html>

60
JS operators
(Assignment operator)
Assignment operator:-
Definition:-The assignment operators are used to assign values to variables.

Operator Description Example Is The Same As

= Assign x=y x=y

+= Add and assign x += y x=x+y


-= Subtract and assign x -= y x=x-y
*= Multiply and assign x *= y x=x*y
/= Divide and assign quotient x /= y x=x/y
%= Divide and assign modulus x %= y x=x%y

61
<!DOCTYPE html>
<head>
<title>JavaScript Assignment Operators</title>
</head>
<body>
<script>
var x; // Declaring Variable
x = 12;
JS document.write(x + "<br>"); // Prints: 12
assignment operator x = 2;
x += 30;
document.write(x + "<br>"); // Prints: 32
x = 5;
x -= 20;
document.write(x + "<br>"); // Prints: -15
x = 10;
x *= 25;
document.write(x + "<br>"); // Prints: 250
x = 5;
Example :- x /= 10;
document.write(x + "<br>"); // Prints: 0.5
x = 10;
x %= 15;
document.write(x); // Prints: 10
</script>
</body> 62
JS operators
(special operator)
special operator:-
Definition:-The following operators are known as JavaScript special operators.

Operator Description

(?:) Conditional Operator returns value based on the condition. It is like if-else.
, Comma Operator allows multiple expressions to be evaluated as single
statement.
delete Delete Operator deletes a property from the object.
in In Operator checks if object has the given property
etc.

63
<!DOCTYPE html>
<html>
<body>
<h1>Demo: JavaScript Ternary Operators/special opeartor</h1>
<script>
var a = 10, b = 15;
var c = a > b? a : b;
var d = a > b? b : a;
JS document.write("c=",c+"<br>");//prints 15
special operator </script>
document.write("d=",d); //prints 10

</body>
</html>
Ternary operator:-

Example :-

64
JS operators
(string operator)
String operator:-

Definition:-’+’ is called concatenation operator. It adds/merges two or more strings and numbers.
Example:-

<!DOCTYPE html>
<html>
<body>
<p>The + operator concatenates (adds) strings and numbers.</p>
<script>
let text1 = "Nepal";
let text2 = "'s capital city is Kathmandu.";
let text3 = text1 + " " + text2;
document.write(text3);
</script>
</body>
</html>

65
JS operators
(typeof operator)
typeof operator:-

Definition:-typeof operator is used to find the data type of a JavaScript variable. It can be used as function.

Example:-

<!DOCTYPE html>
<html>
<body>

<script>
let a="ramn";
var b=300;
c=4.56;
document.write(typeof a,"<br>");
document.write(typeof b,"<br>");
document.write(typeof c,"<br>");
</script>
</body>
</html>

66
3.8 JS control structures
(if, if…else, switch, loop)
Meaning:-
Branching statements:-
A conditional statement is a set of commands that executes if a specified condition is true. JavaScript
supports two conditional statements: if, if …else if… else if and switch.

67
JS branching structures
(if, if…else,if..else if and switch)
Meaning:-
If ,if…else and if…elseif, switch branching statements:-

if control structure:- The if statement is the fundamental control statement that allows JavaScript to make decisions
and execute statements conditionally.
If we want to execute another statement then we have to put else clause with statements. Likewise for multiple conditions
to be tested, we need to put if..elseif.
Syntax:
if (expression)
{
if (expression)
Statement(s) to be executed if expression is true;
{
}
Statement(s) to be executed if expression is true; else
} {
Statement(s) to be executed if expression is false;
}

68
<!DOCTYPE html>
<head>
<title>JavaScript if ..else structure</title>
</head>
<body>
<script>
var x = 2;
var y = 2;
JS var z = "13";
if example if(x==y)
{
document.write("both are same"+"<br");
//for single statement, we may write without braces.It is the best practice to use
braces.
}
If.. example

</script>
Example :- </body>
</html>

69
<!DOCTYPE html>
<head>
<title>JavaScript if ..else structure</title>
</head>
<body>
<script>
var x = 2;
var y = 2;
JS var z = "13";
if..else example if(x==y)
{
document.write("both are same"+"<br");
//for single statement, we may write without braces.It is the best practice to use
braces.
}

else
{
Example :- document.write("both are different"+"<br");
}

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

70
JS branching structures
(if...else if )
Meaning:-
if…elseif branching statements:-

The if...else if...else a special statement that is used to combine multiple if...else statements.
Syntax: if (condition1)
{
Statement(s) to be executed if expression is true;
}
else if(condition2)
{
Statement(s) to be executed if expression is false;
}
else
{
statements to be executed;
}

71
<!DOCTYPE html>
<head>

<title>JavaScript Multiple If Else Statement</title>


</head>
<body>
<script>
var now = new Date();//creates a 'now' object for date
JS var dayOfWeek = now.getDay(); // Sunday - Saturday : 0 - 6. stores the day as number
if..elseif example in dayof week

if(dayOfWeek == 6) {
document.write("Have a nice weekend!");
} else if(dayOfWeek == 0) {
document.write("Have a nice Sunday!");
} else {
document.write("Have a nice day!");
}
Example :- </script>
</body>
</html>

72
Meaning:-
Switch… statements:-
A switch statement allows a program to evaluate an expression and attempt
to match the expression's value to a case label. If a match is found, the
program executes the associated statement. If the match is not found, it
executes the default part. It tests the values in parallel fashion.
JS Syntax:
branching structures
(switch… )
switch (expression)
Switch control structure :- {
case label_1:
statements_1;
[break;]
case label_2:
statements_2;
[break;]
default:
statements_def;
[break;] //Here,this break statement is optional.
}

73
Switch structure example:-
<!DOCTYPE html>
<head>

<title>JavaScript Multiple If Else Statement</title>


</head>
<body>
<script>
JS let fruitname="ora";
switch(fruitname)
branching structures {
(switch… ) case "orange":
Switch control structure example :- document.write("it is an orange"+"<br>");
break;
case "apple":
document.write("it is an apple"+"<br>");
break;
default:
document.write("unknown fruit");
Example:- break;
}
</script>
</body>
</html>
[Note: It supports all types of expression i.e. string, number, characer Boolean]
It supports break and continue statements.

74
JS LOOP structures
Meaning:-Loops offer a quick and easy way to do something repeatedly. This repetition continues if the
condition is true else it stops.
Types: Following are the types of loops supported in JS.
1. for loop
2. do..while loop
3. while loop
4. for…in loop
5. for …of loop
Let’s understand about these loops.

75
JS LOOP structures(‘for’ loop)
Meaning of ‘for’ loop:-
A for loop repeats until a specified condition evaluates to false. The JavaScript for loop is similar to the Java and
C for loop.
syntax:-

for ([initialExpression]; [conditionExpression]; [incrementExpression])

statement ;

76
<!DOCTYPE html>

<head>

<title>JavaScript for loop</title>

</head>
JS <body>
looping structures
(for) <script>

let i;

for(i=1;i<=5;i++)

Example:-
document.write(i+"<br>");

</script>

</body>

</html>
77
JS LOOP structures(‘do…while’ loop)
Meaning of do…while loop:-
A kind of loop where execution repeats until a given condition is false.
syntax:-

do

statements;

increment/decrement;

}while(condition);

[note: If the condition is false, at least once it runs]

78
<!DOCTYPE html>

<head>

<title>JavaScript for do..while loop</title>

</head>

JS <body>
looping structures <script>
(do …while loop)
let i=1;

do

document.write(i+"<br>");
Example:-
i++;

}while(i<=5);

</script>

</body>

</html>
79
JS LOOP structures(‘while’ loop)
Meaning of while loop:-
A kind of loop where execution repeats as long as the condition is true. As the condition becomes false, the
controls is passed to next level.
syntax:-
initialization;
while(condition)
{
statements;
increment/decrement;
}
[note: If the condition is false, it does not run even once.]

80
<!DOCTYPE html>
<head>

<title>JavaScript for while loop</title>


</head>
<body>
<script>
JS let i=1;
looping structures while(i<=5)
(while loop) {
document.write(i+"<br>");
i++;
}

</script>
</body>
</html>
Example:-

81
JS LOOP structures(‘for..in’ loop)
Meaning of for…in loop:-
The for/in statement loops through the properties of an object. An object can have property and value. The block inside the

Loop executes once for each property.


syntax:-
for(variable in object)
{
statements;
}
[note: Do not use it if the order of array is important.]
Given that for...in is built for iterating object properties.
It may be most practically used for debugging purposes, being an easy way to check the properties of an object
(by outputting to the console or otherwise)

82
<!DOCTYPE html>
<head>

<title>JavaScript for ..in loop</title>


</head>
<body>
<script>
JS
looping structures let i={fname:"raman",mname:"shrestha",age:14};
(for in loop) for(a in i)
{
document.write(a+" "+i[a]+"<br>");
//'a' helps to access property;i[a] helps to access value

</script>
Example:-
</body>
</html>

83
JS LOOP structures(‘for…of’ loop)
Meaning of for…of loop:-
To iterate over iterable objects like arrays and strings, we can use the for...of statement. It invokes a custom
iteration hook with statements to be executed for the value of each distinct property of the object.

syntax:-

for(variable of iterable)

statements;

} [note:It works for iterable objects i.e. array/string etc]

84
<!DOCTYPE html>
<head>

<title>JavaScript for ..of loop</title>


</head>
<body>
<script>
JS
looping structures let i=["raman","shrestha",14];
(for of loop) for(a of i)
{
document.write(a+"<br>");
}
</script>
</body>
</html>
Example:-

85
JS functions/user defined
Meaning functions:-
JavaScript functions are used to perform operations. We can call JavaScript function many times to
reuse the code.
Advantage of JavaScript function:-
There are mainly two advantages of JavaScript functions.

1.Code reusability: We can call a function several times so it saves coding.


2.Less coding: It makes our program compact. We don’t need to write many lines of code each time to
perform a common task.
Syntax:
function functionName([arg1, arg2, ...argN])
{

//code to be executed
}

86
JS functions/user defined
Meaning of function:-
Reminder:

1. function may contain parameter inside bracket

2. Function may return some value and that can be assigned to some variable.

3. We have to call it with its name to show its effect.

4. We can also create function using function expression.

i.e. variable= function (n){return n*n;}

result=variable(3);

[taking function below the calling will not work.]

5. We can pass whole object to a function. Actually functions are also objects. In function, parameter, by default is
undefined.

6.All the variables used inside the function are local by default. We can use function inside another function.

In this case, an inner function forms a closure i.e. it can use variables of outer function, not vice-versa.
87
<html>
<body>
<script>
function msg()

JS {

functions alert("hello! this is message");


(user defined }
</script>
<input type="button" onclick="msg()" value="call function"/>
</body>
</html>
Example 1:-
[Note: We may put simply function name to get its output.]

88
<html>
<body>
<script>
function msg()
{
alert("hello! this is message");
}
JS </script>
functions <body>
(user defined <script>
msg(); //does not work by just putting inside body tag.
//we must put script tag for this.
</script>
</body>
</html>
[Note: We may put simply function (inside script)name to get its output.]
Example 1.1:-

89
<html>
<body>
<script>
function msg(txt)

JS {

functions alert(txt);
(user defined) }
</script>
<input type="button" onclick="msg(‘welcome to js’)" value="call
Example 2:- with parameter function"/>
</body>
</html>

90
<!DOCTYPE html>
<head>
<title>JavaScript Return a Value from a Function</title>
</head>
<body>
<script>
// Defining function
JS function getSum(num1, num2)
functions {
(user defined) var total = num1 + num2;
return total;
}
// Displaying returned value
document.write(getSum(16, 20) + "<br>"); // Prints: 36
Example 3:-
document.write(getSum(-15, 17)); // Prints: 2
with parameter and returning value </script>
</body>
</html>

<!Variable scope: The variables used inside the function are


called local variables. Those variables can not be accessed from
outside. In above example, num1,num2 and total are local
variables.*/-->

91
<html>
<body>
<script>
function A(x)
{
document.write("result from function A is",x,"<br>");

JS function B(y)
functions {
(user defined) document.write("result from function B is",x+y,"<br>");
function C(z)
{
document.write(x + y + z);
}
Example 3:-
C(3);
with nested function }
B(2);
}
A(1);
</script>
</body>
</html>

92
<html>
<body>

<script>
function stringlength(x)
{
JS let length=0;
functions for(i=1;i<=x.length;i++)
(user defined) {
length++;
}
return length;
}
Example 4:-
document.write("length=",stringlength("sam kumar Maharjan"));
with function </script>
</body>

93
<html>
<script>
function stringlength(x)
{
//document.writeln(x); //we can also write this.It breaks the line
alert(x);
JS alert(x.toLowerCase());//toLowerCase() converts string into
functions lowercase
(user defined) //it is case sensitive
}
</script>
<body>
Example 5:-
<button onclick="stringlength('SAEAN')">clik me</button>
with <!in html 'onclick' event is not case sensitive whereas it is in js-->
</body>
Document.writeln()
</html>

94
JS ‘DOM’ concept with programs
DOM:-
1. The Document Object Model (DOM) is a programming interface for web documents.
2. It represents the page so that programs can change the document structure, style, and content.
3. The DOM represents the document as nodes and objects; that way, programming languages can interact with
the page.
4. A web page is a document that can be either displayed in the browser window or as the HTML source.
5. In both cases, it is the same document but the Document Object Model (DOM) representation allows it to be
manipulated.
6. As an object-oriented representation of the web page, it can be modified with a scripting language such as
JavaScript.

95
JS ‘DOM’ concept with programs
DOM:-

7. The DOM is not a programming language, but without it, the JavaScript language wouldn't have any model or notion of
web pages, HTML documents, SVG documents, and their component parts.

8. The document as a whole, the head, tables within the document, table headers, text within the table cells, and all
other elements in a document are parts of the document object model for that document. They can all be accessed
and manipulated using the DOM and a scripting language like JavaScript.

9. The DOM is not part of the JavaScript language, but is instead a Web API used to build websites.

96
JS ‘DOM’ concept with programs
DOM:-
DOM can be applied to:
1. Attributes
2. Documents
3. Elements
4. Events
5. Event objects
6. HTML collection
7. Style etc

◦ [Like ‘DOM’, we have BOM. It is used to talk with browser and its properties. Like size,pop-up,cookies,navigation
location etc.]

97
<html>
<style>
p
{
text-align: center;
JS }
background-color: lightgreen;

‘DOM’ examples </style>

<body>

DOM method on elements with properties:- <p id="first">


</p>
Methods:These are actions on elements.
<script>
Property:-It is a value to get or change. document.getElementById('first').innerHTML="DOM concept";
//getElementById() is a method/function
//innerHTML is a property.It is used to get or replace content.
//we use id(it has to be unique) to access and change the contents
easily
Example 1:- using an ID </script>
</body>
</html>

98
<!DOCTYPE html>
<html>
<body>

<p>This example uses the HTML DOM to assign an "onclick" event to a p


element.</p>
JS <p id="p1">Click me.</p>
‘DOM’ examples
<script>
document.getElementById("p1").onclick = function(){my()};//calling
function on click
DOM method on elelments with properties:-
function my()
Methods:These are actions on elements.
{
Property:-It is a value to get or change. document.getElementById("p1").innerHTML = "YOU CLICKED ME!";
}
</script>

</body>
Example 2:- using function for particular id
</html>

99
<!DOCTYPE html>
<html>
<body>

<p>This example uses the HTML DOM to assign an "onclick" event to a p element.</p>

<p>Js is an awesome language to run your code on client cmoputers. It can also be used to
JS run server.
It was developed by Brendan Eich at Netscape, and has since been updated to conform to
‘DOM’ examples ECMA-262 Edition 5 and later versions.

</p>
<script>
function totallength()
DOM method on elelments with properties:- {
Methods:These are actions on elements. var v=document.getElementsByTagName('p');//calling function on click
var len=v.length;
Property:-It is a value to get or change. alert("This contains "+len+"paragraphs");
}
</script>

<button style="width=200px;" onclick="totallength();">click to know total


Example 3:- using function and particular ‘tag’ paragraphs</button>
</body>
</html>

100
<!DOCTYPE html>
<html>
<body>

<p>This example uses the HTML DOM to assign an "onclick" event to a p element.</p>

<p>Js is an awesome language to run your code on client cmoputers. It can also be used to
JS run server.
It was developed by Brendan Eich at Netscape, and has since been updated to conform to
‘DOM’ examples ECMA-262 Edition 5 and later versions.

</p>
<script>
function totallength()
DOM method on elelments with properties:- {
Methods:These are actions on elements. var v=document.getElementsByTagName('p');//calling function on click
var len=v.length;
Property:-It is a value to get or change. alert("This contains "+len+"paragraphs");
}
</script>

<button style="width=200px;" onclick="totallength();">click to know total


Example 4:- using function and particular ‘class’ paragraphs</button>
</body>
</html>

101
<!DOCTYPE html>
<html>
<body>
<script>
function changer()
{
var v,msg;
JS v=document.form1.username.value.length;
if(v<5)
‘DOM’ examples msg="your name contains less than 5 characters";
else
msg="wow, powerful name";
document.getElementById('display').innerText=msg;
}
</script>
<form name="form1">
<input type="tex" name="username" onkeyup="changer()"><span
Example 5:- using ID and innertext property. id="display">strength</span>
</form>
</body>
</html>

102
We have used different methods(functions) in previous examples, as shown
below.

1. document.getElementById()
2. document. getElementsByName()
JS 3. document. getElementsByTagName()
‘DOM’ examples 4. document. open()
5. document. close()
6. document. write()
7. document.writeln()

Example 5:- using HTML DOM using different


Some more methods related to string and numbers can be:
methods.
1. length→ find the length of the string.
2. Slice(start,end)-→to extract a part of string
3. Replace(old,new)→replaces the sub string by new.
etc
example

103
<!DOCTYPE HTML>
<html>
<head>
<title>JavaScript Document Object Methods</title>
<script type="text/javascript">
function dis()
{
JS var number1=90;
var number2=90;
‘DOM’ examples document.writeln("sum=",number1+number2,"<p></p>");
//we must put the lines inside <p> or br otherwise it would not work(new line)
//we may use + for <p> tag
document.writeln("difference=",number1-number2);
}
Example 1:- using HTML DOM </script>
</head>
<body>
document.writeln() <button onclick="dis();"> click to find result</button>
</form>
</body>
</html>

104
BOM examples can be alert(),confirm(),open(),close(), prompt() etc

<!DOCTYPE HTML>
JS <html>
<head>
‘DOM+BOM’ examples <title>JavaScript Document Object Methods</title>
<script type="text/javascript">
function getdata()
{
Example :- using HTML DOM n = window.open();
Window.open(), var v1 = document.getElementById("f1").elements["a1"].value;
n.document.write(" Your Name is " + v1);
getElelmntByID,
document.write }
</script>
BOM:- </head>
<body>
BOM refers to the browser object model in
<form id="f1">
JavaScript. BOM is used on the Windows
<h3>JavaScript Document Object Methods Example</h3>
screen and communicates with the browser.
First Name:<input type="text" name="a1" size="20"><br/>
BOM refers to Windows objects in JavaScript.
Modern browsers have implemented the <input type="button" onclick="getdata()" value="show name">
same methods and properties for JavaScript </form>
interactions, often referred to as BOM's </body>
methods and properties. A window object is </html>
automatically created by the browser.
105
<!DOCTYPE HTML>
<html>
<head>
<title>Js string Methods</title>
<script type="text/javascript">

JS function dis()
{

‘DOM’ examples for strings var text1="Kathmandu city";


var text2=" is beautiful";
(string methods):- document.writeln("length using length()=",text1.length,"<p></p>");//prints the length
document.writeln("slice or substring=",text1.slice(2,5),"<p></p>");//extraxts sub string
document.writeln("replace string=",text1.replace("Kathmandu","Nepal is
beautiful."),"<p></p>");
//replaces the substring 'kathmandu' with 'Nepal is beautiful' then appends with city.
Example 1:- using HTML DOM
}
</script>
1. String methods: </head>
<body>
2. Length <button onclick="dis();"> click to find result</button>
3. Slice </form>
</body>
4. Replace </html>

106
<!DOCTYPE HTML>
<html>
<head>
<title>Js BOM</title>
<script type="text/javascript">
JS function dis()
{
‘BOM’ examples alert("you clicked me " + name);//+ is used to concatenate strings. we should no use
Example 1:- comma. It won't display.
}
alert():- </script>
</head>
<body>
<button onclick="dis()"> press me</button>
</form>
</body>
</html>

107
<!DOCTYPE HTML>
<html>
<head>
<title>Js string Methods</title>
<script type="text/javascript">
function dis()
{
JS var name=prompt("enter your name");
//gets input. we can also use window.prompt().prompt() is a method of window object
‘BOM’ examples alert("hello " + name);//+ is used to concatenate strings. we should no use comma. It
won't display.
}
</script>
</head>
Inputting a data:- <body>
<button onclick="dis()"> click to display name</button>
</form>
Prompt() method /window.prompt():- </body>
</html>

108
<!DOCTYPE HTML>
<html>
<head>
<title>Js BOM confirm</title>
<script type="text/javascript">
function dis()
{
JS var ms=confirm("are you sure ?" );
‘BOM’ examples if(ms)
{
alert("you pressed ok");
}
else
Confirm():- to confirm with ok and cancel {
message. alert("you pressed cancel");
}

Confirm() method :- }
</script>
</head>
<body>
<button onclick="dis()"> press me</button>
</form>
</body>
</html>

109
3.9 Object Based Programming using ‘JS’
Object based Programming:-

1. JavaScript is an object-based language based on prototypes, rather than being class-based. Because of this
different basis, it can be less apparent how JavaScript allows you to create hierarchies of objects and to have
inheritance of properties and their values.
2. A prototype-based language, such as JavaScript, does not make this distinction(class,method and instance).
3. It has objects.
4. A prototype-based language has the notion of a prototypical object, an object used as a template from which
to get the initial properties for a new object.
5. Any object can specify its own properties, either when you create it or at run time.
6. In addition, any object can be associated as the prototype for another object, allowing the second object to
share the first object's properties.
[note:-
template:- it is the content fragment that is being stored for subsequent use in the
document.
In js, we can use everything as an ‘object’.

110
Object based Programming using ‘JS’
There are three ways to write program/create object in JS, using OBP. They are:

1.By object literal


2.By creating instance of Object directly (using new keyword)
3.By using an object constructor (using new keyword)

Let’s understand these all with examples.

111
Object based Programming using ‘JS’
1. By object literal:-
The syntax of creating object using object literal is given below:

object={

◦ property1:value1,property2:value2.....propertyN:valueN
◦ }

As you can see, property and value is separated by : (colon).


Let’s see the simple example of creating object in JavaScript.

112
Example:

<html>
<body>
<script>
emp={

Object Oriented id:102,


name:"Shyam Kumar",
Programming using salary:40000

‘JS’ }
document.write("emp id=",emp.id," emp name=",emp.name,"emp salary=
1. By object literal:- ",emp.salary);
</script>
</body>
</html>

Here, Id is a property and 102 is a value. Both are separated by colon. To access value, we
use dot operator.

113
Object Based Programming using ‘JS’
2. By creating an instance of an object:- Here we have to create an object using ‘new’.

The syntax of creating object directly is given below:

[Here, In simple words, ‘Instance’ refers to the copy of the object at a particular time whereas
object refers to the memory address of the class.]

var objectname=new Object();

114
Example 2:-
<html>
<body>

Object based <script>

Programming using var emp=new Object(); //emp is an object


‘JS’ emp.id=101;
2. By creating an instance of an emp.name="Ravi Mahara";
object:-
emp.salary=50000;
document.write(emp.id+" "+emp.name+"
"+emp.salary);
</script>
</body>
</html>

115
Object based Programming using ‘JS’
3. By using an Object constructor:-
Here, you need to create a function with arguments. Each argument value can be assigned in the
current object by using this keyword.
The this keyword refers to the current object.

The example of creating an object by object constructor is given below.

116
<html>

<body>
<script> Some objects’ list used in js:-

Object based function emp(id,name,salary){


this.id=id;
1.Text processing objects:- For example, string

Programming using this.name=name;


2.Mathematical objects:- For example, number
3.Date object:- for example, getDay() Etc.
‘JS’ this.salary=salary;
}
3. By using an Object constructor:-
e=new emp(10,"Vima ",300);
document.write(e.id+" "+e.name+" "+e.salary);
</script>
</body>
</html>
[note: we may also use class to create object that is under ES6 standard.]
It stands for ‘European Computer Manufacturer's Association’.
ECMAScript is a Standard for scripting languages such as JavaScript, JScript, etc. It is a
trademark scripting language specification.
The Object constructor creates an object wrapper for the given value.
Constructor:It is a method to create an object with many instances.

117
Event handling in ‘JS’
Event:-

1. An event is something that happens when user interact with the web page, such as when he clicked a link or button,
entered text into an input box or textarea, made selection in a select box, pressed key on the keyboard, moved the
mouse pointer, submits a form, etc.

2. In some cases, the Browser itself can trigger the events, such as the page load and unload events.

3. When an event occur, you can use a JavaScript event handler (or an event listener) to detect them and perform
specific task or set of tasks. By convention, the names for event handlers always begin with the word "on", so an
event handler for the click event is called onclick, similarly an event handler for the load event is called onload, event
handler for the blur event is called onblur, and so on.

118
Event handling in ‘JS’
Event types:-
1. Mouse events:-
2.Keyboard events:-
3.form events:-
Etc.

119
Event handling in ‘JS’
Event types:-
1. Mouse events:-
Event Performed Event Handler Description

click onclick When mouse click on an element

mouseover onmouseover When the cursor of the mouse comes over the
element
mouseout onmouseout When the cursor of the mouse leaves an element

mousedown onmousedown When the mouse button is pressed over the element

mouseup onmouseup When the mouse button is released over the element

mousemove onmousemove When the mouse movement takes place.

120
Event handling in ‘JS’
Event types:-
1. Keyboard events:-

Event Description

onkeydown The event occurs when the user is pressing a key

onkeypress The event occurs when the user presses a key

onkeyup The event occurs when the user releases a key

121
Event handling in ‘JS’
Event types:-
1. Form events:-

Event Performed Event Handler Description

focus onfocus When the user focuses on an element


submit onsubmit When the user submits the form
blur onblur When the focus is away from a form element
change onchange When the user modifies or changes the value of a
form element

122
Event handling in ‘JS’
Mouse Event examples:- <!DOCTYPE html>
<!DOCTYPE html> <head>
<title>mouse Event</title>
<head>
<script type="text/javascript">
<title>mouse Event</title>
function n_win()
</head> {
<body> window.open("http://www.yahoo.com","yahoo site");
}
<button type="button" onclick="alert('You have clicked a button!');">Click
Me</button> </script>
</head>
</body>
<body>
</html> <button type="button" ondblclick="n_win();">double
[we may use function] Click Me to open yahoo.com</button>
</body>
</html>

123
Event handling in ‘JS’
Keyboard Event examples:- <!DOCTYPE html>
<!DOCTYPE html>
<html>
<html>
<head>
<head>
<script> <script>
function mfunction() function mfunction()
{ {
var x = document.getElementsByName("firstname")[0];//[0] means first alert("you pressed a key inside the box");
element. }
x.value = x.value.toUpperCase();//converts in to uppercase
</script>
}
</head>
</script>
</head> <body>
<body> <p>As you press a key inside the box, the action/trigger takes place.</p>
<p>As you release the key off the box, the action/trigger takes place.</p> Enter your name: <input type="text" name="firstname"
Enter your name: <input type="text" name="firstname" onkeydown="mfunction();">
onkeyup="mfunction();"> </body>
</body>
</html>
</html>

124
Event handling in ‘JS’
Form Event examples:- <!DOCTYPE html>
<!DOCTYPE html> <html>
<html> <body>
<body> <p>When you submit the form, a function is triggered which alerts some
<p>as you write something, it appears there.</p> text.</p>
<input type="text" id="input" oninput="function1()"> <form name="f" onsubmit="myFunction()">
<p id="para"></p> Enter name: <input type="text" name="fname">
<script> <input type="submit" value="Submit">
function function1() { </form>
var x = document.getElementById("input").value; <script>
document.getElementById("para").innerHTML = "You wrote: " + x; function myFunction()
} {
</script> var n = document.querySelector("form[name='f'] input[name='fname']").value;
</body> v=window.open();
</html> v.document.write("thank you "+n+" your feedback has been recorded");
}
</script>
</body> 125
3.10 Image, event and form objects
Objects:-
JavaScript is designed on a simple object-based paradigm. An object is a collection of properties, and a property is
an association between a name (or key) and a value. A property's value can be a function, in which case the
property is known as a method. In addition to objects that are predefined in the browser, you can define your own
objects.
Let’s talk about some objects.

1. Image object:-
The Image() constructor creates a new HTMLImageElement instance. A constructor is a function
that creates an instance of a class which is typically called an “object”. In JavaScript, a constructor gets called when
you declare an object using the new keyword.
Example:

126
<head>
<script type="text/javascript">
function imagedisplay()
{
img=new Image;//creates an image object.we can also use Image().
img.src="pic.jpg";//that object stores an image with given location
Image, event var picturecontent=document.getElementById('showpicture');

and form objects //it takes the picture by using particular id as in 'div'
picturecontent.appendChild(img);
Image object example:- /*The appendChild() method of the Node interface adds a node to the end of
the list of children of a specified parent node.
*/
}
</script>
</head>
<body>
<button style=" width:200px;height: 200px;" onclick ="imagedisplay();">click me
</button>
<div id="showpicture"></div>
</body>
127
Image, event and form objects
Let’s talk about some objects.

2. event object:-
The Event interface represents an event which takes place in the DOM. An event can be triggered
by the user action.
e.g. clicking the mouse button or tapping keyboard, or generated by APIs to represent the progress of an
asynchronous task.

Example:

128
<head>
<script type="text/javascript">
function eventcon()
{
window.open("http://www.ekantipur.com","kantipur","left=300,top=
Image, event 300,width=600,height=600");

and form objects }


</script>
event object example:-
</head>
<body>
<button style=" width:200px;height: 200px;" onclick ="eventcon();">click
me
</button>
</body>

129
Image, event and form objects(continues…)

Let’s talk about some objects.

3. form object:-
Form object represents an HTML form. It is used to collect user input through elements like text
fields, check box and radio button, select option, text area, submit buttons and etc. We can create and access a form
element using the createElement() and getElementById() method of the document object. We can set various
properties of the form object and can get them too. We may use other functions.

Example:

130
Example:- <form name="f1" onsubmit="return validate()"><!--it
calls the function on submit.It takes the cursor where
<head>
condition is not true.Entered data remains as it is.-->
<script type="text/javascript"> <label>name:</label><input type="text"
function validate() name="username">
{ <label>password:</label><input
if(document.f1.username.value=="") type="password" name="userpassword">
{ <input type="submit" name="submit"
alert("user name can not be blank"); value="submit">
return false;//it prevents from submitting </form>
}
if(document.f1.userpassword.value=="")
{ </body>
alert("password can not be blank");

return false;//it prevents from submitting


}
}
</script>
</head>
<body>

131
3.11 Form validation and Jquery
3.11.1 Form validation:-

• Web forms have become an essential part of web applications.


• It is often used to collect user's information such as name, email address, location, age, and so on.
• But it is quite possible that some user might not enter the data what you've expected.
• So to save bandwidth and avoid unnecessary strain on your server resources you can validate the form data on
client-side (i.e. user's system) using JavaScript before passing it onto the web server for further processing.
• Client-side validation is also helpful in creating better user experience, since it is faster because validation occurs
within the user's web browser, whereas server-side validation occurs on the server, which require user's input to
be first submitted and sent to the server before validation occurs, also user has to wait for server response to
know what exactly went wrong.

Example: Let’s see some examples (1,2 and 3)

132
3.11 Form validation and Jquery
3.11.2 Jquery:-
• jQuery is a fast, small, and feature-rich JavaScript library.
• It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much
simpler with an easy-to use API that works across a multitude of browsers.
• With a combination of versatility and extensibility, jQuery has changed the way that millions of people write
JavaScript.
• One important thing to know is that jQuery is just a JavaScript library.
• All the power of jQuery is accessed via JavaScript, so having a strong grasp of JavaScript is essential for
understanding, structuring, and debugging your code. While working with jQuery regularly can, over time,
improve your proficiency with JavaScript, it can be hard to get started writing jQuery without a working
knowledge of JavaScript's built-in constructs and syntax.

133
3.11 Form validation and Jquery
3.11.2 Jquery:-
Features:-
Following are the some features carried by jquery.
● HTML manipulation
● DOM manipulation
● DOM element selection
● CSS manipulation
● Effects and Animations
● Utilities
● AJAX (Asynchronous JavaScript And XML)(tt can send and receive information in various formats, including JSON, XML, HTML, and text files.)
● HTML event methods
● JSON Parsing (JavaScript Object Notation (JSON) is a standard text-based format for representing structured data based on JavaScript object syntax. It
is commonly used for transmitting data in web applications (e.g., sending some data from the server to the client, so it can be displayed on a web page, or vice
versa).
● Extensibility through plug-ins.

134
3.11 Form validation and Jquery
3.11.2 Jquery:-

❑ jQuery is developed by Google.


❑ To create the first jQuery example, you need to use JavaScript file for jQuery.
❑ You can download the jQuery file from jquery.com or use the absolute URL of jQuery file.
❑ In this jQuery example, we are using the absolute URL of jQuery file.
❑ The jQuery example is written inside the script tag.

135
3.11.2 Jquery
3.11.2 Jquery syntax:-

With jquery, we can select HTML elements/css selectors and perform action on them.
jQuery Selectors:-
jQuery selectors allow you to select and manipulate HTML element(s).
jQuery selectors are used to "find" (or select) HTML elements based on their name, id, classes, types, attributes,
values of attributes and much more. It's based on the existing CSS Selectors, and in addition, it has some own
custom selectors.
All selectors in jQuery start with the dollar sign and parentheses: $().

136
3.11.2 Jquery
Reminder:-
3.11.2 Jquery syntax:- All jQuery methods/codes in our examples, are inside
Basic syntax is: $(selector).action() a document ready event.
i.e.
•A $ sign to define/access jQuery
•A (selector) to "query (or find)" HTML elements $(document).ready(function()
•A jQuery action() to be performed on the element(s) {

Examples: // jQuery codes go here...

$(this).hide() - hides the current element. }


);
$("p").hide() - hides all <p> elements.
->This is to prevent any jQuery code from running
$(".test").hide() - hides all elements with class="test". before the document is finished loading (is ready).
Or
$("#test").hide() - hides the element with id="test".

137
3.11.2 Jquery
The jQuery team has also created an even shorter
All jQuery methods/codes in our
method for the document ready event:
examples, are inside a document
Syntax:
ready event.
i.e.
$(function()
{
$(document).ready(function()
{ or // jQuery methods go here...
// jQuery codes go here...
}
);
}
Whichever you like , use it.
);
->This is to prevent any jQuery code
from running before the document is
finished loading (is ready).

138
3.11.2 Jquery
Jquery event:-

An action for which webpage responds to, is called an event.

To assign a click event to all paragraphs on a page, you can do this:

$("p").click();

The next step is to define what should happen when the event fires. You must pass a function to the event:

$("p").click(function()
{
// action/code goes here!!
}
);
-----------------------
Let’s see an example-------→example 1.

139
3.11.2 Jquery
Example 1:-click event
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<!--loading of js library-->
<script>
$(function()//allows us to execute a function when the document is fully loaded
{
$("p").click(function(){
//click() method attaches an event handler function to an HTML element
//The function is executed when the user clicks on the HTML element.
$(this).hide(); example 1,2and 3.[We have many such
});
});
functions. Like on(),blur(),hover(),focus() etc.
</script>
</head>
<body>

<p>I am first paragraph,click me to disappear</p>


<p>I am second para,Click me to go away!</p>
<p>Click me too,man!</p>

</body>
</html>

140
3.11.2 Jquery
Example 2:- click event:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function()
{
$("#hide").click(function()
////click() method attaches an effect function to an HTML element
//The function is executed when the user clicks on the HTML element.
{
$("p").hide();//hides the element example 1,2and 3.[We have many such
});
$("#show").click(function(){
functions. Like on(),blur(),hover(),focus() etc.
$("p").show();//shows the element
});
});
</script>
</head>
<body>
<p>as click hide me button, i will hide myself and if you click show me, i will appear</p>
<button id="hide">Hide me</button>//id is a 'selector'
<button id="show">Show me</button>
</body>
</html>

141
3.11.2 Jquery
Jquery selector:-

jQuery Selectors are used to select and manipulate HTML elements. They are very important part of jQuery
library.
With jQuery selectors, you can find or select HTML elements based on their id, classes, attributes, types
and much more from a DOM.

All jQuery selectors start with a dollor sign and parenthesis e.g. $(). It is known as the factory function.
-------------------------------------------------------------------------------
Let’s see some examples-------→example 1,2and 3.

142
3.11.2 Jquery
Example 1:-for class
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery examples</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
$("p").text("Hello World!");
$(".p1").click(function()
{
$(this).slideUp("slow"); example 1,2and 3.[We have many such
});
});
functions. Like on(),blur(),hover(),focus() etc.
</script>
</head>
<body>
<p>Not loaded yet.</p>
<div class="p1">click to hide</div>
</body>
</html>

143
3.11.2 Jquery
Jquery for css:-

<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script>
$(function()//we can also use (function())
{
$("p").hover(function()
{
$(this).css("background-color", "violet");
},
function()
{
$(this).css("background-color", "green");
});
});
</script>
</head>
<body>
<p>Hover your mouse pointer on me!</p>
</body>
</html>
144

You might also like