Internet Programming
Internet Programming
Internet basics
Internet:- Internet is a world-wide global system of interconnected
computer networks.
Internet uses the standard Internet Protocol (TCP/IP).
Every computer in internet is identified by a unique IP address.
IP Address is a unique set of numbers (such as [Link])
which identifies a computer location.
A special computer DNS (Domain Name Server) is used to give
name to the IP Address so that user can locate a computer by
a name.
Internet is accessible to every user all over the world.
Evolution
The origin of Internet devised from the concept of Advanced
Research Project Agency Network (ARPANET).
ARPANET was developed by United States Department of
Defense.
Basic purpose of ARPANET was to provide communication
among the various bodies of government.
Initially, there were only four nodes, formally called Hosts.
In 1972, the ARPANET spread over the globe with 23 nodes
located at different countries and thus became known
as Internet.
By the time, with invention of new technologies such as TCP/IP
protocols, DNS, WWW, browsers, scripting languages etc.
Internet provided a medium to publish and access information
over the web.
Application/Uses of Internet:-
1. Email: -By using Internet, now we can communicate with
person sitting across the world. It can be done using E-mail
(Electronic Mail). Internet can be used for sending and
receiving message from one and other through internet by
using electronic mail. Same as ordinary mail we can send
message electronically, which is easy, fast and secure. And we
can also send images, audio and video with e-mail. We have
Page | 1
numerous websites providing these services like: [Link],
[Link] and [Link].
2. Information: -The biggest advantage of internet is information.
The internet and the World Wide Web has made it easy for
anyone to access information, and it can be of any type, as the
internet is flooded with information. Any kind of information
on any topic is available on the Internet. Books and other study
material stored around the world can be easily located through
internet.
3. Business: -World of business is got a boom with the help of
internet. As internet made it easier for buyers and sellers to
communicate. Classified sites saves us lot of money and time so
this is chosen as medium by most of people to advertise their
products.
4. Social-Networking: -Today social networking sites have
become an important part of our life as online community.
These websites are used to stay in touch with our friends and
family, and it can also be used for business purpose. We can
advertise here easily and availability of our friends and family
to support us.
5. Shopping: -Today life is very busy, we haven’t enough time for
go to shopping every weekend, so most people prefer online
shopping. Today almost anything can be bought with the use of
the internet. We have many shopping sites on internet like
[Link], [Link] and [Link]. We can also
use the internet to sale/auction goods. There are many auction
sites online, where anything can be sold like: [Link],
[Link].
6. Entertainment: -On internet we can find all forms of
entertainment from watching films to playing games online.
Almost anyone can find the right kind of entertainment for
themselves. When people surf the Web, there are numerous
things that can be found; Music, hobbies, news and more can
be found and shared on the Internet. There are many games
that may be downloaded from the Internet for free.
Page | 2
7. E-commerce: -Ecommerce is the concept used for any type of
commercial maneuvering, or business deals that involves the
transfer of information across the globe via internet. It has
become a phenomenon associated with any kind of shopping,
almost anything. It has got a real amazing and range of
products from household needs, technology to entertainment.
8. Services: -Many services are now provided on the internet such
as online banking, purchasing tickets for our favorite movies,
and guidance services on topics in the every aspect of life, and
hotel reservations and bills paying. Often these services are not
available off-line and can cost us more.
9. Job Search: -Internet makes life easy for both employers and
job seekers as there are plenty of job sites which connect
employers and job seekers. Here job seeker can post their
resume and companies can invite candidates for job. Some of
the web sites providing this service are [Link],
[Link], [Link], [Link].
10. Travel: -Anyone can use internet to gather information
about various tourist places. It can be used for booking Holiday
tours , hotels, train and flights.
ISP (Internet Service providers): - An Internet service provider (ISP)
is an organization that provides access to the Internet or it refers to a
company that provides Internet services. ISP may also be called IAP
(Internet Access Providers). An ISP (Internet service provider) is a
company that provides individuals and other
company’s/organization’s access to the Internet and other related
services such as Web site building and virtual hosting. ISP provide
personal as well as business access to the internet, where in personal
access ISP serves individuals and in business access ISP serves large
companies, providing a direct connection from the company's
network to the Internet. ISPs themselves are connected to one
another through Network Access Points (NAPs).
Short for Internet Service Provider, an ISP is a company that provides
Internet access to users or subscribers of its service. The first ISP is
widely believed to be Telenet, which was the first
Page | 3
commercial version of ARPANET introduced in 1974. The first ISP for
the Internet we know and use today is considered to be "The World"
who started serving customers in 1989.
Page | 5
E-mail Header(Anatomy of E-mail)
The first five lines of an E-mail message is called E-mail header. The
header part comprises of following fields:
FROM: The From field indicates the sender’s address i.e. who
sent the e-mail.
DATE: The Date field indicates the date when the e-mail was
sent
TO: The To field indicates the recipient’s address i.e. to whom
the e-mail is sent
SUBJECT: The Subject field indicates the purpose of e-mail. It
should be precise and to the point.
CC: CC stand s for Carbon copy. It includes those recipient
addresses whom we want to keep informed but not exactly the
intended recipient.
BCC: BCC stands for Black Carbon Copy. It is used when we do
not want one or more of the recipients to know that someone
else was copied on the message.
GREETING: Greeting is the opening of the actual message. i.e.
Hi Sir or Hi Guys etc.
TEXT: It represents the actual content of the message.
SIGNATURE: This is the final part of an e-mail message. It
includes Name of Sender, Address, and Contact Number.
Advantages of E-mail:-
Speed: Email enables speed in communication.
Respond: email allows receiver to respond or reply
immediately.
Save paper: use of email saves trees, because it is an alternate
to papers.
Save fuel: using email we don’t need to transfer information
through vehicle.
Formatting: User enjoys sending colorful and attractive
messages using HTML. And also can send images and videos.
Low cost: email has no cost or low cost.
Business: we can send ads of our business through email.
Easy: email sending and receiving is very easy.
Page | 6
Secure: email messages are always secure from unauthorized
persons.
E-mail Protocols
1. SMTP: SMTP stands for Simple Mail Transfer Protocol. It was
first proposed in 1982. It is a standard protocol used for
sending e-mail efficiently and reliably over the internet.
Key Points:
SMTP is application level protocol.
SMTP is connection oriented protocol.
SMTP is text based protocol.
It handles exchange of messages between e-mail servers over
TCP/IP network.
Apart from transferring e-mail, SMPT also provides notification
regarding incoming mail.
When you send e-mail, your e-mail client sends it to your e-
mail server which further contacts the recipient mail server
using SMTP client.
These SMTP commands specify the sender’s and receiver’s e-
mail address, along with the message to be send.
The exchange of commands between servers is carried out
without intervention of any user.
In case, message cannot be delivered, an error report is sent to
the sender which makes SMTP a reliable protocol.
2. IMAP: IMAP stands for Internet Mail Access Protocol. It was
first proposed in 1986. There exist five versions of IMAP as
follows:
1. Original IMAP
2. IMAP2
3. IMAP3
4. IMAP2bis
5. IMAP4
Key Points:
IMAP allows the client program to manipulate the e-mail
message on the server without downloading them on the local
computer.
Page | 7
The e-mail is hold and maintained by the remote server.
It enables us to take any action such as downloading, delete
the mail without reading the mail. It enables us to create,
manipulate and delete remote message folders called mail
boxes.
IMAP enables the users to search the e-mails.
It allows concurrent access to multiple mailboxes on multiple
mail servers.
3. POP: POP stands for Post Office Protocol. It is generally used to
support a single client. There are several versions of POP but
the POP 3 is the current standard.
Key Points
POP is an application layer internet standard protocol.
Since POP supports offline access to the messages, thus
requires less internet usage time.
POP does not allow search facility.
In order to access the messaged, it is necessary to download
them.
It allows only one mailbox to be created on server.
It is not suitable for accessing non mail data.
POP commands are generally abbreviated into codes of three
or four letters. i.e. STAT.
Page | 8
All the messages have to be It allows selective transfer of
4
downloaded. messages to the client.
Page | 9
Working of E-mail
Page | 10
Reading Email: Every email program offers you an interface to access
email messages. Like in Gmail, emails are stored under different tabs
such as primary, social, and promotion. When you click one of tab, it
displays a list of emails under that tab.
In order to read an email, you just have to click on that email. Once
you click a particular email, it gets opened.
The opened email may have some file attached with it. The
attachments are shown at the bottom of the opened email with an
option called download attachment.
Mailing List
In order to send same email to a group of people, an electron list is
created which is known as Mailing List. It is the list server which
receives and distributes postings and automatically manages
subscriptions.
Mailing list offers a forum, where users from all over the globe can
answer questions and have them answered by others with shared
interests.
Types of Mailing List
Following are the various types of mailing lists:
I. RESPONSE LIST: It contains the group of people who have
response to an offer in some way. These people are the
customers who have shown interest in specific product or
service.
II. COMPILED LIST: The compiled list is prepared by collecting
information from various sources such as surveys,
telemarketing etc.
III. ANNOUNCEMENTS: These lists are created for sending out
coupons , new product announcements and other offers to the
customers.
IV. DISCUSSION LIST: This list is created for sharing views on a
specific topic such as computer, environment , health,
education etc.
How does mailing list work?
Before joining a mailing list, it is mandatory to subscribe to it. Once
you are subscribed, your message will be sent to all the persons who
Page | 11
have subscribed to the list. Similarly if any subscriber posts a
message, then it will be received by all subscribers of the list.
Page | 13
Unit-2
WWW:-WWW stands for the World Wide Web or simply the Web.
WWW is a network of information spread all over the world, stored
on computers. All the computers connected to WWW, can
communicate to each other. The Web standards are made up by
W3C (World Wide Web Consortium). WWW is a part of the Internet
accessed through a graphical user interface and containing
documents often connected by hyperlinks. It is important to know
that this is not a synonym for the Internet. The World Wide Web, or
just "the Web," as ordinary people call it, is a subset of the Internet.
The Web consists of pages that can be accessed using a Web
browser. The Internet is the actual network of networks where all
the information resides. Things like Telnet, FTP, Internet gaming,
Internet Relay Chat (IRC), and e-mail are all part of the Internet, but
are not part of the World Wide Web. The Hyper-Text Transfer
Protocol (HTTP) is the method used to transfer Web pages to your
computer. With hypertext, a word or phrase can contain a link to
another Web site. All Web pages are written in the hyper-text
markup language (HTML), which works in conjunction with HTTP. “An
information system on the Internet which allows documents to be
connected to other documents by hypertext links, enabling the user
to search for information by moving from one document to
another.” “The World Wide Web is a huge collection of hypertext
documents and hypermedia. It has facilitated easy access to
information over the Internet.”
Page | 14
of web servers serves as the backbone of the World Wide Web. The
Hypertext Transfer Protocol (HTTP) is used to gain access to the web.
A web browser makes a request for a particular web page to the web
server, which in turn responds with the requested web page and its
contents. It then displays the web page as rendered by HTML or
other web languages used by the page. Each web page has a unique
address, with the help of which a browser accesses it, with the help
of the domain name system.
Categories:
General Search: -AltaVista, AlltheWeb, Gigablast, Google, HotBot,
Lycos, MSN, Rolist, SearchHippo, Teoma, WiseNut
Page | 16
#HTTP:- Hypertext Transfer (or Transport) Protocol, the data transfer
protocol used on the World Wide Web. Short for Hypertext Transfer
Protocol, the underlying protocol used by the World Wide Web.
HTTP defines how messages are formatted and transmitted, and
what actions Web servers and browsers should take in response to
various commands. For example, when you enter a URL in your
browser, this actually sends an HTTP command to the Web server
directing it to fetch and transmit the requested Web page. HTTP is
called a stateless protocol because each command is executed in
dependently, without any knowledge of the commands that came
before it. Hypertext transfer protocol (HTTP) is a communications
protocol that transfers information on intranets and the World Wide
Web to retrieve and publish hypertext pages. The hypertext transfer
protocol is in place to send out the message that a particular web
browser is looking for the particular web page at the address that
follows the HTTP in the address bar of the web browser window. It is
a response or request protocol between a client and a server to
access a certain resource, which may be a web page or other graphic
stored in the server as files. The client can be a number of things,
such as a web browser, a search engine spider, or any other end-user
tool, while the server is a storage area for a particular set of HTML
files and images. The user agent, as the client is called, uses the
hypertext transfer protocol to communicate with the server, which is
also called the origin server. Of course, the simplistic way of looking
at hypertext transfer protocols is certainly a good way to learn how
they work, but there is much more to HTTP than simply sending the
message that an end user wants to see a web page. HTTP actually
identifies eight different methods which indicate what the desired
action is and what action should be performed.
Page | 17
These eight different methods are: -
HEAD
GET
POST
PUT
DELETE
TRACE
OPTIONS
CONNECT
Important to communication and the way the entire Internet works,
the hypertext transfer protocol or HTTP is a necessary protocol.
Architecture of HTTP: -
1. network protocol
2. host name or address
Page | 18
3. file or resource location
These substrings are separated by special characters as follows:
protocol://host/location
#FTP (File Transfer Protocol): -FTP (or "file transfer protocol") lets
people and applications exchange and share data within their offices
and across the Internet.
April 16,19s71 by AbhayBhushan. FTP is a standard way of sending
and receiving files between two computers. A good example of how
FTP is used today is by web developers, who will connect to their
web server using FTP and send updated versions of their web pages
to the server. Although many FTP servers require logins, many FTP
servers also allow anonymous ftplogin, which only require a
username, often an e-mail and no password. It is also important to
Page | 20
realize that FTP is insecure. When your username and password are
sent to the server they're both sent as plaintext and could be
intercepted and read. If your server supports SFTP or FTP with TLS
encryption, we suggest one of them instead of plain FTP to help keep
your information private.
Application server
Storage
File system
Database
Page | 22
Unit-3
Hyper Text Mark-up Language
Page | 23
they are viewed. Dynamic pages have content that can change each
time they are accessed.
Angle brackets: -less than (<) and greater than (>) symbols used to
surround an element to create a tag.
Broken links: -Broken links are those links that do not work because
the destination has been deleted or the path has been changed.
Closing tag: -An HTML instruction that tells the browser to turn off a
specific feature of an opening tag.
Page | 25
Footer text: -The text that is not specifically related to the content of
the webpage and that appears on every webpage is referred to as
footer text. The most notable example of footer text is the copyright
statements at the bottom of webpages.
FTP: -FTP stands for File Transfer Protocol. FTP is a robust method for
transferring files between computers using TCP/IP. TCP stands for
Transmission Control Protocol and IP stands for Internet Protocol.
TCP is responsible for transporting data and IP is responsible for
making sure data goes to the correct address.
Page | 26
Hypermedia: -Hypertext that may include multimedia like text,
images, sound, and video.
Line break: -Line break simply refers to stop of the current line and
continuation to the next line. In HTML documents, the <br> tag is
used to end a line.
Page | 27
Obsoleted element: -An element that won't necessarily work in the
future versions of browsers. Any obsolete element that you may be
using in your website should be removed; otherwise, newer
browsers would ignore that element.
Opening tag: -An HTML instruction that tells the browser to turn on
the feature and apply it to the document content that follows.
Style sheet: -A style sheet includes styling syntax (rules) that dictates
how your web page will look. Style sheets are very useful as they
help web developers create uniform (or consistent) presentation of
web pages.
Page | 28
Syntax: -Syntax basically refers to the rules a computer language
uses to perform a task. Without syntax, a computer language would
not be functional or useful at all. HTML syntax dictates what and how
a web page will display.
HTML Tags:-
Page | 29
HTML tags are not case sensitive.
We can use nested HTML tags.
Use lower case for HTML tags, because w3c recommends lower
case tags in HTML4 and above.
Example: -
<HTML>
<BODY>
<H1>Heading 1</H1>
</BODY>
</HTML>
Example Explained: -
Tag Attributes:-
Font tags specify the font size, font face and color of text.
Syntax:
Page | 31
The most important attribute of the <a> element is the href
attribute, which indicates the link’s destination.
By default, links will appear as follows in all browsers:
An unvisited link is underlined and blue
A visited link is underlined and purple
An active link is underlined and red
#HTML Link Syntax
The HTML code for a link is simple. It looks like this:
<a href="url">Link text</a>
Page | 32
The list items are marked with numbers.
<ol>
<li>Coffee</li>
<li>Milk</li>
</ol>
Milk
#HTML Image Tag: -The image tag is used to place an image on the
web [Link] is very important to understand that images are not
technically "part" of the web page file, they are separate files which
are inserted into the page when it is viewed by a browser. So a
Page | 33
simple web page with one image is actually two files - the HTML file
and the image [Link] it’s most simple form it looks like this:
<img src="[Link]">
The size attributes define the width and height of the image. They
look like this:
<img src="[Link]"align="left">
<form>
Input fields
</form>
1. <input>
2. <textarea>
3. <button>
4. <select>
5. <option>
6. <optgroup>
7. <fieldset>
8. <label>
The Input Element: -The most important form element is the <input>
[Link] <input> element is used to select user [Link]
<input> element can vary in many ways, depending on the type
attribute. An <input> element can be of type text field, checkbox,
password, radio button, submit button, and [Link] most common
input types are described below.
Text Fields
<input type="text">
Page | 35
Defines a one-line input field that a user can enter text into:
<form>
First name: <input type="text" name="firstname"><br>
Last name: <input type="text" name="lastname">
</form>
Note: The form itself is not visible. Also note that the default width of
a text field is 20 characters.
Password Field
<input type="password">
<form>
Password: <input type="password" name="pwd">
</form>
Radio Buttons
<input type="radio">
Define a radio button. Radio buttons let a user select ONLY ONE of a
limited number of choices:
<form>
<input type="radio" name="sex" value="male">Male<br>
<input type="radio" name="sex" value="female">Female
</form>
Checkboxes
<input type="checkbox">
Page | 36
defines a checkbox. Checkboxes let a user select ZERO or MORE
options of a limited number of choices.
<form>
<input type="checkbox" name="vehicle" value="Bike">I have a
bike<br>
<input type="checkbox" name="vehicle" value="Car">I have a car
</form>
Submit Button
<input type="submit">
#HTML Frames:
Page | 37
each frame within the frameset. All frame tags are nested with
a <frameset> tag.
Syntax:
The frameset is used instead of the <body> and </body> tags. Rows
and cols attributes can be used to describe the dimensions of the
frames in comma-separated lists of sizes (in pixels or percentages). If
the percentages, do not add to 100 the browser should adjust the
sizes proportionally. Any row or column size may be replaced with an
asterisk (*) to indicate the remainder of the remaining screen space.
Within the frameset, the framed panels are described with their
source documents. The <noframes> element may be included so
browsers with frames disabled (or browsers that don't support
frames) can display something to the user, as in this example:
<noframes>
</noframes>
</frameset>
Rows Specifies the number of rows and their height in either pixels, perc
Cols Specifies the number of columns and their width in either pixels, p
For each frame you want to display, you specify a frame tag. You nest
these within the frameset tag.
Attribute Description
Src Location of the frame contents (for example, the HTML page to
scrolling Whether the frame should be scrollable or not (i.e. should scro
Page | 39
appear). Possible values:
auto
yes
no
frameborder Whether the frame should have a border or not. Possible value
1 (border)
0 (no border)
marginwidth Specifies the margin, in pixels, between the frame's contents a
IFrame(Inline Frame):
Page | 40
<iframe src="URL"></iframe>
The height and width attributes are used to specify the height and
width of the iframe.
The attribute values are specified in pixels by default, but they can
also be in percent (like "80%").
Page | 41
0 border around an <iframe>
Page | 42
Unit-4
#CSS:-CSS stands for Cascading style sheets. Cascading style sheets
are used to format the layout of Web pages. Till now we use HTML
for layout of our web page, and also for formatting of web page, CSS
allows us to separate our page layout and formatting. Layout is still
done in HTML but formatting done in CSS. There are no confusion
between layout and formatting. And CSS allows us to Write CSS code
in different file, and use same file with multiple HTML [Link]
allows designers to determine how a document is viewed in a
browser over theWorld Wide Web (WWW) by applying tags that
manipulate the appearance or assign style to the text. The purpose
of cascading style sheets (CSS) is to allow Web developers to
manipulate a Web page's appearance without affecting its HTML
structure.“CSS can give a designer the ability to separate content and
presentation.” CSS can be created by using a normal text editor,
which is similar to creating HTML code, or by using software tools.
<head>
</head>
Page | 43
An external style sheet can be written in any text editor. The file
should not contain any html tags. Your style sheet should be saved
with a .css extension.
<head>
<style>
hr {color:red;}
p {margin-left:20px;}
body {background-image:url("images/[Link]");}
</style>
</head>
1. Inline Style.
2. Internal Style Sheet.
3. External Style Sheet.
4. Browser default.
Page | 44
Class in CSS:-The class selector is used to specify a style for a group
of elements. The class selector is most often used on multiple
elements. This allows you to set a particular style for many HTML
elements with the same class. The class selector uses the HTML class
attribute, and is defined with a "." You declare a CSS class by
using a dot (.) followed by the class name. You make up the class
name yourself. After the class name you simply enter the
properties/values that you want to assign to your class.
<html>
<head>
<style>
.center
text-align:center;
</style>
</head>
<body>
</body>
</html>
Page | 45
DIV Tag:-The <div> tag defines a division or a section in an HTML
document. The <div> tag is used to group block-elements to format
them with CSS. The <div> element is very often used together with
CSS, to layout a web page. By default, browsers always place a line
break before and after the <div> element. However, this can be
changed with CSS.
Example:-
<html>
<body>
</div>
</body>
</html>
Example:
Page | 46
<html>
<body>
</body>
</html>
Page | 47
Cause text or a graphic image to change during a mouse
rollover
Variables:-Like many other programming languages, JavaScript has
variables. Variables can be thought of as named containers. You can
place data into these containers and then refer to the data simply by
naming the [Link] is stored in the memory. Actually, data is
not stored in the variable. A variable is the name given to the
memory location. A variable name is an entity that points to a
particular memory [Link] you uses a variable in a JavaScript
program, you must declare it. Variables are declared with the var
keyword as follows:
<script type="text/javascript">
var money;
var name;
</script>
You can also declare multiple variables with the same var keyword as
follows:
<script type="text/javascript">
</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.
Page | 48
JavaScript is Loosely Typed(untyped) language. This means that a
JavaScript variable can hold a value of any data type. Unlike many
other languages, you don't have to tell JavaScript during variable
declaration what type of value the variable will hold. The value type
of a variable can change during the execution of a program and
JavaScript takes care of it automatically.
Arithmetic Operators
Comparison Operators
Logical (or Relational) Operators
Assignment Operators
Conditional (or ternary) Operators
The Arithmetic Operators:- There are following arithmetic operators
supported by JavaScript language:
Page | 49
Operator Description Example
Page | 50
Checks if the values of two
operands are equal or not, if values
!= (A != B) is true.
are not equal then condition
becomes true.
Page | 51
Operator Description Example
Page | 52
on each bit of its integer
arguments.
Page | 53
of the original operand, in order to
preserve the sign of the result. If
the first operand is positive, the
result has zeros placed in the high
bits; if the first operand is negative,
the result has ones placed in the
high bits. Shifting a value right one
place is equivalent to dividing by 2
(discarding the remainder), shifting
right two places is equivalent to
integer division by 4, and so on.
Page | 55
If Condition is true ? Then
?: Conditional Expression
value X : Otherwise value Y
Number "number"
String "string"
Boolean "boolean"
Object "object"
Function "function"
Undefined "undefined"
Null "object"
Page | 56
Built-In Functions:-Built in functions are those functions, whose
working is already defined. User just has to use them with their exact
syntax. JS supports many built in functions.
Page | 57
Unit-5
Page | 58
JavaScript can react to events - A JavaScript can be set to execute
when something happens, like when a page has finished loading or
when a user clicks on an HTML element
JavaScript can read and write HTML elements - A JavaScript can
read and change the content of an HTML element
JavaScript can be used to validate data - A JavaScript can be used to
validate form data before it is submitted to a server. This saves the
server from extra processing
JavaScript can be used to detect the visitor's browser - A JavaScript
can be used to detect the visitor's browser, and - depending on the
browser - load another page specifically designed for that browser
JavaScript can be used to create cookies - A JavaScript can be used
to store and retrieve information on the visitor's computer
Where to Put the JavaScript
JavaScripts in a page will be executed immediately while the page
loads into the browser. This is not always what we want. Sometimes
we want to execute a script when a page loads, other times when a
user triggers an event.
Scripts in the head section
Scripts to be executed when they are called, or when an event is
triggered, go in the head section. When you place a script in the head
section, you will ensure that the script is loaded before anyone uses
it.
<html>
<head>
<script type="text/javascript">
....
</script>
</head>
Scripts in the body section
Scripts to be executed when the page loads go in the body
section. When you place a script in the body section it generates the
content of the page.
<html>
<head>
Page | 59
</head>
<body>
<script type="text/javascript">
....
</script>
</body>
Note: -
<script> tag
Script tag tells the browser where the scripting starts (<script
type="text/javascript">) and ends(</script>). Type attribute indicates
the type of scripting language we're using. In our case it's JavaScript,
that's why type is equal to "text/javascript".
[Link]
The word [Link] is a standard JavaScript command for
writing output to a page.
JavaScript Comments
JavaScript comments can be used to explain JavaScript code, and to
make it more readable.
JavaScript comments can also be used to prevent execution, when
testing alternative code.
Single Line Comments
Single line comments start with //.
Any text between // and the end of the line will be ignored by
JavaScript (will not be executed).
This example uses a single-line comment before each code line:
<!DOCTYPE html>
<html>
<body>
<h1 id="myH"></h1>
<p id="myP"></p>
<script>
// Change heading:
[Link]("myH").innerHTML = "JavaScript
Comments";
// Change paragraph:
Page | 60
[Link]("myP").innerHTML = "My first
paragraph.";
</script>
</body>
</html>
Multi-line Comments
Multi-line comments start with /* and end with */.
Any text between /* and */ will be ignored by JavaScript.
This example uses a multi-line comment (a comment block) to
explain the code:
<!DOCTYPE html>
<html>
<body>
<h1 id="myH"></h1>
<p id="myP"></p>
<script>
/*
The code below will change
the heading with id = "myH"
and the paragraph with id = "myP"
*/
[Link]("myH").innerHTML = "JavaScript
Comments";
[Link]("myP").innerHTML = "My first
paragraph.";
</script>
</body>
</html>
JavaScript Variables
Like many other programming languages, JavaScript has variables.
Variables can be thought of as named containers. You can place
data into these containers and then refer to the data simply by
naming the container.
Before you use a variable in a JavaScript program, you must declare
it. Variables are declared with the var keyword as follows.
Page | 61
<script type = "text/javascript">
<!--
var money;
var name;
//-->
</script>
JavaScript Identifiers
All JavaScript variables must be identified with unique names.
These unique names are called identifiers.
Identifiers can be short names (like x and y) or more descriptive
names (age, sum, totalVolume).
The general rules for constructing names for variables (unique
identifiers) are:
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
JavaScript identifiers are case-sensitive.
JavaScript Variable Scope
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. Function parameters are always
local to that function.
<html>
<body onload = checkscope();>
<script type = "text/javascript">
<!--
var myVar = "global"; // Declare a global variable
function checkscope( ) {
var myVar = "local"; // Declare a local variable
Page | 62
[Link](myVar);
}
//-->
</script>
</body>
</html>
What is an Operator?
Let us take a simple expression 4 + 5 is equal to 9. Here 4 and 5 are
called operands and ‘+’ is called the operator. JavaScript supports
the following types of operators.
Arithmetic Operators
Comparison Operators
Logical (or Relational) Operators
Assignment Operators
Conditional (or ternary) Operators
Let’s have a look on all operators one by one.
Arithmetic Operators
JavaScript supports the following arithmetic operators −
Assume variable A holds 10 and variable B holds 20, then −
[Link]. Operator & Description
1 + (Addition)
Adds two operands
Ex: A + B will give 30
2 - (Subtraction)
Subtracts the second operand from the first
Ex: A - B will give -10
3 * (Multiplication)
Multiply both operands
Ex: A * B will give 200
4 / (Division)
Divide the numerator by the denominator
Ex: B / A will give 2
Page | 63
5 % (Modulus)
Outputs the remainder of an integer division
Ex: B % A will give 0
6 ++ (Increment)
Increases an integer value by one
Ex: A++ will give 11
7 -- (Decrement)
Decreases an integer value by one
Ex: A-- will give 9
Note − Addition operator (+) works for Numeric as well as Strings.
e.g. "a" + 10 will give "a10".
Comparison Operators
JavaScript supports the following comparison operators −
Assume variable A holds 10 and variable B holds 20, then −
[Link]. Operator & Description
1 = = (Equal)
Checks if the values of two operands are equal or not, if
yes, then the condition becomes true.
Ex: (A == B) is not true.
2 != (Not Equal)
Checks if the values of two operands are equal or not, if
the values are not equal, then the condition becomes true.
Ex: (A != B) is true.
2 || (Logical OR)
If any of the two operands are non-zero, then the
condition becomes true.
Ex: (A || B) is true.
3 ! (Logical NOT)
Reverses the logical state of its operand. If a condition is
true, then the Logical NOT operator will make it false.
Ex: ! (A && B) is false.
Bitwise Operators
Page | 65
JavaScript supports the following bitwise operators −
Assume variable A holds 2 and variable B holds 3, then −
[Link]. Operator & Description
2 | (Bitwise OR)
It performs a Boolean OR operation on each bit of its
integer arguments.
Ex: (A | B) is 3.
3 ^ (Bitwise XOR)
It performs a Boolean exclusive OR operation on each bit
of its integer arguments. Exclusive OR means that either
operand one is true or operand two is true, but not both.
Ex: (A ^ B) is 1.
4 ~ (Bitwise Not)
It is a unary operator and operates by reversing all the bits
in the operand.
Ex: (~B) is -4.
Page | 66
operand.
Ex: (A >> 1) is 1.
1 = (Simple Assignment )
Assigns values from the right side operand to the left side
operand
Ex: C = A + B will assign the value of A + B into C
Page | 67
6 %= (Modules and Assignment)
It takes modulus using two operands and assigns the result
to the left operand.
Ex: C %= A is equivalent to C = C % A
Note − Same logic applies to Bitwise operators so they will become
like <<=, >>=, >>=, &=, |= and ^=.
Miscellaneous Operator
We will discuss two operators here that are quite useful in
JavaScript: the conditional operator (? :) and the typeof operator.
Conditional Operator (? :)
The conditional operator first evaluates an expression for a true or
false value and then executes one of the two given statements
depending upon the result of the evaluation.
[Link]. Operator and Description
1 ? : (Conditional )
If Condition is true? Then value X : Otherwise value Y
JavaScript Data Types
JavaScript variables can hold many data types: numbers, strings,
objects and more:
var length= 16;
var lastName= "Johnson";
var x = {firstName:"John", lastName:"Doe"}; // Object
JavaScript Strings
A string (or a text string) is a series of characters like "John Doe".
Strings are written with quotes. You can use single or double quotes:
var carName1= "Volvo";
JavaScript Numbers
JavaScript has only one type of numbers.
Numbers can be written with, or without decimals:
var x1= 34.00; //with-decimals
var x2 = 34; // without decimals
Page | 68
JavaScript Booleans
Booleans can only have two values: true or false.
var x= 5;
var y= 5;
var z= 6;
(x==y) //Returns true
(x == z) // Returns false
JavaScript Arrays
JavaScript arrays are written with square brackets.
Array items are separated by commas.
The following code declares (creates) an array called cars, containing
three items (car names):
<script>
var cars = ["Saab","Volvo","BMW"];
[Link]("demo").innerHTML = cars[0];
</script>
JavaScript Objects
JavaScript objects are written with curly braces {}.
Object properties are written as name: value pairs, separated by
commas.
<script>
var person = {
firstName : "John",
lastName : "Doe",
age : 50,
eyeColor : "blue"
};
[Link]("demo").innerHTML =
[Link] + " is " + [Link] + " years old.";
</script>
Primitive Data
A primitive data value is a single simple data value with no additional
properties and methods.
Page | 69
The typeof operator can return one of these primitive types:
string
number
boolean
undefined
<script>
[Link]("demo").innerHTML =
typeof "john" + "<br>" +
typeof 3.14 + "<br>" +
typeof true + "<br>" +
typeof false + "<br>" +
typeof x;
</script>
Output
string
number
boolean
boolean
undefined
Complex Data
The typeof operator can return one of two complex types:
function
object
The typeof operator returns object for objects, arrays, and null.
The typeof operator does not return object for functions.
<script>
[Link]("demo").innerHTML =
typeof {name:'john', age:34} + "<br>" +
typeof [1,2,3,4] + "<br>" +
typeof null + "<br>" +
typeof function myFunc(){};
</script>
Output:
object
object
Page | 70
object
function
What is conditions statements(Decision making/selection
statements)
JavaScript supports conditional statements which are used to
perform different actions based on different conditions. Here we
will explain the [Link] statement.
if statement
if...else statement
if...else if... statement.
1. The if Statement
Use the if statement to specify a block of JavaScript code to be
executed if a condition is true.
Syntax
if (condition)
{
// block of code to be executed if the condition is true
}
Example
<script>
Var age=20;
if (age> 18)
{
[Link](“Qualifies for driving”);
}
</script>
2. if...else statement:-
If condition is true then if code execute otherwise else code execute.
Syntax
if (condition)
{
//if code
}
else
{
Page | 71
//else code
}
Example:
<script>
Var age=20;
if (age> 18)
{
[Link](“Qualifies for driving”);
}
else
{
[Link](“Disqualifies for driving”);
}
</script>
3. The else if Statement
Use the else if statement to specify a new condition if the first
condition is false.
Syntax
if (condition1)
{
// block of code to be executed if condition1 is true
}
else if (condition2)
{
// block of code to be executed if the condition1 is false and
condition2 is true
}
else
{
// block of code to be executed if the condition1 is false and
condition2 is false
}
Example:
<script>
Page | 72
Var per=70.55;
if (per>=60)
{
[Link](“1st Division”);
}
else if(per>=45)
{
[Link](“2nd Division”);
}
else if(per>=33)
{
[Link](“3rd Division”);
}
else
{
[Link](“Fail”);
}
</script>
break;
case y:
//code block;
break;
default:
//code block;
Page | 73
}
Example:
<script>
var day=2;
switch (day)
{
case 1:
[Link](“MON”);
break;
case 2:
[Link](“TUE”);
break;
case 3:
[Link](“WED”);
break;
case 4:
[Link](“THR”);
break;
case 5:
[Link](“FRI”);
break;
case 6:
[Link](“SAT”);
break;
case 7:
[Link](“SUN”);
break;
default:
[Link](“Wrong choice”);
}
</script>
JavaScript Loops
Loops are handy, if you want to run the same code over and over
again, each time with a different value.
Page | 74
Different Kinds of Loops
JavaScript supports different kinds of loops:
for - loops through a block of code a number of times
for/in - loops through the properties of an object
while - loops through a block of code while a specified
condition is true
do/while - also loops through a block of code while a specified
condition is true
The For Loop
The for loop has the following syntax:
for (statement 1; statement 2; statement 3)
{
//statements
}
Statement 1 is executed (one time) before the execution of the code
block.
Statement 2 defines the condition for executing the code block.
Statement 3 is executed (every time) after the code block has been
executed.
Example: -
<script>
var i;
for (i = 1; i < =5; i++)
{
[Link](i);
}
</script>
The While Loop
The while loop loops through a block of code as long as a specified
condition is true.
Syntax
while (condition)
{
// code block to be executed
}
Page | 75
Example
<script>
var i=1;
while (i < =5)
{
[Link](i);
i++;
}
</script>
The Do/While Loop
The do/while loop is a variant of the while loop. This loop will
execute the code block once, before checking if the condition is true,
and then it will repeat the loop as long as the condition is true.
Syntax
do
{
// code block to be executed
}
while (condition);
Example
<script>
var i=1;
do
{
[Link](i);
i++;
} while (i < =5);
</script>
What is an Array?
An array is a special variable, which can hold more than one value at
a time.
If you have a list of items (a list of car names, for example), storing
the cars in single variables could look like this:
Page | 76
var car1 = "Saab";
var car2 = "Volvo";
var car3 = "BMW";
Creating an Array
Using an array literal is the easiest way to create a JavaScript Array.
Syntax:
var array_name = [item1, item2, ...];
Example: -
<script>
var cars = ["Saab", "Volvo", "BMW"];
[Link](cars);
</script>
Access the Elements of an Array
You access an array element by referring to the index number.
This statement accesses the value of the first element in cars:
Example: -
<script>
var cars = ["Saab", "Volvo", "BMW"];
[Link]( cars[0]);
</script>
JavaScript Objects
Object Definition
You define (and create) a JavaScript object with an object literal:
<script>
// Create an object:
var person ={firstName:"John", lastName:"Doe", age:50,
eyeColor:"blue"};
</script>
Object Properties
The name:values pairs in JavaScript objects are called properties:
Property Property Value
firstName John
Page | 77
lastName Doe
age 50
eyeColor Blue
Example
var person = {
firstName: "John",
lastName : "Doe",
id : 5566,
Page | 78
fullName : function() {
return [Link] + " " + [Link];
}
};
Accessing Object Methods
You access an object method with the following syntax:
[Link]()
Example
name = [Link]();
JavaScript Popup Boxes
JavaScript has three kind of popup boxes: Alert box, Confirm box,
and Prompt box.
Alert Box
An alert box is often used if you want to make sure information
comes through to the user.
When an alert box pops up, the user will have to click "OK" to
proceed.
Syntax
[Link]("sometext");
The [Link]() method can be written without the window
prefix.
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
alert("I am an alert box!");
}
</script>
Confirm Box
A confirm box is often used if you want the user to verify or accept
something.
When a confirm box pops up, the user will have to click either "OK"
or "Cancel" to proceed.
If the user clicks "OK", the box returns true. If the user clicks
"Cancel", the box returns false.
Syntax
Page | 79
[Link]("sometext");
The [Link]() method can be written without the window
prefix.
Prompt Box
A prompt box is often used if you want the user to input a value
before entering a page.
When a prompt box pops up, the user will have to click either "OK"
or "Cancel" to proceed after entering an input value.
If the user clicks "OK" the box returns the input value. If the user
clicks "Cancel" the box returns null.
Syntax
[Link]("sometext","defaultText");
The [Link]() method can be written without the window
prefix.
What is JavaScript
JavaScript is the world's most popular programming language.
JavaScript is the programming language of the Web.
JavaScript is easy to learn.
Why Study JavaScript?
JavaScript is one of the 3 languages all web developers must learn:
1. HTML to define the content of web pages
2. CSS to specify the layout of web pages
3. JavaScript to program the behavior of web pages
JavaScript Where To
The <script> Tag
In HTML, JavaScript code is inserted
between <script> and </script> tags.
JavaScript in <head> or <body>
You can place any number of scripts in an HTML document.
Scripts can be placed in the <body>, or in the <head> section of an
HTML page, or in both.
JavaScript Comments
JavaScript comments can be used to explain JavaScript code, and to
make it more readable.
Page | 80
JavaScript comments can also be used to prevent execution, when
testing alternative code.
Single Line Comments
Single line comments start with //.
Multi-line Comments
Multi-line comments start with /* and end with */.
Any text between /* and */ will be ignored by JavaScript.
JavaScript Variables
JavaScript variables are containers for storing data values.
In this example, x, y, and z, are variables, declared with
the var keyword:
Example:
var x = 5;
var y = 6;
var z = x + y;
JavaScript Identifiers
All JavaScript variables must be identified with unique names.
These unique names are called identifiers.
Identifiers can be short names (like x and y) or more descriptive
names (age, sum, totalVolume).
The general rules for constructing names for variables (unique
identifiers) are:
Names can contain letters, digits, underscores, and dollar signs.
Names must begin with a letter
Names can also begin with $ and _
Names are case sensitive (y and Y are different variables)
Reserved words (like JavaScript keywords) cannot be used as
names
Type of variable : -
1. Local variable (declare inside the function)
2. Global variable(declare outside the function)
Example:
var y=20; //global
Function L2CL()
Page | 81
{
var x=10; //local
[Link](x+y);
}
Javascript Data Types
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
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. For
example:
var a=40;//holding number
var b="Rahul";//holding string
JavaScript primitive data types
There are five types of primitive data types in JavaScript. They are as
follows:
Data Type Description
+ Addition 10+20 = 30
- Subtraction 20-10 = 10
/ Division 20/10 = 2
Page | 83
JavaScript Comparison Operators
The JavaScript comparison operator compares the two operands.
The comparison operators are as follows:
Operator Description Example
Page | 84
>> Bitwise Right Shift (10>>2) = 2
= Assign 10+10 = 20
Page | 85
, Comma Operator allows multiple expressions to be
evaluated as single statement.
<button onclick="CDC()">L2CL</button>
<script>
function CDC()
{
alert("Lane to Computer learning.......");
}
</script>
</body>
</html>
Confirm Box
A confirm box is often used if you want the user to verify or accept
something.
Page | 87
When a confirm box pops up, the user will have to click either "OK"
or "Cancel" to proceed.
If the user clicks "OK", the box returns true. If the user clicks
"Cancel", the box returns false.
Syntax
[Link]("sometext");
Example:
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
function CDC()
{
var txt;
if (confirm("Press a button!"))
{
txt = "You pressed OK!";
}
else
{
txt = "You pressed Cancel!";
}
[Link]("demo").innerHTML = txt;
}
</script>
</body>
</html>
Page | 88
Prompt Box
A prompt box is often used if you want the user to input a value
before entering a page.
When a prompt box pops up, the user will have to click either "OK"
or "Cancel" to proceed after entering an input value.
If the user clicks "OK" the box returns the input value. If the user
clicks "Cancel" the box returns null.
Syntax
[Link]("sometext","defaultText");
Example:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Prompt</h2>
<p id="demo"></p>
<script>
function myFunction() {
var txt;
var person = prompt("Please enter your name:", "Harry Potter");
if (person == null || person == "")
{
txt = "User cancelled the prompt.";
}
else
{
txt = "Hello " + person + "! How are you today?";
}
[Link]("demo").innerHTML = txt;
}
</script>
Page | 89
</body>
</html>
JavaScript Events
HTML Events
An HTML event can be something the browser does, or something a
user does.
Here are some examples of HTML events:
An HTML web page has finished loading
An HTML input field was changed
An HTML button was clicked
Often, when events happen, you may want to do something.
JavaScript lets you execute code when events are detected.
HTML allows event handler attributes, with JavaScript code, to be
added to HTML elements.
With single quotes:
<element event='some JavaScript'>
With double quotes:
<element event="some JavaScript">
In the following example, an onclick attribute (with code), is added to
a <button> element:
Example:
<button onclick="[Link]('demo').innerHTML =
Date()">The time is?</button>
In the example above, the JavaScript code changes the content of
the element with id="demo".
In the next example, the code changes the content of its own
element (using [Link]):
Example:
<button onclick="[Link] = Date()">The time is?</button>
Common HTML Events
Here is a list of some common HTML events:
Event Description
Page | 90
Onchange An HTML element has been changed
Onclick The user clicks an HTML element
onmouseover The user moves the mouse over an HTML element
onmouseout The user moves the mouse away from an HTML
element
Onkeydown The user pushes a keyboard key
Onload The browser has finished loading the page
What is an Array?
An array is a special variable, which can hold more than one value at
a time.
If you have a list of items (a list of car names, for example), storing
the cars in single variables could look like this:
var car1 = "Saab";
var car2 = "Volvo";
var car3 = "BMW";
However, what if you want to loop through the cars and find a
specific one? And what if you had not 3 cars, but 300?
The solution is an array!
Creating an Array
Using an array literal is the easiest way to create a JavaScript Array.
Syntax:
var array_name = [item1, item2, ...];
Example: -
var cars = ["Saab", "Volvo", "BMW"];
Access the Elements of an Array
Example: -
var cars = ["Saab", "Volvo", "BMW"];
[Link](cars[2]);
Page | 91
Access the Full Array
With JavaScript, the full array can be accessed by referring to the
array name:
Example:
var cars = ["Saab", "Volvo", "BMW"];
[Link](cars);
Arrays are Objects
Arrays are a special type of objects. The typeof operator in JavaScript
returns "object" for arrays.
But, JavaScript arrays are best described as arrays.
Arrays use numbers to access its "elements". In this
example, person[0] returns John:
Example:
var person = ["John", "Doe", 46];
Page | 92