Internet Technology 2
Internet Technology 2
Introduction to Internet
Technologies and HTML
Course Writer
Content Editor
Prof. (Dr.) Nilesh K. Modi Professor and Director, School of Computer Science,
Dr. Babasaheb Ambedkar Open University, Ahmedabad
ISBN -
Printed and published by: Dr. Babasaheb Ambedkar Open University, Ahmedabad While all efforts
have been made by editors to check accuracy of the content, the representation of facts, principles,
descriptions and methods are that of the respective module writers. Views expressed in the publication
are that of the authors, and do not necessarily reflect the views of Dr. Babasaheb Ambedkar Open
University. All products and services mentioned are owned by their respective copyrights holders, and
mere presentation in the publication does not mean endorsement by Dr. Babasaheb Ambedkar Open
University. Every effort has been made to acknowledge and attribute all sources of information used in
preparation of this learning material. Readers are requested to kindly notify missing attribution, if any.
Dr. Babasaheb BCAMI-103
Ambedkar Open
University
UNIT-1
INTRODUCTION TO WEB 06
UNIT-2
HYPERTEXT MARKUP LANGUAGE 21
UNIT-3
WORKING WITH TEXT 32
UNIT-4
WORKING WITH LISTS, TABLES AND FRAMES 40
UNIT-5
WORKING WITH HYPERLINKS, IMAGES,
MULTIMEDIA AND FORMS 64
UNIT-6
INTRODUCTION TO HTML5 88
UNIT-7
INTRODUCTION TO NEW ELEMENTS IN HTML5 98
BLOCK-3: DYNAMIC HTML CONCEPTS (CSS,JAVA
SCRIPT)
UNIT-8
CASCADING STYLE SHEET 105
UNIT-9
CASCADING STYLE SHEET ATTRIBUTES AND
PROPERTIES 119
UNIT-10
INTRODUCTION TO JAVA SCRIPT 130
UNIT-11
ARRAYS, FUNCTIONS, EVENTS AND DIALOG BOXES
IN JAVA SCRIPT 150
UNIT-12
JAVA SCRIPT OBJECTS, METHODS AND PROPERTIES 159
UNIT-13
INTRODUCTION TO JQUERY 194
UNIT-14
JQUERY SELECTORS, FUNCTIONS, EFFECTS AND
EVENTS 199
UNIT-15
INTRODUCTION TO XML 298
Introduction to Web-Desisgning
Contents
BLOCK1: INTRODUCTION TO WEB AND HTML
UNIT 1 INTRODUCTION TO WEB
Adding plain Text to an HTML Web page, Adding Text in New Line,
Creating Headings on a Web page, Creating a Paragraph, Creating a
Horizontal Ruler Line, Inserting the <pre> tag, Formatting Tags,
Aligning the Text, Grouping the Text, Indenting Quotations, Working
with Character Entities, Commenting the Text, Summary
Summary
1
UNIT 6 INTRODUCTION TO HTML5
Java Script Arrays, Java Script Functions, Java Script Popup Boxes,
Java Script Events, Summary
2
BLOCK 4: JAVA SCRIPT OBJECTS, JQUERY AND XML
Java Script Document Object, Java Script Array Object, Java Script
String Object, Java Script Date Object, Java Script Math Object, Java
Script Window Object, Summary
What is XML, XML Verses HTML, XML Syntax, XML References, XML
Declaration, XML Comments, XML Terminologies, XML Namespace,
Summary
3
Dr. Babasaheb BCAMI-103
Ambedkar Open
University
UNIT 1
INTRODUCTION TO WEB 10
UNIT 2
UNIT 3
WORKING WITH TEXT 43
UNIT 4
4
BLOCK 1: INTRODUCTION TO WEB AND
HTML
Block Introduction
I have also described, basic tags used to write a HTML document, and tags
used for text, use to create list, create tables and create frames.Basically, these
tags gives developer more flexibility to create document.
Block Objective
The objective of the block is to explain what is an web and what is HTML.
Students will able to learn about web and hyper text markup languagetocreate
web pages. Detail study of tags is required to build website.
By learning this block of web technology student will learn about different
tags of HTML, to createweb page. Reader of this block, will know web page
development through various tags.
5
Unit 1: Introduction to Web
Unit Structure
1.9. Summary
6
1.1 Introduction to WWW
The Web, or World Wide Web, is basically a system that support specially formatted
documents. The documents are formatted in a markup language called HTML
(HyperText Markup Language) that supports links to other documents, as well as
graphics, audio, and video files.
This means you can jump from one document to another simply by clicking.
There are several applications called Web browsers that make it easy to access the
World Wide Web.
In the beginning, World Wide Web was introduced as a medium for sharing scientific
and research documents, especially, between government organizations and
academic institutions.
It was created in 1989 by the UK physicist Tim Berners-Lee while working at the
European Particle Physics Laboratory called CERN(European Organization for
Nuclear Research) in Switzerland, as an easier way to accessinformation scattered
across the internet.
Evolution of web from Web 1.0 (The World Wide Web) to Web 2.0 (The Social Web)
and then to Web 3.0 (The Semantic Web) is shown in following figure 1.
7
Figure 1: showing the Evolution of Web page
• HTML: HyperText Markup Language. The markup (formatting) language for the
Web.
• URI: Uniform Resource Identifier. A kind of “address” that is unique and used to
identify to each resource on the Web. It is also commonly called a URL.
• HTTP: Hypertext Transfer Protocol. Allows for the retrieval of linked resources
from across the Web.
8
1.2 The Web System Architecture
HTTP stands for Hyper Text Transfer Protocol.The Hypertext Transfer Protocol
(HTTP) is an application-level protocol for distributed, collaborative, hypermedia
information systems. This is the foundation for data communication for the World
Wide Web (i.e. internet) since 1990. HTTP is a generic and stateless protocol which
can be used for other purposes as well using extensions of its request methods,
error codes, and headers.
Basic Features
9
There are three basic features that make HTTP a simple but powerful protocol:
• HTTP is connectionless: The HTTP client, i.e., a browser initiates an HTTP
request and after a request is made, the client waits for the response. The
server processes the request and sends a response back after which client
disconnect the connection. So client and server knows about each other
during current request and response only. Further requests are made on new
connection like client and server are new to each other.
• HTTP is media independent: It means, any type of data can be sent by
HTTP as long as both the client and the server know how to handle the data
content. It is required for the client as well as the server to specify the content
type using appropriate MIME-type.
• HTTP is stateless: As mentioned above, HTTP is connectionless and it is a
direct result of HTTP being a stateless protocol. The server and client are
aware of each other only during a current request. Afterwards, both of them
forget about each other. Due to this nature of the protocol, neither the client
nor the browser can retain information between different requests across the
web pages.
Basic Architecture
The following diagram shows a very basic architecture of a web application and
depicts where HTTP sits:
Figure 4 shows the HTTP Architecture
10
Client
The HTTP client sends a request to the server in the form of a request method, URI,
and protocol version, followed by a MIME-like message containing request
modifiers, client information, and possible body content over a TCP/IP connection.
Server
The HTTP server responds with a status line, including the message's protocol
version and a success or error code, followed by a MIME-like message containing
server information, entity meta information, and possible entity-body content.
Communication between client computers and web servers is done by
sending HTTP Requests and receiving HTTP Responses
A client that wants to access a web page needs the address. To facilitate the access
of documents distributed throughout the world HTTP uses locator.
DEFINATION
“The Uniform Resource Locator (URL) is a standard for specifying any kind of
information on the internet .the URL defines four things: protocol, host computer, port
and path”
11
The Protocol is the client/server program used to retrieve the document .many
different protocol can retrieve a document; among them FTP or HTTP .the most
common today is HTTP.
The Host is the computer on which the information is located, although the name of
the computer can be an alias .web pages are usually stored in computer and
computers are given alias names that usually begin with the character “WWW” .this
is not mandatory, however, as the host can be any name given to the computer that
hosts the web page.
The URL can optionally contain the port number of the server .if the port is included,
it is inserted between the host and the path, and it is separated from the host by a
colon.
The Path is the pathname of the file where the information is located. Note that the
path can itself contain slashes that, in the UNIX operating system .separate the
directories from subdirectories and files.
Domain Name
Domain Name System, a system for naming computers and network services that is
organized into a hierarchy of domains.It is used to locate computers and services
through user-friendly names.
Because domain names are alphabetic, they're easier to remember. The Internet
however, is really based on IP addresses. Every time you use a domain name,
therefore, a DNS service must translate the name into the corresponding IP address.
The domain name system (DNS) is the way that Internet domain names are located
and translated into Internet Protocol addresses. A domain name is a meaningful and
easy-to-remember "handle" for an Internet address.
The following figure shows a basic use of DNS, which is finding the IP address of a
computer based on its name.
12
Figure 6: showing How DNS Works
In this example, a client computer queries a DNS server, asking for the IP address of
a computer configured to use host-a.example.microsoft.com as its DNS domain
name.
Because the DNS server is able to answer the query based on its local database, it
replies with an answer containing the requested information, which is a host (A)
resource record that contains the IP address information for host-
a.example.microsoft.com.
1. Geographical
2. Non- Geographical
13
Every computer on network requires an IP address to communicate with other
computer.
Each computer on the Internet known as a host has at least one IP address that
uniquely identifies it from all other computers on the Internet.
When you send or receive data (for example, an e-mail note or a Web page), the
message gets divided into little chunks called packets.
The most widely used version of IP today is Internet Protocol Version 4 (IPv4).
However, IP Version 6 (IPv6)
The first part of an Internet address identifies the network on which the host resides,
while the second part identifies the particular host on the given network. This creates
the two-level addressing hierarchy.
All hosts on a given network share the same network prefix but must have a unique
host number. Similarly, any two hosts on different networks must have different
network prefixes but may have the same host number.
14
0 is reserved and represents all IP addresses;
Web browser, a browser is a software application used to locate, retrieve and display
content on the World Wide Web, including Web pages, images, video and other files.
Client/server model, the browser is the client run on a computer that contacts the
Web server and requests information. The Web server sends the information back to
the Web browser which displays the results on the computer or other Internet-
enabled device that supports a browser.
The first Web browser with a graphical user interface was Mosaic, which appeared in
1993.Common web browsers include Microsoft Internet Explorer, Google Chrome,
Mozilla Firefox, and Apple Safari.
A web page is a single hypertext document available on World Wide Web (WWW). It
is composed of HTML elements and displayed on the user's browser such
as Mozilla, Firefox, Chrome, etc. It is also referred to as "Page."
What is a Webpage?
A webpage is a document written in HTML and can be viewed on any web browser.
It is contained within the web server, which can be accessed by entering the URL for
that web page, and once it is loaded, it appears on the user's web browser. Each
webpage is linked with a unique URL; hence two pages cannot have the same URL.
A webpage may contain text, links for other pages, graphics, videos, etc.
Moreover, it is mainly used to provide information to the user in text, images, etc.
The WWW or Internet contains millions of web pages, and daily, a lot is being added.
Tim Berners-Lee developed the first webpage.
15
Following are some characteristics of a Web page:
o A web page and a website should be compatible with any device, such as
Mobile, Desktop, Laptop, etc.
o The search engine provides a web page through a link, and when a user
clicks on that link, it is redirected to the webpage of a website.
o A webpage can have any type of information including videos, and audios.
Website Webpage
A website is a collection of different web A webpage is a single hypertext
pages that are linked together with document.
hyperlinks.
It consists of more than one webpage. It is a single document that is displayed
on the user's browser.
To develop a website, developers need To develop a webpage, developers need
more skills and more time compared to a basic HTML knowledge and less time.
webpage.
A website is accessed through its domain A webpage is accessed through a unique
name, and it does not include any URL with some extension.
extension in the URL.
It can contain information for different It can contain information for a single
entities, such as Javatpoint.com, which entity, such as currently viewing a web
contains information about different page containing information about this
technologies. page only.
It is a little challenging to create a perfect It is very simple to create a webpage.
website and requires lots of
programming.
Some examples of the website are Some examples of Webpages are the
Myntra.com, Amazon.com, etc. currently viewing page, contact page,
registration page, the home page, etc.
16
A simple web page is created using HTML, which is a markup language. However,
we can also use CSS and JavaScript to add more functionalities and make it more
attractive.
It is created using HTML, hence containing different markup tags that specify how
the data should be formatted on screen.
The webpage is contained within the webserver. To load this webpage, a client
sends the request to the server, and generally, the browser is known as the client,
which can request the page on the internet.
The web browser requests the page on the internet. Once it is responded to by the
server, the browser interprets the markup tags and displays them on the user's
screen in the correct format.
The browser sends the request for a page or a file via an HTTP request. The HTTP
is the Hypertext Transfer Protocol, a network protocol that allows transferring
hypermedia documents over the internet between a browser and server.
Once the request reaches the server, the HTTP server accepts the request, finds the
requested page, and sends it back to the browser through the HTTP response. If a
server is unable to find the requested page, it returns a 404 response.
Types
17
Figure 8 shows How Static Web Page Works
18
1.8 Use of Cookies to Store Information
Cookies are text files with small pieces of data — like a username and password —
that are used to identify your computer as you use a computer network. Specific
cookies known as HTTP cookies are used to identify specific users and improve your
web browsing experience.
Data stored in a cookie is created by the server upon your connection. This data is
labeled with an ID unique to you and your computer.
When the cookie is exchanged between your computer and the network server, the
server reads the ID and knows what information to specifically serve to you.
HTTP cookies, or internet cookies, are built specifically for Internet web browsers to
track, personalize, and save information about each user’s session. A “session” just
refers to the time you spend on a site.
Cookies are created to identify you when you visit a new website. The web server —
which stores the website’s data — sends a short stream of identifying info to your
web browser.
Based on this, you’ll want to understand why they’re worth keeping — and when
they’re not.
1. Session management. For example, cookies let websites recognize users and
recall their individual login information and preferences, such as sports news versus
politics.
3. Tracking. Shopping sites use cookies to track items users previously viewed,
allowing the sites to suggest other goods they might like and keep items in shopping
carts while they continue shopping.
19
1.9 Summary
• WWW
• About HTTP
• Web Browsers
• Web Pages
20
Unit 2: Hypertext Markup Language
(HTML)
Unit Structure
2.8. Summary
21
H ypertext Markup Language(HTML) is the most commonly used markup
language for creating Web pages.HTML describes the structure of a Web
page.HTML is the combination of Hypertext and Markup language. Hypertext defines
the link between the web pages. A markup language is used to define the text
document within tag which defines the structure of web pages.
Hypertext is called ‘hyper’ because the navigation through the pages using the
hypertext is not linear.It means that if you click the hypertext present on a Web page,
the Web page you are redirected may be on a next page or any page on the same
website.World Wide Web Consortium (W3C) is an organization, which defines new
specifications for HTML and its responsible for updating the language.
HTML is markup language used to create Web pages, a Web page is a document
stored in the World Wide Web (WWW) or Web.Each HTML page contains the data to
be included in the page, between the HTML tags.A Web browser understands these
tags and displays the corresponding Web pages.
HTML allows you to format, arrange and group text, display text as link and add
images and multimedia to a Web page. It also allows you to create controls, create
and work with style sheets and embed scripting language code (such as JavaScript
code) into a Web page.
HTML was created by Tim Berners-Lee in 1991. The first-ever version of HTML was
HTML 1.0, but the first standard version was HTML 2.0, published in 1999.
22
Figure 1: showing HTML Versions
An HTML element is defined by a start tag, some content, and an end tag:
Tag Element
Note: Some HTML elements have no content (like the <br> element). These
elements are called empty elements. Empty elements do not have an end tag!
• The opening tag: This consists of the name of the element (in this
example, h1 for paragraph), wrapped in opening and closing angle brackets.
This opening tag marks where the element begins or starts to take effect.
• The content: This is the content of the element. In this example, it is the
heading text.
• The closing tag: This is the same as the opening tag, except that it includes a
forward slash before the element name. This marks where the element ends.
Failing to include a closing tag is a common beginner error that can produce
peculiar results.
ATTRIBUTE
An Attribute is a special word used inside tag to specify additional informationto tag
such as color, alignment etc.
23
Some examples of HTML tags with attributes are:
TAG ATTRIBUTE
Features of HTML
Advantages of HTML
Disadvantages of HTML
• HTML can only create static web pages. For dynamic web pages, other
languages have to be used.
• A large amount of code has to be written to create a simple web page.
• The security feature is not good.
HTML editor is software used for writing code in HTML,which is used for structuring
and creating websites.Essentially, a HTML editor either converts text and layout
interface input into actual HTML code, or allows users to scan HTML code to look for
appropriate syntax in design. The former type of editor can be called a WYSIWYG or
'what you see is what you get’ editor where the visual platform allows individuals to
effectively code in HTML, without knowing HTML.
24
There are two common forms of HTML editors: text and WYSIWYG (What You See
Is What You Get).
These are text-based editors where the developers can write their codes and
compile them. The code appears in the same manner we write it, thus it requires
basic knowledge of HTML.
Some of these editors also provide features of making a project, managing all the
files related to the web, etc. Examples of HTML Text editors include-Notepad++,
VSCode,Sublime Text.
’What you see is what you get’ is its full form. WYSIWYG are editors that provide the
preview of the output of the source code i.e. as it would appear on a browser. There
is a drag and drop feature available in most of them that eases the handling.
It does not require any hardcore knowledge of HTML, thus enabling non-technicals
to easily develop websites. Examples include-Adobe Dreamweaver, Microsoft
FrontPage etc.
25
• HEAD: This contains the information about the HTML document. For Example,
Title of the page, version of HTML, Meta Data etc.
• BODY: This contains everything you want to display on the Web Page.
The <html> element marks the beginning and the end of the HTML document. All
HTML content has to be within the start and end tag (<html>...</html>).
The <head> tag contains information about the document, including its title, and
documentdescription.The <head> element contains all the page information which
is not shown in the browser. For instance, the <title> elem ent, metatags and more
elements.
The <title> element contains the page title, which will be shown in the web
browsers title-bar. The title should match the content of the HTML page, meaning it
should tell what the page contains. The <title> element can be defined individually
for every single HTML page.
The <body> element contains the visible page content. It can contain text, images,
graphs, forms, tables etc.
26
2.4 Getting started with HTML
Before you create an HTML document, make sure that you have an editor, such as
Dreamweaver or Notepad and a Web browser, such as Internet Explorer, Firefox or
Google Chrome. The most common editor and the browser are Notepad and Internet
Explorer respectively.
27
An HTML document (file) is always saved with the .html or .htm extension.
A Web browser performs the function of reading HTML files and displaying them as
Web pages. The tags written inside an HTML file are used to interpret the content of
the Web page. The browser does not display the HTML tags.
Background of an HTML Web page can be modified in many ways, for example by
adding a background color to the Web page or by adding a background image to the
Web page
Table 1 lists color values for each of the W3C predefined colors.
28
navy #000080
fuchsia #ff00ff
purple #800080
indianred #cd5c5c
lightcoral #f08080
red #ff0000
Yellow #ffff00
HTML lets you specify metadata - additional important information about a document
in a variety of ways. It specifies page description, keywords, copyright, language,
author of the documents, etc.
The metadata does not display on the webpage, but it is used by search engines,
browsers and other web services which scan the site or webpage to know about the
webpage.
With the help of meta tag, you can experiment and preview that how your webpage
will render on the browser.
The <meta> tag is placed within the <head> tag, and it can be used more than one
times in a document.
You can add metadata to your web pages by placing <meta> tags inside the header
of the document which is represented by <head> and </head> tags. A meta tag can
have following attributes in addition to core attributes (Table 2)
29
Table 2 Attributes, value and Description of Meta tag
Attribute Value Description
charset character_set It specifies the character encoding of an
HTML page. You can set the value as
charset=”utf-8”
content text It contains the value of the attribute
"name" and "http-equiv" in an HTML
document, depending on context.
http-equiv It specifies the Information given by the
o Content-type
web server about how the web page
o default-style should be served.
o refresh
30
2.8 Summary
• Introduction to HTML
• HTML Editors
31
Unit 3: Working with Text
Unit Structure
3.13. Summary
32
H ypertext Markup Language (HTML) describes the structure of text-based
information on a Web page by marking the text as heading and
paragraphs.The basic text-fromatting tags in HTML are <br>, <p> and <hr>, which
are used to add text in a new line, create paragraphs, and insert horinzontal ruler,
respectively.HTML also provides tags to apply various styles to the text such as
<font>, <b, <i>, <strike>and <pre>.HTML provides elements such as subscript,
superscript and blockquote that can be used to enhance the look of the text on a
Web page.
Apart from this, characters such as graterer than(>) , less than(<) ,quotation mark(“)
etc., which are reserved characters in HTML , can be displayed on a Web page
using the character entities.In this chapter, you learn how to work with text in HTML.
Text can be added to an HTML document by typing between the <body> tags of
HTML document. If you enter plain text in an HTML document, the Web browser
displays the text in its default font, color and size.
HTML recognizes only single spaces between characters. This means if there are
more than single space spaces between characters, HTML does not recognize it.
Even if you type the text in a different line in Notepad, HTML considers it as a single
space and displays the text in the same line on the Web page.
When you're writing HTML, you often need to insert line breaks. A line break is
essential in addresses, poems, or when text exceeds the available browser width.
In HTML, the <br> tag is used for line break. It is an empty tag i.e. no need to add an
end tag. Writing <br> tag is perfectly fine. If you place the <br> tag in the HTML
code, then it works the same as pressing the enter key in a word processor.
33
3.3 Creating Headings ona Web page
A HTML heading can be defined as a title or a subtitle which you want to display on
the webpage. When you place the text within the heading tags, it is displayed on the
browser in the bold format and size of the text depends on the number of heading.
There are six different HTML headings which are defined with the <h1> to <h6> tags,
from highest level h1 (main heading) to the least level h6 (least important heading).
h1 is the largest heading tag and h6 is the smallest one.The heading tags are pairs
with an opening tag and a closing tag.
While displaying any heading, browser adds one line before and one line after
that heading.
HTML <hr> tag is used to draw a horizontal line. It is also called a Horizontal Rule in
HTML.
The HTML <pre> tag is used to specify pre formatted texts. Texts within
<pre>.......</pre> tag is displayed in a fixed-width font. Usually it is displayed in
Courier font. It maintains both space and line break.
It is widely used to display language examples e.g. Java, C#, C, C++ etc because it
displays the code as it is typed.
34
3.7 Formatting Tags
1. <b> Tag
HTML <b> tag is used to display the written text in bold format. It is strictly a
presentational element. If you want to show your text in bold letters and not have real
semantic meaning, then put it within <b>.......</b> tag.
2. <i> Tag
HTML <i> tag is used to represent a part of text in a different voice from the
surrounding text. The content within <i> tag usually renders in italic type on the
browser. It can be useful to represent some technical terms, phrase, fictional
character thoughts, etc.
3. <u> Tag
HTML <u> tag is used to define a span of inline text with a non-textual annotation. It
rendered as an solid underlined text,
4. <sup> Tag
HTML <sup> tag is termed as a superscript tag which is used to define superscript
text. The text within <sup> tag appears with an upper baseline and renders with
smaller font size than surrounding text.
The <sup> tag is useful for defining Mathematical formulas and footnotes.
5. <sub> Tag
HTML <sub> tag is termed as Subscript tag and which is used to define subscript
text. The text within <sub> renders with a lower baseline and with a smaller font than
surrounding text font.
The <sub> tag is useful for presenting mathematical formula and chemical formulas
such as H2O.
35
6. <big> Tag
HTML <big> tag was used to increase the text font size one level bigger than the
document's base font size or surrounding text size, such as small to medium,
medium to large, etc.
7. <small> Tag
HTML <small> tag makes text font by one size smaller than the document?s base
font size (Such as large to medium, medium to small, etc.)
8. <strike> Tag
HTML <strike> tag was used to strike a line through the text, contained within it.
9. <tt> Tag
HTML <tt> tag was used to define text in monospaced font or fixed-width fonts so
that it would render as teletype, text-only screen, or line printer on the browser.
The align Attribute in HTML is used to is used to specify the alignment of text
content of The Element. this attribute is is used in all elements.
Attribute Values:
36
3.9 Grouping The Text
In Html you can group several contents together to make sections or subsections in
a page. Grouping content makes it easier to manage the content. It is easier for both
the programmer and readers as it looks good while we group similar contents
together.
In Html the tags available for grouping contents are <div> and <span>
The contents before and after the Div element will be displayed in separate lines.
Span is an inline grouping element. The text written before and after the
<span>….</span>element all will be displayed in a single line.
HTML <blockquote> tag is used to define a block of text which is quoted from
another source. The Browser usually displays the content within <blockquote> tag as
indented text.
If you want to insert a long quote then use <blockquote> and for short or inline quote
use <q> tag.
Some characters are reserved in HTML and they have special meaning when used
in HTML document. For example, you cannot use the greater than and less than
signs or angle brackets within your HTML text because the browser will treat them
differently and will try to draw a meaning related to HTML tag.
37
HTML processors must support following five special characters listed in the table
that follows.
Comments are some text or code written in your code to give an explanation about
the code, and not visible to the user. Comments which are used for HTML file are
known as HTML comments. Anything written between these tags will be ignored by
the browser, so comments will not be visible on the webpage.
Comments of any code make code easy to understand and increase readability of
code.
3.13 Summary
• Creating a Paragraph
38
• Inserting the <pre> tag
• Formatting Tags
• Indenting Quotations
• Character Entities
39
Unit 4: Working with Lists, Tables, and
Frames
Unit Structure
4.4. Summary
40
4.1 Working with Lists
HTML offers web authors three ways for specifying lists of information. All lists must
contain one or more list elements. Lists may contain −
• <ul> − An unordered list. This will list items using plain bullets.
• <ol> − An ordered list. This will use different schemes of numbers to list
your items.
• <dl> − A definition list. This arranges your items in the same way as they
are arranged in a dictionary.
1. Open blank document in Notepad and add the code, given in listing 1, in the
document
<html>
<head>
</head>
<body>
<ul>
<li>Beetroot</li>
<li>Ginger</li>
41
<li>Potato</li>
<li>Radish</li>
</ul>
</body>
</html>
2. Save the document with appropriate name and .html extension. Here we have
named HTML document as unorderliist.html.
3. Open the HTML document in browser, as shown in figure 1
Attribute
1. Type
You can use type attribute for <ul> tag to specify the type of bullet you like. By
default, it is a disc. Following are the possible options −
42
2) HTML Ordered Lists
If you are required to put your items in a numbered list instead of bulleted, then
HTML ordered list will be used.
This list is created by using <ol> tag. The numbering starts at one and is
incremented by one for each successive ordered list element tagged with <li>.
1. Open blank document in Notepad and add the code, given in listing 5, in the
document
<html>
<head>
</head>
<body>
<ol>
<li>Beetroot</li>
<li>Ginger</li>
<li>Potato</li>
<li>Radish</li>
</ol>
</body>
</html>
2. Save the document with appropriate name and .html extension. Here we have
named HTML document as orderliist.html.
3. Open the HTML document in browser, as shown in figure 5
43
Figure 5: Displaying ordered list on web page
Attributes
1. Type
You can use type attribute for <ol> tag to specify the type of numbering you like. By
default, it is a number. Following are the possible options
<ol type = "1"> - Default-Case Numerals.
2. Start
You can use start attribute for <ol> tag to specify the starting point of numbering you
need. Following are the possible options −
<ol type = "1" start = "4"> - Numerals starts with 4.
44
<ol type = "a" start = "4"> - Letters starts with d.
3. Reversed
This is a Boolean attribute of HTML <ol> tag, and it is new in HTML5 version. If you
use the reversed attribute with tag then it will numbered the list in descending order
(7, 6, 5, 4......1).
The definition list is the ideal way to present a glossary, list of terms, or other
name/value list.
1. Open blank document in Notepad and add the code, given in listing 10, in the
document
<html>
<head>
</head>
<body>
<dl>
45
<dt><b>HTML</b></dt>
<dt><b>HTTP</b></dt>
</dl>
</body>
</html>
2. Save the document with appropriate name and .html extension. Here we have
named HTML document as Definition list.html.
3. Open the HTML document in browser, as shown in figure 10
4) Nested Lists
A nested list is a list inside another list. The following are different combination of
nested list
46
Now, let’s see all above combination of nested list with example..
Let’s perform steps to create Unordered List within Unordered List on HTML Web
page:
1. Open blank document in Notepad and add the code, given in listing 11, in the
document
Listing 11: Adding Unordered List within Unordered List to an HTML Web page
<html>
<head>
</head>
<body>
<li>HTML</li>
<li>CSS</li>
<li>JavaScript
<li>Angular</li>
<li>React</li>
<li>Vue</li>
</li>
</body>
</html>
47
2. Save the document with appropriate name and .html extension. Here we have
named HTML document as Unordered List within Unordered List.html.
3. Open the HTML document in browser, as shown in figure 11
Figure 11: Displaying Unordered List within Unordered List on web page
Let’s perform steps to create ordered List within ordered List on HTML Web page:
1. Open blank document in Notepad and add the code, given in listing 12, in the
document
Listing 12: Adding ordered List within ordered List to an HTML Web page
<html>
<body>
<h2>An Ordered List within Ordered List </h2>
<ol>
<li>Coffee</li>
<li>Tea
<ol>
<li>Black tea</li>
<li>Green tea</li>
48
</ol>
</li>
<li>Milk
<ol>
<li>Hot</li>
<li>Cold</li>
</ol>
</li>
</ol>
</body>
</html>
2. Save the document with appropriate name and .html extension. Here we have
named HTML document as ordered List within ordered List.html.
3. Open the HTML document in browser, as shown in figure 12
Figure 12: Displaying ordered List within ordered List on web page
Let’s perform steps to create Unordered List within ordered List on HTML Web page:
49
1. Open blank document in Notepad and add the code, given in listing 13, in the
document
Listing 13: Adding Unordered List within ordered List to an HTML Web page
<html>
<body>
<ol>
<li>Coffee</li>
<li>Tea
<ul>
<li>Black tea</li>
<li>Green tea</li>
</ul>
</li>
<li>Milk</li>
</ol>
</body>
</html>
2. Save the document with appropriate name and .html extension. Here we have
named HTML document as Unordered List within ordered List.html.
3. Open the HTML document in browser, as shown in figure 13
50
Figure 13: Displaying Unordered List within ordered List on web page
Let’s perform steps to create ordered List within Unordered List on HTML Web page:
1. Open blank document in Notepad and add the code, given in listing 14, in the
document
Listing 14: Adding ordered List within Unordered List to an HTML Web page
<html>
<body>
<ul>
<li>Coffee</li>
<li>Tea
<ol>
<li>Black tea</li>
<li>Green tea</li>
</ol>
</li>
<li>Milk</li>
</ul>
</body>
</html>
2. Save the document with appropriate name and .html extension. Here we have
named HTML document as ordered List within Unordered List.html.
3. Open the HTML document in browser, as shown in figure 14
51
Figure 14: Displaying ordered List within Unordered List on web page
The HTML tables are created using the <table> tag in which the <tr> tag is used to
create table rows and <td> tag is used to create data cells. The elements under
<td> are regular and left aligned by default
1. Open blank document in Notepad and add the code, given in listing 15, in the
document
<html>
<head>
<title>HTML Tables</title>
</head>
<body>
52
<tr>
</tr>
<tr>
</tr>
</table>
</body>
</html>
2. Save the document with appropriate name and .html extension. Here we have
named HTML document as Table.html.
3. Open the HTML document in browser, as shown in figure 15
53
Table Heading
Table heading can be defined using <th> tag. This tag will be put to replace <td>
tag, which is used to represent actual data cell. Headings, which are defined in <th>
tag are centered and bold by default.
Attributes
1. Cellpadding and Cellspacing
There are two attributes called cellpadding and cellspacing which you will use to
adjust the white space in your table cells. The cellspacing attribute defines
space between table cells, while cellpadding represents the distance between
cell borders and the content within a cell.
2. Colspan and Rowspan
You will use colspan attribute if you want to merge two or more columns into a single
column. Similar way you will use rowspan if you want to merge two or more rows.
3. Table Backgrounds
You can set table background using one of the following two ways −
• bgcolor attribute − You can set background color for whole table or just for
one cell.
• background attribute − You can set background image for whole table or
just for one cell.
You can also set border color also using bordercolor attribute.
You can set a table width and height using width and height attributes. You can
specify table width or height in terms of pixels or in terms of percentage of available
screen area.
54
Table Caption
The caption tag will serve as a title or explanation for the table and it shows up at
the top of the table.
Nested Tables
You can use one table inside another table. Not only tables you can use almost all
the tags inside table data tag <td>.
Let’s perform steps to create Nested Table on HTML Web page:
1. Open blank document in Notepad and add the code, given in listing 23, in the
document
<html>
<head>
<title>HTML Table</title>
</head>
<body>
<tr>
<td>
<tr>
<th>Name</th>
<th>Salary</th>
</tr>
<tr>
<td>Ramesh Raman</td>
<td>5000</td>
55
</tr>
<tr>
<td>Shabbir Hussein</td>
<td>7000</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>
2. Save the document with appropriate name and .html extension. Here we have
named HTML document as Nested_Table.html.
3. Open the HTML document in browser, as shown in figure 23
56
4.3 Working with Frames
HTML frames are used to divide your browser window into multiple sections where
each section can load a separate HTML document.
Creating Frames
To use frames on a page we use <frameset> tag instead of <body> tag. The
<frameset> tag defines, how to divide the window into frames.
The rows attribute of <frameset> tag defines horizontal frames and cols attribute
defines vertical frames.
Each frame is indicated by <frame> tag and it defines which HTML document shall
open into the frame.
To create a set of four vertical columns, we need to use the frameset element with
the cols attribute.
The cols attribute is used to define the number and size of columns the frameset will
contain.
In our case, we have four files to display, so we need four frames. To create four
frames we need to assign four comma-separated values to the cols attribute.
To make things simple we’re going to assign the value * to each of the frames, this
will cause them to be automatically sized to fill the available space.
Let’s perform steps to create Frame with Vertical Columns on HTML Web page:
1. Open blank document in Notepad and add the code, given in listing 24, in the
document
Listing 24: Adding Frame with Vertical Columnsto an HTML Web page
<html>
<frameset cols="*,*,*,*">
57
<frame src="frame1.html">
<frame src="frame2.html">
<frame src="frame3.html">
<frame src="frame4.html">
</frameset>
</html>
2. Save the document with appropriate name and .html extension. Here we have
named HTML document as Frame_verticalcolumns.html.
3. Open the HTML document in browser, as shown in figure 24
Rows of frames can be created by using the rows attribute rather than
the cols attribute as shown in the HTML below.
Let’s perform steps to create Frame with Horizontal Rows on HTML Web page:
1. Open blank document in Notepad and add the code, given in listing 25, in the
document
Listing 25: Adding Frame with Horizontal Rows to an HTML Web page
58
<html>
<frameset rows="*,*,*,*">
<frame src="frame1.html">
<frame src="frame2.html">
<frame src="frame3.html">
<frame src="frame4.html">
</frameset>
</html>
2. Save the document with appropriate name and .html extension. Here we have
named HTML document as Frame_Horizontal Rows.html.
3. Open the HTML document in browser, as shown in figure 24
To do this, we first create a frameset and then nest a child frameset within the parent
element.
59
Let’s perform steps to create Frame with nesting rows and columns on HTML Web
page:
1. Open blank document in Notepad and add the code, given in listing 26, in the
document
Listing 26: Adding Frame with nesting rows and columns to an HTML Web page
<frameset cols="*,*,*">
<frameset rows="*,*">
<frame src="frame1.html">
<frame src="frame2.html">
</frameset>
<frame src="frame3.html">
<frame src="frame4.html">
</frameset>
2. Save the document with appropriate name and .html extension. Here we have
named HTML document as Frame_nesting rows and columns.html.
3. Open the HTML document in browser, as shown in figure 26
Figure 26: Displaying Frame with nesting rows and columnson web page
The nested frameset takes the place of the first frame within the parent element. The
nested element can be placed in any position.
If we wanted the nested element to appear in the center position we would just
rearrange the elements.
60
One more way to create a combination of rows and columns is to define a grid of
columns and rows in a single frameset.
4.4 Summary
61
Dr. Babasaheb BCAMI-103
Ambedkar Open
University
CHAP 5
CHAP 6
CHAP 7
62
BLOCK 2: ADVANCED HTML AND HTML5
Block Introduction
Block Objective
By learning this block of web technology student will learn about more
tags of HTML, to create eye-caching web page. Reader of this block, will know
web page development through various tags and add some new tags of HTML5.
Different tags are used to create web pages which include multiple tags.
This block servers knowledge of different tags. I hope, this block will clear the
idea of more tags of HTML and new version of HTML.
63
Unit 5: Working with Hyperlinks,
Images, Multimedia and Forms
Unit Structure
5.6. Summary
64
5.1 Working with Hyperlinks
1. External link
Linking Documents
The tags used to produce links are the <a> and </a>. The <a> tells where the link
should start and the </a> indicates where the link ends.
Use mailto: inside the href attribute to create a link that opens the user's email
program (to let them send a new email):
A local link (a link to a page within the same website) is specified with a relative
URL (without the "https://www" part):
Attributes
1. target
By default, the linked page will be displayed in the current browser window. To
change this, you must specify another target for the link.
65
The target attribute can have one of the following values:
• _self - Default. Opens the document in the same window/tab as it was clicked
• _blank - Opens the document in a new window or tab
• _parent - Opens the document in the parent frame
• _top - Opens the document in the full body of the window
The general color of text links is specified in the <body> tag, like in the example
below:
• link - standard link - to a page the visitor hasn't been to yet. (Standard color is
blue).
• vlink - visited link - to a page the visitor has been to before. (Standard color is
purple).
• alink - active link - the color of the link when the mouse is on it. (Standard color is
red ).
3. Internal link
First create a link to the place where you want to reach with-in a webpage and
name it using <a...> tag as follows −
Second step is to create a hyperlink to link the document and place where you want
to reach −
66
Let’s perform steps to create Internal Link on HTML Web page:
1. Open blank document in Notepad and add the code, given in listing 5, in the
document
<html>
<head>
<title>links</title>
</head>
<body>
<a name="top">
<h2>this is top of the page</h2>
<h1>linking to a section in a page</h1>
<br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br>
<hr>
<a name="bottom">
<a href="#top">top</a>
<h3>this is a bottom of the page</h3>
</a>
</body>
</html>
2. Save the document with appropriate name and .html extension. Here we have
named HTML document as Internal_Link.html.
67
3. Open the HTML document in browser, as shown in figure 5
The <img> tag is used to insert images in the HTML documents. It is an empty
element and contains attributes only.
1. Open blank document in Notepad and add the code, given in listing 6, in the
document
<html>
<head>
<title>Using Image in Webpage</title>
</head>
<body>
68
<p>Simple Image Insert</p>
<img src = "computer.jpg" />
</body>
</html>
2. Save the document with appropriate name and .html extension. Here we have
named HTML document as image.html.
3. Open the HTML document in browser, as shown in figure 6
Attributes
Sometimes an inserted image does not appear in web browser because of incorrect
path or file name. In this case you can specify the alternate text for an image.
The basic purpose of alternate text is to provide a short description about an image
so that user can get idea of what the image is all about.
You can set image width and height based on your requirement using width
and height attributes. You can specify width and height of the image in terms of
either pixels or percentage of its actual size.
69
3. Image Border
By default, image will have a border around it, you can specify border thickness in
terms of pixels using border attribute. A thickness of 0 means,no border around the
picture.
4. Alignment
By default, image will align at the left side of the page, but you can use align
attribute to set it in the center or right.
It's simple to use an image as hyperlink. We just need to use an image inside
hyperlink at the place of text
1. Open blank document in Notepad and add the code, given in listing 11, in the
document
<html>
<head>
</head>
<body>
</a>
</body>
70
</html>
2. Save the document with appropriate name and .html extension. Here we have
named HTML document as imageaslink.html.
3. Open the HTML document in browser, as shown in figure 11
Image map is a technique that divides the image into multiple sections and allows
linking of each section to different web pages.
Linked regions of an image map are called hot regions. Each hot regions are
associated with an HTML file.
71
Add the Map
Use the HTML <map> tag to create a map with a name. Inside <map>tag, you will
specify where the clickable areas are with the HTML <area>tag.
We use the <area> tag in conjunction with the shape and coords attributes. These
accept the following attributes:
• default
• rect
• circle
• polygon
rect
left, top, right, bottom
circle
center-x, center-y, radius
polygon
x1, y1, x2, y2, ...
1. Open blank document in Notepad and add the code, given in listing 12, in the
document
<html>
<body>
<img src="computer.jpg" width="145" height="126" alt="Planets"
usemap="#cmap">
<map name="cmap">
<area shape="rect" coords="17,52,41,155" href="order.html">
<area shape="circle" coords="115,20,70" href="unorder.html">
72
<area shape="polygon" coords="37,80,160,140,132,140" href="nestedlist.html">
</map>
</body>
</html>
2. Save the document with appropriate name and .html extension. Here we have
named HTML document as imagemap.html.
3. Open the HTML document in browser to view output.
1. <audio> tag
The <audio> tag is an inline element used to embed sound files into a web page. It is
useful when you want to add any audio, such as a song or interview, to your web
pages.
73
none autoplay attribute can override this attribute,
because if you want to automatically play a audio,
the browser will obviously need to download it.
src URL Specifies the location of the audio file.
2. <video> Tag
The <video> element is used to embed video content in an HTML document without
requiring any additional plugin like Flash player. Support for the <video> element
varies accross browsers.
The following table shows the attributes that are specific to the <video> tag.
74
metadata to download of the video itself or its metadata.
none
src URL Specifies the location of the video file to
embed. Alternatively, you can use the
preferred <source> tag as it allows for
multiple options.
width pixels Sets the width of the video's display area.
3. <source> Tag
The HTML <source> tag is used to specify multiple media resources on media
elements (such as <audio> and <video>).
Attributes
➢ The following table shows the attributes that are specific to this tag/element.
Attribute Description
src Specifies the location of the audio/video file. Its value must be the URL
of an audio/video file.
type Specifies the type of the embedded content. If specified, the value
must be a MIME type.
media Specifies the type of media resource, so the browser can determine
whether it can play it or not. If not, it can choose not to download it. If
specified, the value must be a valid media query.
4. <embed> Tag
The easiest way to add video or sound to your web site is to include the special
HTML tag called <embed>. This tag causes the browser itself to include controls for
the multimedia automatically provided browser supports <embed> tag and given
media type.
Attributes
75
The following table shows the attributes that are specific to this tag/element.
You can also include a <noembed> tag for the browsers which don't recognize the
<embed> tag.
5. <object> Tag
The HTML <object> tag is used for embedding an object within an HTML document.
Use this tag to embed multimedia and other files in your web pages
Attributes
Attribute Description
data Specifies the location of data to be used
by the object. The value must be a valid
URL.
type Specifies the object type as specified in
the data attribute. Must be a valid MIME
76
type.
name Assigns the name of the object.
width Specifies the width, in pixels, to display the
external content.
height Specifies the height, in pixels, to display
the external content.
Possible values:
The HTML <form> element provides a document section to take input from user.
It provides various interactive controls for submitting information to web server such
as text field, text area, password field, etc.
Users generally complete a form by modifying its controls e.g. entering text, selecting
items, etc. and submitting this form to a web server for further processing.
Attributes
Attribute Description
name Assigns a name to the form. This is used when
referencing the form with stylesheets or scripts. If there
are multiple forms, the name of each form must be
unique.
method Specifies the HTTP method to use when the form is
submitted.
Possible values:
77
automatically completed based on the user's history
(i.e. based on previous forms that the user has
completed)
action Specifies a URI/URL of the page that will process the
form.i.e defines where to send data after submitting
form.
<form >
//input controls e.g. textfield, textarea, radiobutton, button
</form>
Tag Description
<form> It defines an HTML form to enter inputs
by the used side.
<input> It defines an input control.
<textarea> It defines a multi-line input control.
<label> It defines a label for an input element.
<fieldset> It groups the related element in a form.
<legend> It defines a caption for a <fieldset>
element.
<select> It defines a drop-down list.
<optgroup> It defines a group of related options in a
drop-down list.
<option> It defines an option in a drop-down list.
<button> It defines a clickable button.
78
<input> element
The HTML <input> element is fundamental form element. It is used to create form
fields, to take input from user. We can apply different input filed to gather different
information form user. Following is the example to show the simple text input.
• TextField Control
The type="text" attribute of input tag creates textfield control also known as single
line textfield control. The name attribute is optional.
Example
<form>
</form>
Example
<form>
Password: <input type="password" id="password" name="password"/> <br/>
</form>
The email field in new in HTML 5. It validates the text for correct email address. You
must use @ and . in this field.
Example
<form>
<label for="email">Email: </label>
<input type="email" id="email" name="email"/> <br/>
</form>
The radio button is used to select one option from multiple options. It is used for
selection of gender, quiz questions etc.
79
If you use one name for all the radio buttons, only one radio button can be selected
at a time.
Using radio buttons for multiple options, you can only choose a single option at a
time.
Example
<form>
<label for="gender">Gender: </label>
<input type="radio" id="gender" name="gender" value="male"/>Male
• Checkbox Control
The checkbox control is used to check multiple options from given checkboxes.
Example
<form>
Hobby:
<input type="checkbox" id="cricket" name="cricket" value="cricket"/>
Cricket
<input type="checkbox" id="football" name="football" value="football"/>
Football:
<input type="checkbox" id="hockey" name="hockey" value="hockey"/>
Hockey:
</form>
The <textarea> tag in HTML is used to insert multiple-line text in a form. The size of
<textarea> can be specify either using "rows" or "cols" attribute
Example
<form>
</form>
80
• Adding Button
Example
<form>
</form>
HTML <input type="submit"> are used to add a submit button on web page. When
user clicks on submit button, then form get submit to the server.
Example
<form>
Enter name
<input type="text" id="name" name="name"><br>
Enter Password
<input type="Password" id="pass" name="pass"><br>
<input type="submit" value="submit">
</form>
You can add graphics to your regular submit button. This implies that you can define
an image to act as a button on form.
Example
<form>
Enter name
Enter Password
81
<input type="image" src="submit.jpg" width="100" height="30">
</form>
Example
<form>
Enter name
Enter Password
</form>
Example
<form>
</form>
➢ The URL field is used to enter only web addresses, in the correct format.If the
URL is not entered in the correct format then URL field validates it.
Attribute
82
Autofocus: helps in keeping the focus of mouse pointer on the input field
Example
<form>
Enter URL
</form>
You can use <input type="tel"> to provide a telephone number in the field.
Example
<form>
Telephone
</form>
In HTML5 we can easily select date and time from a date picker control using various
input type values of date
Example
<form>
83
date and time:
date:
time:
week:
month:
</form>
HTML5 contains a number type attribute of input field.This type is used to validate
the textbox only if the value within the field is a numerical value.
Example
<form>
number:
</form>
84
In HTML 5 the range of values by using the type of the input field. you can use the
<input type=”range”> tag, which is used to specify the range values.
Example
<form>
number:
</form>
The <input type=”color”> tag is used to select a color from a color picker control.
Example
<form>
color:
<input type="color"><br/>
</form>
HTML <select> tag is used to create a drop down list with multiple options. The
<option> element is nested within <select> tag for defining options in a list.
The <optgroup> element can be used for grouping related options in a list.
Syntax
<select>
<option></option>
</select>
Attributes
85
load.
disabled disabled It is used to disable the control and
user cannot interact with the drop-
down list.
multiple multiple If it sets then a user can select
multiple options from the list.
name name It determines the name for the drop-
down list.
required required If it specified, user must select that
field before submitting the form.
size number It specifies the visible number of
options in the list.
Example
<form>
City:
<option value="sydney">Sydney</option>
<option value="melbourne">Melbourne</option>
<option value="India">India</option>
<option value="canada">canada</option>
</select>
</form>
HTML <fieldset> tag is used to group the logically related fields/labels contained
within an HTML form.
The use of this tag is optional while creating an HTML form but using <fieldset>, it is
easy to understand the purpose of grouped elements of form.
The <legend> tag is used with the <fieldset> element as a first child to define the
caption for the grouped related fields.
86
Syntax
<fieldset>.....</fieldset>
5.6 Summary
87
Unit 6: Introduction to HTML5
Unit Structure
6.5. Summary
88
6.1 Introduction to HTML5
HTML5 is the fifth revision and newest version of the HTML standard. It offers new
features that provide not only rich media support but also enhance support for
creating web applications that can interact with users, their local data, and servers
more easily and effectively than was previously possible.
It has improved the markup available for documents and has introduced application
programming interfaces(API) and Document Object Model(DOM).
Features:
• It has introduced new multimedia features which supports audio and video
controls by using <audio> and <video> tags.
• There are new graphics elements including vector graphics and tags.
• Enrich semantic content by including <header><footer>, <article>, <section>
and <figure> are added.
• Drag and Drop- The user can grab an object and drag it further dropping it on
a new location.
• Geo-location services- It helps to locate the geographical location of a client.
• Web storage facility which provides web application methods to store data on
web browser.
• Uses SQL database to store data offline.
• Allows to draw various shapes like triangle, rectangle, circle, etc.
• Capable of handling incorrect syntax.
• Easy DOCTYPE declaration i.e. <!doctype html>
• Easy character encoding i.e. <meta charset=”UTF-8″>
89
1. <header>
The header element is used to contain the content that appears at the top of every
page of your website: the logo, tagline, search prompt, and possibly a navigational
menu.
2. <nav>
The <nav> element is used to declaring the navigational section in HTML
documents. Websites typically have sections dedicated to navigational links, which
enables user to navigate the site. These links can be placed inside a nav tag.
3. <section>
It defines different sections of webpage.
The section element is used to identify content that is a major sub-section of a larger
whole.
Example
<section>
<h1>Header</h1>
</section>
<section>
<h1>Header 2</h1>
</section>
4. <article>
Example
<article>
</article>
5. <aside>
90
If your website contains information that isn't directly related to the main content of
the page, it would be appropriate to wrap that information in aside tags.
Some possible uses for aside include a sidebar, a secondary list of links, or a block
of advertising.
6. <footer>
The most common use of the footer element is to place it at the bottom of an HTML
document to contain things like a copyright notice, links to related
content, address information about the owner of the website, and links to
administrative things like privacy policies and website's terms of service.
The major browsers are google chrome, opera, Mozilla firefox, apple’s safari and
intrenet explorer 8.
A basic HTML page always starts with the Document Type Declaration or doctype.
That is a way to tell the browsers what type of document it is.
The doctype is always the first thing at the top of any HTML file. Then sections and
subsections come, each possibly has its heading and subheading. These heading
and sectioning elements helps the reader to perceive the content meaning.
<!DOCTYPE html>
1. Open blank document in Notepad and add the code, given in listing 1, in the
document
91
<!DOCTYPE HTML>
<html>
<head>
<article>
<header>
<h2>Learn HTML</h2>
</header>
<p>Our free HTML tutorial for beginners will teach you HTML and how to create your
website from the scratch. HTML isn't difficult, so hoping you will enjoy learning.</p>
</article>
<article>
<header>
</header>
<p>You will get 5% for each correct answer for single choice questions. In multiple
choice question it might be up to 5%. At the end of the Quiz, your total score will be
displayed. Maximum score is 100%.</p>
</article>
</section>
<aside>
<h2>Our Books</h2>
<p>HTML</p>
<p>CSS</p>
<p>JavaScript</p>
<p>PHP</p>
</aside>
92
<footer>
</footer>
</body>
</html>
The <html> element follows the doctype information, which is used to inform the
browser that this is an HTML document.
Attributes
Attribute Description
class The class attribute is used to associate an element with a style sheet, and
specifies the class of element. Used in CSS.
The value of the attribute may also be a space-separated list of class
names. For example −
class = "className1 className2 className3"
93
dir The dir attribute allows you to indicate to the browser about the direction
in which the text should flow. The dir attribute can take one of two values
ltr Left to right (the default value)
lang The lang attribute allows you to indicate the main language used in a
document, but this attribute was kept in HTML only for backwards
compatibility with earlier versions of HTML.
id The id attribute of an HTML tag can be used to uniquely identify any
element within an HTML page.
If you have two elements of the same name within a Web page (or style
sheet), you can use the id attribute to distinguish between elements that
have the same name.
Example
<p id = "html">This para explains what is HTML</p>
manifest The manifest attribute gives the address of the document's application
cache manifest, if there is one.
It only has an effect during the early stages of document load. is part of
the legacy "offline Web applications" feature, which is in the process of
being removed from the Web platform.
Version It refer to the version of the HTML page
<header>
<nav>
<section>
<article>
<aside>
<footer>
The <head> element contains metadata (document title, character set, styles, links,
scripts), specific information about the web page that is not displayed to the user.
94
Attributes
Attribute Description
class The class attribute is used to associate an element with a style sheet, and
specifies the class of element. Used in CSS.
The value of the attribute may also be a space-separated list of class
names. For example −
class = "className1 className2 className3"
dir The dir attribute allows you to indicate to the browser about the direction
in which the text should flow. The dir attribute can take one of two values
ltr Left to right (the default value)
lang The lang attribute allows you to indicate the main language used in a
document, but this attribute was kept in HTML only for backwards
compatibility with earlier versions of HTML.
id The id attribute of an HTML tag can be used to uniquely identify any
element within an HTML page.
If you have two elements of the same name within a Web page (or style
sheet), you can use the id attribute to distinguish between elements that
have the same name.
Example
<p id = "html">This para explains what is HTML</p>
style The style attribute allows you to specify Cascading Style Sheet (CSS)
rules within the element.
title Holds additional information for the element.
<title>
<style>
<script>
<link>
The HTML <title> tag is used for declaring the title, or name, of the HTML document.
95
The title is usually displayed in the browser's title bar (at the top).
Attributes
Attribute Description
class The class attribute is used to associate an element with a style sheet, and
specifies the class of element. Used in CSS.
The value of the attribute may also be a space-separated list of class
names. For example −
class = "className1 className2 className3"
lang The lang attribute allows you to indicate the main language used in a
document, but this attribute was kept in HTML only for backwards
compatibility with earlier versions of HTML.
id The id attribute of an HTML tag can be used to uniquely identify any
element within an HTML page.
If you have two elements of the same name within a Web page (or style
sheet), you can use the id attribute to distinguish between elements that
have the same name.
Example
<p id = "html">This para explains what is HTML</p>
style The style attribute allows you to specify Cascading Style Sheet (CSS)
rules within the element.
The HTML <body> tag is used for indicating the main content section of the HTML
document. The body tag is placed between the </head> and the </html> tags.
Attributes
Attribute Description
class The class attribute is used to associate an element with a style sheet, and
specifies the class of element. Used in CSS.
The value of the attribute may also be a space-separated list of class
names. For example −
class = "className1 className2 className3"
lang The lang attribute allows you to indicate the main language used in a
document, but this attribute was kept in HTML only for backwards
compatibility with earlier versions of HTML.
96
id The id attribute of an HTML tag can be used to uniquely identify any
element within an HTML page.
If you have two elements of the same name within a Web page (or style
sheet), you can use the id attribute to distinguish between elements that
have the same name.
Example
<p id = "html">This para explains what is HTML</p>
style The style attribute allows you to specify Cascading Style Sheet (CSS)
rules within the element.
title Holds additional information for the element.
6.5 Summary
• Introduction to HTML5
97
Unit 7: Introduction to New Elements
in HTML5
Unit Structure
7.4. Summary
98
7.1 Markup Elements HTML5
Element Description
<article> The <article> tag is used to represent an article. Helps in
adding content on a webpage which can be Block, inline,
and text
<aside> Helps in adding extra information such as note, tip etc.
The details element is used to represent an area where
<details>
users can go to obtain additional information.
<summary> The <summary> tag in HTML is used to define a summary
or title for the <details> element.
<figure> The <figure> tag in HTML is used to add content like
illustrations, diagrams, photos in a document.
<figcaption> The <figurecaption> tag in HTML is used to set a caption to
the<figure >element
<header> The header element typically contains the headings for a
section. A header should contain title and heading
information about the related content.
99
document.
This element normally used to indicate how much of a task
<progress>
has been completed, such as loading something on a page
or registration process. It is typically displayed as a
progress bar and often marked as a percentage from 0 to
100%.
The <ruby> element represents a ruby annotation. Ruby
<ruby>
annotations are used for showing pronounciation of East
Asian characters, like Chinese and Japanese Chinese.
element is used within a <ruby> to define the pronunciation
<rt>
of character presented in a ruby annotations. Used to
create annotations or pronunciation guides for words and
phrases.
element is used to provide fall-back parenthesis for
<rp>
browsers that that don't support ruby annotations.
The <section> element defines a section of a document,
<section>
such as header, footer etc.
The <time> element represents a time and/or date.
<time>
The HTML5 canvas element can be used to draw graphics on the webpage via
scripting usually JavaScript.
The <canvas> element is only a container for graphics, you must need a scripting
language to draw the graphics. The <canvas> element allows for dynamic and
scriptable rendering of 2D shapes and bitmap images.
100
<canvas id = "mycanvas" width ="200" height ="100">
</canvas>
By default the canvas element has 300px of width and 150px of height without any
border and content. However the custom width and height can be defined.
The canvas element has a DOM method called getContext, used to obtain the
rendering context and its drawing functions. This function takes one parameter, the
type of context2d.
Example
1. The parameters (0,0,200,100) is used for fillRect() method. This parameter will fill
the rectangle start with the upper-left corner (0,0) and draw a 200 * 100
rectangle.
If you want to draw a straight line on the canvas, you can use the following two
methods.
Tag Description
<datalist> It specifies a list of pre-defined options for input
control.
<keygen> It defines a key-pair generator field for forms.
<output> It defines the result of a calculation.
101
1. <datalist> element
The HTML <datalist> tag is is used to provide an auto complete feature on form
element. It provides a list of predefined options to the users to select data.
The datalist tag is introduced in HTML5.The <datalist> tag should be used with an
<input>element that contains a "list" attribute. The value of "list" attribute is linked
with the datalist id.
2. <output> element
HTML <output> tag is used to display the result of some calculation (performed by
JavaScript) or the outcome of a user action (such as Input data into a form element).
The <output> tag is a newly added tag and was introduced in HTML5.
Syntax
<output>......</output>
3. <keygen> element
The KEYGEN Element is commonly used for generating the key pair in the form.
Whenever user hit the submit button, the KEYGEN Element creates two key pair,
first one is Public Key and another one is Private Key.
The private key is encrypted and stored in the local key database and the public key
is sent with the form data to the server. The KEYGEN Element is most useful when
the user wants to generate the unique key for a particular form.
7.4 Summary
102
Dr. Babasaheb BCAMI-103
Ambedkar Open
University
CHAP 8
CHAP 9
CHAP 10
CHAP 11
103
BLOCK 3: DYNAMIC HTML CONCEPTS
(CSS, JAVA SCRIPT)
Block Introduction
Block Objective
By learning this block of web technology student will learn about adding
dynamic concepts to web page and make web page more interactive and
attractive. Reader of this block, will know web page development through various
attributes of CSS and various syntax of Java script.
104
Unit 8: Cascading Style Sheet
Unit Structure
8.7. Summary
105
8.1 Introduction to Cascading Style Sheet
Concept of CSS
Cascading style sheets are used to format the layout of Web pages. CSS enforce
standards and uniformity throughout a web site and provide numerous attributes to
create dynamic effects.
They can be used to define (fonts, colors, background, borders, text formatting, link
effects & so on…).These aspects of Web pages that previously could only be
defined in a page's HTML.
Instead of defining the style of each table and each block of text within a page's
HTML, commonly used styles need to be defined only once in a CSS document.
Once the style is defined in cascading style sheet, it can be used by any page that
references the CSS file. Plus, CSS makes it easy to change styles across several
pages at once.
For example, a Web developer may want to increase the default text size from 10pt
to 12pt for fifty pages of a Web site. If the pages all reference the same style sheet,
the text size only needs to be changed on the style sheet and all the pages will show
the larger text.
Advantages CSS
CSS makes it very easy to change the style of a document. Let's say we wanted to
move the picture in the title of this page to the right by 10 pixels.
We have to do is open our CSS file which stores the layout of the site, and change
the number relating to the position of the image. That will change his position
throughout the whole site.
The look and layout of a site can be changed beyond recognition just by altering the
CSS file. This makes CSS indispensable for large web sites.
File Size
Probably the mostly useful feature of CSS is that all of the style and layout is
removed from the html, so the html page size is very much smaller.
106
The CSS file is downloaded just once by the visitor's browser and re-used for
different pages on a web site. This reduces the bandwidth requirements for your
server and also ensures a faster download for your visitors.
Search Engines
A search engine normally considers the text at the start of your html page as more
important than the text towards the end of the code.
CSS-based websites use simpler and better structured markup (HTML) and are
therefore more accessible to search engines.
Accessibility
Separating style from content makes life very easy for visitors who prefer to view
only the content of a web page, or to modify the content. These could be blind or
partially sighted people who might use a screen reader to interpret a page.
Consistency
Layout and position of navigation can be completely consistent across a site. This
was previously possible only using frames.
By using CSS for your website's layout, you will see significant improvements in your
web page download times. With CSS you will achieve faster download speeds.
Search engines like CSS-based websites and are likely to place them higher in
search engine rankings because:
By using CSS for style and layout, you only have to adjust one style sheet to make
adjustments right across your website. Table-based layouts require each web page
to be adjusted. So CSS is less time-consuming. Imagine if you had a 100 page
website. It would take a long time to adjust if it used tables, but would take no time at
all using CSS.
107
Web page print friendly
When a user wishes to print a web page an alternative CSS document can be called
up. This document can specify that only the content and logo are to appear on the
print out, with the navigation and formatting made to disappear.
Disadvantages CSS
Browser compatibility
Different browsers will render CSS layout differently as a result of browser bug or
lack of support for CSS features.
CSS renders different dimensions with each browser. Programmers are required to
consider and test all code across multiple browsers for compatibility before taking
any website
Lack of Variables
CSS contain no variables. This makes it necessary to do a "replace-all" when one
desires to change a fundamental constant, such as color scheme or various heights
and widths.
A CSS comprises of style rules that are interpreted by the browser and then applied
to the corresponding elements in your document. A style rule is made of three parts
• Selector − A selector is an HTML tag at which a style will be applied. This could
be any tag like <h1> or <table> etc.
• Property - A property is a type of attribute of HTML tag. Put simply, all the
HTML attributes are converted into CSS properties. They could be color, border
etc.
• Value - Values are assigned to properties. For example, color property can have
value either red or #F1F1F1 etc.
108
The selector points to the HTML element you want to style.
A CSS declaration always ends with a semicolon, and declaration blocks are
surrounded by curly braces.
In the following example all <p> elements will be center-aligned, with a red text color:
Example
p{
color: red;
text-align: center;
}
Here table is a selector and border is a property and given value 1px solid #C00 is
the value of that property.
You can define selectors in various simple ways based on your comfort. Let me put
these selectors one by one.
109
8.3 CSS Selector
CSS selectors are used to "find" (or select) HTML elements based on their element
name, id, class, attribute, and more.
You can select all <p> elements on a page like this (in this case, all <p> elements
will be center-aligned, with a red text color):
Example
p{
text-align: center;
color: red;
}
2. The id Selector
The id selector uses the id attribute of an HTML element to select a specific element.
To select an element with a specific id, write a hash (#) character, followed by
the id of the element.
The style rule below will be applied to the HTML element with id="para1":
Example
#para1 {
text-align: center;
color: red;
}
Rather than selecting elements of a specific type, the universal selector quite simply
matches the name of any element type −
*{
color: #000000;
}
110
This rule renders the content of every element in our document in black.
Suppose you want to apply a style rule to a particular element only when it lies inside
a particular element. As given in the following example, style rule will apply to <em>
element only when it lies inside <ul> tag.
Example
ul em {
color: #000000;
}
This selector matches all elements that are the immediate children of a specified
element
Syntax
Example
ul>li {
color: red;
To select elements with a specific class, write a period (.) character, followed
by the name of the class.
In the example below, all HTML elements with class="center" will be red and center-
aligned:
Example
111
.center {
text-align: center;
color: red;
}
You can also specify that only specific HTML elements should be affected by a
class.
In the example below, only <p> elements with class="center" will be center-aligned:
Example
p.center {
text-align: center;
color: red;
}
In the example below, the <p> element wil be styled according to class="center" and
to class="large":
Example
<p class="center large">This paragraph refers to two classes.</p>
Example
h1 { color: green } Becomes => h1, h2, h3 { color: green; }
h2 { color: green }
h3 { color: green }
HTML code
<html>
<head>
<style>
112
h1, h2, p {
text-align: center;
color: red;
</style>
</head>
<body>
<h1>Hello World!</h1>
<h2>Smaller heading!</h2>
<p>This is a paragraph.</p>
</body>
</html>
113
8.5 CSS Comments
Comments are used to explain the code, and may help when you edit the source
code at a later date.
A CSS comment starts with /* and ends with */. Comments can also span multiple
lines:
Example
p{
color: red;
/* This is a single-line comment */
text-align: center;
}
/* This is
a multi-line
comment */
With an external style sheet, you can change the look of an entire website by
changing just one file!
Each page must include a reference to the external style sheet file inside the <link>
element. The <link> element goes inside the <head> section:
An external style sheet can be written in any text editor. The file should not contain
any html tags. The style sheet file must be saved with a .css extension.
body {
background-color: lightblue;
114
}
h1 {
color: navy;
margin-left: 20px;
<html>
<head>
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
</html>
An internal style sheet may be used if one single page has a unique style.
Internal styles are defined within the <style> element, inside the <head> section of
an HTML page:
Example:
<html>
<head>
<style>
body {
115
background-color: linen;
h1 {
color: maroon;
margin-left: 40px;
</style>
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
</html>
Inline Styles
An inline style may be used to apply a unique style for a single element.
To use inline styles, add the style attribute to the relevant element. The style attribute
can contain any CSS property.
The example below shows how to change the color and the left margin of a <h1>
element:
<html>
<body>
<p>This is a paragraph.</p>
</body>
</html>
116
Multiple Style Sheets
If some properties have been defined for the same selector (element) in different
style sheets, the value from the last read style sheet will be used.
Example:
<html>
<head>
<style>
h1 {
color: orange;
</style>
</head>
<body>
<h1>This is a heading</h1>
</body>
</html>
So, an inline style (inside a specific HTML element) has the highest priority, which
means that it will override a style defined inside the <head> tag, or in an external
style sheet, or a browser default value.
Example:
<html>
<head>
117
<style>
</style>
</head>
<p>In this example, the background color is set inline, in an internal stylesheet, and
in an external stylesheet.</p>
</body>
</html>
8.7 Summary
• CSS Syntax
• CSS Selectors
• Selectors Grouping
• CSS Comments
118
Unit 9: Cascading Style Sheet
Attributes and Properties
Unit Structure
9.12. Summary
119
9.1 CSS Color Attribute
Example
body {
color: red;
}
h1 {
color: #00ff00;
}
p{
color: rgb(0,0,255);
}
Property Description
background-color Specifies the background color to be used
background-image Specifies ONE or MORE background images to be used
Specifies the position of the background images. You
can set this property to top left/center/right ,center
left/center/right, bottom left/center/right right
top/center/bottom, left top/center/bottom, x%
y%(The first value is the horizontal position and the
second value is the vertical. The top left corner is 0%
background-position
0%. The right bottom corner is 100% 100%. If you only
specify one value, the other value will be 50%. . Default
value is: 0% 0%),
x-position y-position(The first value is the horizontal
position and the second value is the vertical. The top left
corner is 0 0. Units can be pixels (0px 0px)
background-size Specifies the size of the background images.
Specifies how to repeat the background images. You
background-repeat can set this property to repeat, repeat-x, repeat-y or
no- repeat.
120
Specifies whether the background images are fixed or
background-attachment scrolls with the rest of the page. You can set this
property to scroll or fixed.
Set font related styles for the text present on an HTML web page.
Property Description
Specifies a prioritized list of font family name /or generic
font-family names, the browser should try to match. (serif, sans-
serif, Times new roman etc.)
You can set the style of text in element. You can set this
font-style
property to normal, italic or oblique
You can control the weight of text in an element. You
can set this property to normal, bold, bolder, lighter, or
font-weight
numeric value(100, 200, 300, 400, 500, 600, 700, 800,
900)
Specifies whether or not a font is small-caps font; You
font-variant
can set this property to normal or small-caps
The text properties allow you to format text present in HTML web page by providing
various text formatting options.
Property Description
Color Specifies the foreground color of the text.
The text-align property is used to set the horizontal
text-align alignment of a text. A text can be left or right aligned,
centered, or justified.
The text-decoration property is used to set or remove
text-decoration decorations from text. You can set this property to
underline, overline, line-through or blink
The text-transform property is used to specify
uppercase and lowercase letters in a text. It can be
text-transform
used to turn everything into uppercase or lowercase
letters, or capitalize the first letter of each word.
121
The text-indent property is used to specify the
indentation of the first line of a text.It can be
text-indent
length(pixcel(px), centimeter(cm), inch(in), point(pt)) or
percentage
The letter-spacing property is used to specify the space
between the characters in a text.You can set this to
letter-spacing
normal or length(pixcel(px), centimeter(cm), inch(in),
point(pt)).
The line-height property is used to specify the space
line-height
between lines.
The direction property is used to change the text
direction
direction of an element:
The word-spacing property is used to specify the space
word-spacing between the words in a text. You can set this to normal
or length(pixcel(px), centimeter(cm), inch(in), point(pt)).
The CSS border properties allow you to specify the style, width, and color of an
element's border.
Property Description
The border-style property specifies what kind of border
to display. The following values are allowed:
border-top-style, border-
Specify the styles of the top, right, bottom and left
right- style, border-bottom-
borders.
style and border-left- style
The border-width property specifies the width of the four
borders. The width can be set as a specific size (in px,
border-width
pt, cm etc) or by using one of the three pre-defined
values: thin, medium, or thick.
border-top-width, border-
Specify the width of the top, right, bottom and left
right- width, border-bottom-
borders.
width and border-left- width
border-color The border-color property is used to set the color of the
four borders. The border-color property can have from
122
one to four values (for the top border, right border,
bottom border, and the left border
border-top-color, border-
Specify the colors of the top, right, bottom and left
right-color, border-bottom-
borders.
color and border-left-color
• border-style: dotted;
o all four borders are dotted
To shorten the code, it is also possible to specify all the individual border properties
in one property.
The border property is a shorthand property for the following individual border
properties:
• border-width
123
• border-style (required)
• border-color
The CSS margin properties are used to generate space around elements.
The CSS margin properties set the size of the white space OUTSIDE the border.
(The margins are completely transparent - and cannot have a background color.It is
also possible to use negative values for margins)
Property Description
It set margin properties for all four borders.You can set
Margin it to auto, length(pixcel(px), centimeter(cm), inch(in),
point(pt)) or percentage
Margin-top, Margin-right, Specify the margin of the top, right, bottom and left
Margin-bottom, Margin-left borders.
The margin property is a shorthand property for the following individual margin
properties:
• margin-top
• margin-right
• margin-bottom
• margin-left
You can set the margin property to auto to horizontally center the element within its
container.
The element will then take up the specified width, and the remaining space will be
split equally between the left and right margins:
The CSS dimension properties allow you to control the height and width of an
element.
124
Property Description
Sets the height of an element. You can be set to auto (this is
default. Means that the browser calculates the height and width),
height
or be specified in length values, like px, cm, etc., or in percent (%)
of the containing block.
The CSS padding properties are used to generate space around content.
The CSS padding properties define the white space between the element content
and the element border.
Property Description
125
9.9 CSS List Attributes
Property Description
Property Description
126
bottom
The position property specifies the type of positioning method used for an element.
Property Description
• Static
Static positioned elements are not affected by the top, bottom, left, and right
properties.
127
• Relative
Setting the top, right, bottom, and left properties of a relatively-positioned element
will cause it to be adjusted away from its normal position
• Fixed
An element is positioned relative to the view port, which means it always stays in the
same place even if the page is scrolled. The top, right, bottom, and left properties are
used to position the element.
A fixed element does not leave a gap in the page where it would normally have been
located.
Absolute
This type of positioning allows you to place your element precisely where you
want it.
The positioning is done relative to the first relatively (or absolutely) positioned
parent element. In the case when there is no positioned parent element, it will be
positioned related directly to the HTML element (the page itself).
What Is Z-Index?
➢ The Z-Index property determines the stack level of an HTML element.CSS layer
refer to applying z-index property to element that overlap to another element.
➢ CSS z-index possible value 0, positive (1 to 9999) and negative (-1 to -9999)
value to set an element.
128
9.12 Summary
129
Unit 10: Introduction to Java Script
Unit Structure
10.9. Summary
130
10.1Introduction to Java Script
Advantages of JavaScript
1) It is an interpreted language.
4) Procedural Capabilities
6) Platform Independence
131
10.2 Select Developing Environment for JavaScript
With simple text editor such as notepad, you can create JavaScript program.
1) Microsoft Frontpage
2) Adobe Deramweaver
3) Adobe GoLive
There are 3 possibilities to integrate the JavaScript code into the HTML file.
The first possibility to incorporate the source code under the <head> tag of HTML
file.
Example
<html>
<head>
<script type=”text/JavaScript”>
…..
…..
</script>
</head>
132
2. Integrated script under the <body> tag
When you place JavaScript code under the <body> tag, this generates the contents
of the web page.
JavaScript code under the <body> tag executes when the web page loads and go in
the body section.
Example
<html>
<head>
</head>
<body>
<script type=”text/JavaScript”>
…..
…..
</script>
</body>
You can import an external JavaScript file, when you want to run the same
JavaScript file on several HTML files, without having to write the same JavaScript
code on every HTML file.
Example
<html>
<head>
<script src=”abc.js”>
</script>
</head>
133
First JavaScript Program
The javascript code used <script>..</script> tags to start and end the code.
To print something
Document.write(“hello”);
1. JavaScript Statements
JavaScript statements are the single line codes in between the <script>and </script>
tags.
<script type=”text/JavaScript”>
document.write(“hello”);
</script>
The statement block begins and ends with open and close brackets.
Example
<script type=”text/JavaScript”>
document.write(“<h1>This is a header</h1>”);
document.write(“<p>This is a paragraph</p>”);
document.write(“<h2>This is a header2</h2>”);
} </script>
3. JavaScript Comments
134
JavaScript comments can be used to explain JavaScript code, and to make it more
readable.
1. Single-Line Comments
Any text between // and the end of the line, will be ignored by JavaScript (will not be
executed).
2. Multi-line Comments
Variables are temporary store data and have a name, value and memory address.
The general rules for constructing names for variables (unique identifiers) are:
Declaring Variables
• Before you can use variable for storing any data, it has to be declared.
• Syntax
• Once you assign value to a variable, you can access the value and use
it.
135
• Syntax
Depending on the type of data, the data is processed in different ways by JavaScript.
The basic data types available in JavaScript are string, number and Boolean.
• Strings are written with quotes. You can use single or double quotes.
Code Outputs
\\ backslash
\n new line
\r carriage return
\t tab
\b backspace
You can use quotes inside a string, as long as they don't match the quotes
surrounding the string:
136
Numbers can be written with, or without decimals
Example
Extra large or extra small numbers can be written with scientific (exponential)
notation:
Example
var y = 123e5; // 12300000
var z = 123e-5; // 0.00123
Example
var x = true;
var y = false;
JavaScript operators are used to assign values, compare values, perform arithmetic
operations, and more.
1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Bitwise Operators
4. Logical Operators
5. Assignment Operators
1. Arithmetic Operators
137
The following operators are known as JavaScript arithmetic operators.
2. Assignment Operators
Given that x = 10 and y = 5, the table below explains the assignment operators:
+= x += y x=x+y x = 15
-= x -= y x=x-y x=5
*= x *= y x=x*y x = 50
/= x /= y x=x/y x=2
%= x %= y x=x%y x=0
138
3. Logical Operators
Logical operators are used to determine the logic between variables or values.
Given that x = 6 and y = 3, the table below explains the logical operators:
(x == 5 || y == 5) is
|| or
false
4. Comparison Operators
The JavaScript comparison operator compares the two operands. The comparison
operators are as follows:
5. Bitwise Operators
Bit operators work on 32 bits numbers. Any numeric operand in the operation is
converted into a 32 bit number. The result is converted back to a JavaScript number.
The bitwise operators perform bitwise operations on operands. The bitwise operators
are as follows:
139
Operator Description Example
Bitwise AND
(10==20 &
& It performs a Boolean AND operation on 20==33) = false
each bit of its integer arguments.
Bitwise OR
(10==20 |
| It performs a Boolean OR operation on each 20==33) = false
bit of its integer arguments.
Bitwise XOR
Bitwise NOT
~ It is a unary operator and operates by (~10) = -10
reversing all the bits in the operand.
140
6. Conditional (Ternary) Operator
The typeof operator returns the type of a variable, object, function or expression:
Example
typeof "John" // Returns string
typeof 3.14 // Returns number
typeof false // Returns boolean
typeof new Date() // Returns object
typeof function () {} // Returns function
typeof myCar // Returns undefined (if myCar is not declared)
typeof null // Returns object
After deletion, the property cannot be used before it is added back again.
The delete operator deletes both the value of the property and the property itself.
Example
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
delete person.age; // or delete person["age"];
141
10.8 Java Script Flow Control Statements
If-else
The JavaScript if-else statement is used to execute the code whether condition is
true or false. There are three forms of if statement in JavaScript.
1. If Statement
2. If else statement
3. if else if statement
JavaScript If statement
if(expression){
//content to be evaluated
The following flow chart shows how the if-else statement works.
142
JavaScript If...else Statement
It evaluates the content whether condition is true of false. The syntax of JavaScript if-
else statement is given below.
if(expression){
else{
143
JavaScript If...else if statement
It evaluates the content only if expression is true from several expressions. The
signature of JavaScript if else if statement is given below.
if(expression1){
else if(expression2){
else if(expression3){
else{
<script>
var a=20;
if(a==10){
else if(a==15){
else if(a==20){
144
}
else{
</script>
Switch Case
Flow Chart
145
Syntax
switch (expression)
{
case condition 1: statement(s)
break;
default: statement(s)
146
}
The break statements indicate the end of a particular case. If they were omitted, the
interpreter would continue executing each statement in each of the following cases.
While Loops
The purpose of a while loop is to execute a statement or code block repeatedly as
long as an expression is true. Once the expression becomes false, the loop
terminates.
Syntax
The syntax of while loop in JavaScript is as follows –
while (expression){
Statement(s) to be executed if expression is true
}
The do...while loop is similar to the while loop except that the condition check
happens at the end of the loop. This means that the loop will always be executed at
least once, even if the condition is false.
Syntax
The syntax for do-while loop in JavaScript is as follows –
do{
Statement(s) to be executed;
} while (expression);
Note − Don’t miss the semicolon used at the end of the do...while loop.
For Loop
The 'for' loop is the most compact form of looping. It includes the following three
important parts −
• The loop initialization where we initialize our counter to a starting value. The
initialization statement is executed before the loop begins.
• The test statement which will test if a given condition is true or not. If the
condition is true, then the code given inside the loop will be executed,
otherwise the control will come out of the loop.
• The iteration statement where you can increase or decrease your counter.
147
You can put all the three parts in a single line separated by semicolons.
Syntax
Loop Control
JavaScript provides full control to handle loops and switch statements. There may be
a situation when you need to come out of a loop without reaching at its bottom.
There may also be a situation when you want to skip a part of your code block and
start the next iteration of the look.
To handle all such situations, JavaScript provides break and continue statements.
These statements are used to immediately come out of any loop or to start the next
iteration of any loop respectively.
The break statement, which was briefly introduced with the switch statement, is used
to exit a loop early, breaking out of the enclosing curly braces.
The continue statement tells the interpreter to immediately start the next iteration of
the loop and skip the remaining code block.
When a continue statement is encountered, the program flow moves to the loop
check expression immediately and if the condition remains true, then it starts the
next iteration, otherwise the control comes out of the loop.
A label can be used with break and continue to control the flow more precisely. A
label is simply an identifier followed by a colon (:) that is applied to a statement or a
block of code. We will see two different examples to understand how to use labels
with break and continue.
Note − Line breaks are not allowed between the ‘continue’ or ‘break’ statement and
its label name. Also, there should not be any other statement in between a label
name and associated loop.
148
10.9 Summary
149
Unit 11: Arrays, Functions, Events and
Dialog boxes in Java Script
Unit Structure
11.5. Summary
150
11.1 Java Script Arrays
1. By array literal
2. By creating instance of Array directly (using new keyword)
3. By using an Array constructor (using new keyword)
var arrayname=[value1,value2.....valueN];
151
There are mainly two advantages of JavaScript functions.
1. Built-in functions
2. User defined functions
Built-in functions
JavaScript has five functions built in to the language. They are eval, parseInt,
parseFloat, number, and string.
1. eval
eval(Expression)
Examples
var num = 2;
eval("num + 200");
2. parseInt
Parses a string argument and returns an integer and convert number into integer.
Syntax:
parseInt(string)
3. parseFloat
If string is not begin with a floating point than it returns NaN error.
Syntax:
152
parseFloat(string)
4. Number
5. String
//code to be executed
Function Arguments
We can call function by passing arguments. Let’s see the example of function that
has one argument.
<script>
function getcube(number){
alert(number*number*number);
</script>
<form>
153
</form>
We can call function that returns a value and use it in our program.
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.
Example
alert("I am an alert box!");
Confirm Box
A confirm box is often used if you want the user to verify or accept something.
154
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.
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.
Line Breaks
To display line breaks inside a popup box, use a back-slash followed by the
character n.
Example
alert("Hello\nHow are you?");
When JavaScript is used in HTML pages, JavaScript can "react" on these events.
JavaScript's interaction with HTML is handled through events that occur when the
user or the browser manipulates a page.
When the page loads, it is called an event. When the user clicks a button, that click
too is an event. Other examples include events like pressing any key, closing a
window, resizing a window, etc.
Events Description
onclick occurs when element is clicked.
155
ondblclick occurs when element is double-clicked.
occurs when an element gets focus such
onfocus
as button, input, textarea etc.
occurs when form looses the focus from
onblur
an element.
onsubmit occurs when form is submitted.
occurs when mouse is moved over an
onmouseover
element.
occurs when mouse is moved out from
onmouseout
an element (after moved over).
occurs when mouse button is pressed
onmousedown
over an element.
occurs when mouse is released from an
onmouseup
element (after mouse is pressed).
occurs when document, object or
onload
frameset is loaded.
occurs when body or frameset is
onunload
unloaded.
onscroll occurs when document is scrolled.
onresized occurs when document is resized.
onreset occurs when form is reset.
onkeydown occurs when key is being pressed.
onkeypress occurs when user presses the key.
onkeyup occurs when key is released.
11.5 Summary
156
Dr. Babasaheb BCAMI-103
Ambedkar Open
University
CHAP 12
CHAP 13
CHAP 14
CHAP 15
157
BLOCK 4: JAVA SCRIPT OBJECTS, JQUERY
AND XML
Block Introduction
Block Objective
By learning this block of web technology student will learn about adding
objects with methods and properties, write code in jquery syntax and describe data in
XML. Reader of this block, will know web page development through various
objects of java script, jQuery and using XML describes the text in a digital
document.
This block servers knowledge of CSS and Java script. I hope, this block will
clear the idea of all concepts of objects of javascript, jQuery and XML.
158
Unit 12: Java Script Objects, Methods
and Properties
Unit Structure
12.7. Summary
159
12.1 Java Script Document Object
When html document is loaded in the browser, it becomes a document object. It is the
root element that represents the html document.
Methods
Properties
Property Description
The color to be used when displaying
alinkcolor
activated links in the document
An array of anchor objects present in the
anchors
document
bgColor The background color of the document
The foreground color (i.e. the color of the
fgColor
text in the document)
An array of the Forms objects contained in
forms
the document.
images An Array of Image objects contained the
160
document
The date that the document was last
lastModified
modified
The color to be used when displaying links
linkColor
in the document
An array of links contained in the
links
document
The color to be used when displaying links
vlinkColor in the document which have been visited
by the current user
The innerHTML property can be used to
modify your document's HTML.When you
innerHTML use innerHTML, you can change the
page's content without refreshing the
page.
Even when the title of a document has been specified using the HTML <title> tag it is
possible to dynamically change the current setting using the title property of the
document object.
The following example initially sets the document title to JavaScript Document Object
Example and provides a button which, when pressed, changes the title to a new value:
<html>
<head>
<title>JavaScript Document Object Example</title>
</head>
<body>
<form action="">
<input type=button value="Press to change title" onclick="document.title='hello'"/>
</form>
</body>
</html>
161
Changing the Document Colors
A similar approach can be used to change the colors using in the document.
The following example changes the foreground and background colors when the
"Change colors" button is pressed:
<html>
<head>
<title>JavaScript Document Object Example</title>
<script language="javascript" type="text/javascript">
function changeColors()
{
document.fgColor="red";
document.bgColor="blue";
}
</script>
</head>
<body>
<p>
Sample text to show color change
</p>
<form action="">
<input type=button value="Change colors" onclick="changeColors()"/>
</form>
</body>
162
</html>
the links property of the document object can be used to obtain a list of Link objects (in
other words, links to other web pages) in the current document.
To demonstrate this, the following example consists of a simple HTML page containing
two links to other sites (Amazon.com and Yahoo). The J
<html>
<head>
<title>JavaScript Document Object Example</title>
</head>
<body>
163
for (i in document.links)
{
document.write( document.links[i] + "<br>" );
}
</script>
</form>
</body>
</html>
Inner HTML
<!DOCTYPE html>
<html>
<body>
<script>
164
function myFunction() {
</script>
</body>
</html>
Describes the JavaScript array object including parameters, properties, and methods.
Parameters
• arrayLength
• elementN - Array element list of values
165
Properties
• index
• input
• length - The quantity of elements in the object.
Methods
<html>
<head>
<title>JavaScript Array concat Method</title>
</head>
<body>
<script type="text/javascript">
var alpha = ["a", "b", "c"];
var numeric = [1, 2, 3];
</body>
</html>
166
• join(delimiter) - Puts all elements in the array into a string, separating each element
with the specified delimiter.
<html>
<head>
</head>
<body>
<script type="text/javascript">
</script>
</body>
167
</html>
• pop() - Pops the last string off the array and returns it.
<html>
<head>
</head>
<body>
<script type="text/javascript">
168
</script>
</body>
</html>
<html>
<head>
</head>
<body>
<script type="text/javascript">
169
length = numbers.push(20);
</script>
</body>
</html>
<html>
<head>
</head>
<body>
<script type="text/javascript">
170
document.write("Reversed array is : " + arr );
</script>
</body>
</html>
• shift() - Decreases array element size by one by shifting the first element off the
array and returning it.
<html>
<head>
<title>JavaScript Array shift Method</title>
</head>
<body>
<script type="text/javascript">
var element = [105, 1, 2, 3].shift();
document.write("Removed element is : " + element );
</script>
</body>
171
</html>
<html>
<head>
</head>
<body>
<script type="text/javascript">
</script>
172
</body>
</html>
• splice() - It is used to take elements out of an array and replace them with those
specified. In the below example the element starting at element 3 is removed, two of
them are removed and replaced with the specified strings. The value returned are
those values that are replaced.
<html>
<head>
</head>
<body>
<script type="text/javascript">
173
// document.write("<br />removed is: " + removed);
</script>
</body>
</html>
document.write(swords);
174
limit, lines, finish, complete, In, Out
• unshift() -method adds one or more elements to the beginning of an array and
returns the new length of the array.
<html>
<head>
</head>
<body>
<script type="text/javascript">
</script>
</body>
</html>
175
12.3 Java Script String Object
The String object lets you work with a series of characters; it wraps Javascript's string
primitive data type with a number of helper methods.
As JavaScript automatically converts between string primitives and String objects, you
can call any of the helper methods of the String object on a string primitive.
Syntax
The String parameter is a series of characters that has been properly encoded.
String Properties
Property Description
176
String Methods
Here is a list of the methods available in String object along with their description.
<script type="text/javascript">
var str1 = new String( "This is string one" );
var str2 = new String( "This is string two" );
Combines the var str3 = str1.concat( str2 );
text of two
document.write("Concatenated String :" + str3);
strings and
concat() </script>
returns a new
string.
Output
Concatenated String :This is string oneThis is string two.
<script type="text/javascript">
Returns the var str1 = new String( "This is string one" );
index within the var index = str1.indexOf( "string" );
calling String document.write("indexOf found String :" + index );
object of the
document.write("<br />");
indexOf() first occurrence var index = str1.indexOf( "one" );
of the specified document.write("indexOf found String :" + index );
value, or -1 if </script>
not found.
Output
177
indexOf found String :8
indexOf found String :15
<script type="text/javascript">
var str1 = new String( "This is string one and again
string" );
var index = str1.lastIndexOf( "string" );
Returns the document.write("lastIndexOf found String :" + index );
index within the
calling String document.write("<br />");
object of the
lastIndexOf() var index = str1.lastIndexOf( "one" );
last occurrence
document.write("lastIndexOf found String :" + index
of the specified );
value, or -1 if </script>
not found.
Output
lastIndexOf found String :29
lastIndexOf found String :15
<script>
var s1="abcdefgh";
Extracts a
section of a var s2=s1.slice(2,5);
string and
slice()
returns a new document.write(s2);
string.
</script>
</body>
178
output
cde
<script type="text/javascript">
var str = "Apples are round, and apples are juicy.";
Splits a String var splitted = str.split(" ", 3);
object into an
array of strings document.write( splitted );
split() by separating </script>
the string into
substrings. Output
Apples,are,round,
<script type="text/javascript">
var str = "Apples are round, and apples are juicy.";
(20, 2): d
179
converted to var s2=s1.toLowerCase();
lower case.
document.write(s2);
</script>
<script type="text/javascript">
var str = "Apples are round, and Apples are Juicy.";
Returns a document.write(str.toString( ));
string </script>
representing
toString()
the specified
Output
object.
Apples are round, and Apples are Juicy.
<script>
<script>
This method
removes var s1=" javascript trim ";
leading and
var s2=s1.trim();
Trim() trailing
whitespaces document.write(s2);
from the string.
</script>
180
The JavaScript date object can be used to get year, month and day. You can display a
timer on the webpage by the help of JavaScript date object.
You can use different Date constructors to create date object. It provides methods to get
and set day, month, year, hour, minute and seconds.
Constructor
1. Date()
2. Date(milliseconds)
3. Date(dateString)
4. Date(year, month, day, hours, minutes, seconds, milliseconds)
Example
<script>
var msecs = Date.parse( "Aug 28, 2008 23:30:00" );
document.write( "Number of milliseconds from 1970: " + msecs );
</script>
</body>
</html>
Output
Number of milliseconds from 1970: 1219946400000
7 agruments − To use the last form of the constructor shown above. Here is a
description of each argument:
181
o year − Integer value representing the year., you should always specify the
year in full; use 1998, rather than 98.
o month − Integer value representing the month, beginning with 0 for January
to 11 for December.
o date − Integer value representing the day of the month.
o hour − Integer value representing the hour of the day (24-hour scale).
o minute − Integer value representing the minute segment of a time reading.
o second − Integer value representing the second segment of a time reading.
o millisecond − Integer value representing the millisecond segment of a time
reading.
Method Description
Example:
<HTML>
182
<HEAD>
<TITLE>Welcome Message</TITLE>
</HEAD>
<BODY>
<SCRIPT language="JavaScript">
var d = t.getDate();
var m = t.getMonth()+1;
var y = t.getFullYear();
var h = t.getHours();
if(h<12)
document.write("Good Morning!!!");
document.write("Good Afternoon!!!");
else if(h>=18)
document.write("Good Evening!!!");
else if(h>=22)
document.write("Good Night!!!");
183
}
</SCRIPT>
</BODY>
</HTML>
Methods
The following table lists the methods available with the Math object:
var value =
Math.abs("string");
document.write("<br
/>Fourth Test Value : " + value
);
</script>
Output
First Test Value : 1
184
Second Test Value : 0
Third Test Value : 20
Fourth Test Value : NaN
<script type="text/javascript">
var value =Math.cos(90);
document.write("First Test
Value : " + value );
<script type="text/javascript">
var value = Math.exp(1);
document.write("First Test
Exponential and natural Value : " + value );
exp, log
logarithm, base e var value = Math.log(10);
document.write("First Test
Value : " + value );
</script>
<body>
</script>
Output
185
Ceil of 4.6 is: 5
<body>
<script>
document.write(Math.floor(4.6));
Returns greatest integer
floor less than or equal to </script>
argument
</body>
Output
186
First Test Value : 100
Second Test Value : -1
<body>
<script>
Exponential; first
document.write(Math.pow(3,4));
pow argument is base, second
is exponent </script>
</body>
Output
3 to the power of 4 is: 81
<body>
</script>
</body>
<script type="text/javascript">
187
</body>
</html>
Output
Second Test Value : 21
Third Test Value : 20
Fourth Test Value : -20
<body>
<script>
document.write(Math.sqrt(17));
sqrt Square root
</script>
</body>
Output
Square Root of 17 is:
4.123105625617661
Methods
Method Description
188
open() Opens the new window.
Example
<html>
<body>
<script>
function myFunction() {
</script>
</body>
</html>
189
Example of creating Digital Clock
<html>
<body>
<script>
window.onload=function(){getTime();}
function getTime(){
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
m=checkTime(m);
s=checkTime(s);
document.getElementById('txt').innerHTML=h+":"+m+":"+s;
190
setTimeout(function(){getTime()},1000);
//setInterval("getTime()",1000);//another way
function checkTime(i){
if (i<10){
i="0" + i;
return i;
</script>
</body>
</html>
Example:
191
<HTML>
<HEAD>
<TITLE>Window Events</TITLE>
</HEAD>
<BODY>
<FORM name="windowEvent">
</FORM>
</BODY>
</HTML>
192
12.7 Summary
193
Unit 13: Introduction to JQuery
Unit Structure
13.6. Summary
194
13.1 What is JQuery?
JQuery is a fast, small and feature-rich JavaScript library included in a single .js file.
JQuery makes a web developer's life easy. It provides many built-in functions using
which you can accomplish various tasks easily and quickly.
DOM Manipulation:You can manipulate DOM elements using various built-in jQuery
functions. For example, adding or removing elements, modifying html content, css class
etc.
Special Effects: You can apply special effects to DOM elements like show or hide
elements, fade-in or fade-out of visibility, sliding effect, animation etc.
Events: jQuery library includes functions which are equivalent to DOM events like click,
dblclick, mouseenter, mouseleave, blur, keyup, keydown etc. These functions
automatically handle cross-browser issues.
Ajax: jQuery also includes easy to use AJAX functions to load data from servers without
reloading whole page.
Advantages of jQuery:
1. Easy to learn: jQuery is easy to learn because it supports same JavaScript style
coding.
2. Write less do more: jQuery provides a rich set of features that increase
developers' productivity by writing less and readable code.
195
3. Excellent API Documentation: jQuery provides excellent online API
documentation.
4. Cross-browser support: jQuery provides excellent cross-browser support without
writing extra code.
5. Unobtrusive: jQuery is unobtrusive which allows separation of concerns by
separating html and jQuery code.
On the jQuery home page, two downloads are available: a production version and a
development version. Unless you’re planning to develop jQuery plug-ins, or need to
look at the internals of jQuery, you should download and use the minified production
version.
As another viable option, especially for working through this chapter, you could use a
content delivery network (CDN) to access a hosted version of jQuery. Google hosts
jQuery and other libraries through its API website. This means that you can include
jQuery in your webpage and JavaScript programs without having to host the file locally
on your server. See http://code.google.com/apis/libraries/devguide.html for more
information.
2. Including jQuery
You include jQuery in a webpage in the same manner as you would any other external
JavaScript file—with a <script> tag pointing to the source file. Consider the code in
Listing
Example
196
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
</head>
<body>
</body>
</html>
The jQuery syntax is tailor-made for selecting HTML elements and performing some
action on the element(s).
Examples:
In jQuery, you do this through the .ready() utility function of the document element.
Example
$(document).ready
197
$(document).ready(function(){
});
This is to prevent any jQuery code from running before the document is finished loading
(is ready).
It is good practice to wait for the document to be fully loaded and ready before working
with it. This also allows you to have your JavaScript code before the body of your
document, in the head section.
Here are some examples of actions that can fail if methods are run before the document
is fully loaded:
$(function(){
});
13.6 Summary
• What is JQuery
• Using JQuery
• JQuery Syntax
198
Unit 14: JQuery Selectors, Functions,
Effects and Events
Unit Structure
14.6. Summary
199
14.1 JQuery Selectors
jQuery selectors allow you to select and manipulate HTML element(s).jQuery selectors
are used to "find" (or select) HTML elements based
All selectors in jQuery start with the dollar sign and parentheses: $().
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$("p").hide();
});
});
</script>
</head>
<body>
<h2>This is a heading</h2>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<button>Click me to hide paragraphs</button>
</body>
200
</html>
The jQuery #id selector uses the id attribute of an HTML tag to find the specific element.
An id should be unique within a page, so you should use the #id selector when you want
to find a single, unique element.
To find an element with a specific id, write a hash character, followed by the id of
the HTML element:
Example: $("#test")
<html>
<head>
<title>The Selecter Example</title>
<script src="jquery-3.3.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
201
/* This would select second division only*/
$("#div2").css("background-color", "yellow");
});
</script>
</head>
<body>
<div class = "big" id = "div1">
<p>This is first division of the DOM.</p>
</div>
202
2. Selecting element by class(The .class Selector)
To find elements with a specific class, write a period character, followed by the name of
the class:
$(".test")
Example
<html>
<head>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(".big").css("background-color", "yellow");
});
</script>
</head>
<body>
</div>
203
<p>This is second division of the DOM.</p>
</div>
</div>
</body>
</html>
The element type selector selects all the elements that have a tag name of it.
Syntax
Here is the simple syntax to use this selector −
$('tagname')
204
Example: $('div'), $('a')
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$("p").hide();
});
});
</script>
</head>
<body>
<h2>This is a heading</h2>
<p>This is a paragraph.</p>
</body>
</html>
205
4. Selecting element by hierarchy
This hierarchy Elements selector selects the combined results of all the specified
selectors like div, p etc.
You can specify any number of selectors to combine into a single result. Here order of
the DOM elements in the jQuery object isn’t necessarily identical.
Example
• $('div, p') − selects all the elements matched by div or p.
<html>
<head>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
});
206
</script>
</head>
<body>
</div>
</div>
</div>
</body>
</html>
207
5. Selecting element by Attribute
The attribute selector selects the attribute of all the specified selectors like div, p etc.
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(":text").css("background-color", "yellow");
});
</script>
</head>
<body>
<form>
<label>Name:
<input type="text"></label>
<label>Password:
<input type="password"></label>
</form>
208
</body>
</html>
Basic Selectors
209
Basic Filter Selectors
Selector Example Description
:first $("p:first") Selects the first <p> element.
:last $("p:last") Selects the last <p> element.
:even $("tr:even") Selects all even <tr> elements,
zero-indexed.
:odd $("tr:odd") Selects all odd <tr> elements,
zero-indexed.
:eq() $("tr:eq(1)") Select the 2nd <tr> element
within the matched set, zero-
based index.
:not() $("p:not(:empty)") Select all <p> elements that are
not empty.
:lt() $("ul li:lt(3)") Select all <li> elements at an
index less than three within the
matched set (i.e. selects 1st,
2nd, 3rd list elements), zero-
based index.
:gt() $("ul li:gt(3)") Select all <li> elements at an
index greater than three within
the matched set (i.e. selects
4th, 5th, ... list elements), zero-
based index.
:header $(":header") Selects all elements that are
headers,
like <h1>, <h2>,<h3> and so
on.
:lang() $(":lang(en)") Selects all elements that have
a language value "en"
i.e.lang="en", lang="en-us" etc.
<!DOCTYPE html>
<html>
<head>
210
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
$(document).ready(function(){
$("p:first").css("background-color", "yellow");
});
</script>
</head>
<body>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
$(document).ready(function(){
$("tr:even").css("background-color", "yellow");
211
});
</script>
</head>
<body>
<table border="1">
<tr>
<th>Company</th>
<th>Country</th>
</tr>
<tr>
<td>Alfreds Futterkiste</td>
<td>Germany</td>
</tr>
<tr>
<td>Berglunds snabbköp</td>
<td>Sweden</td>
</tr>
<tr>
<td>Centro comercial Moctezuma</td>
<td>Mexico</td>
</tr>
<tr>
<td>Ernst Handel</td>
<td>Austria</td>
</tr>
<tr>
<td>Island Trading</td>
<td>UK</td>
</tr>
</table>
</body>
</html>
212
Example of lt selector
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
$(document).ready(function(){
$("tr:lt(4)").css("background-color", "yellow");
});
</script>
</head>
<body>
<table border="1">
<tr>
<th>Company</th>
<th>Contact</th>
<th>Country</th>
</tr>
<tr>
<td>Alfreds Futterkiste</td>
<td>Maria Anders</td>
<td>Germany</td>
</tr>
<tr>
<td>Berglunds snabbköp</td>
213
<td>Christina Berglund</td>
<td>Sweden</td>
</tr>
<tr>
<td>Centro comercial Moctezuma</td>
<td>Francisco Chang</td>
<td>Mexico</td>
</tr>
<tr>
<td>Ernst Handel</td>
<td>Roland Mendel</td>
<td>Austria</td>
</tr>
<tr>
<td>Island Trading</td>
<td>Helen Bennett</td>
<td>UK</td>
</tr>
<tr>
<td>Königlich Essen</td>
<td>Philip Cramer</td>
<td>Germany</td>
</tr>
<tr>
<td>Laughing Bacchus Winecellars</td>
<td>Yoshi Tannamuri</td>
<td>Canada</td>
</tr>
<tr>
<td>Magazzini Alimentari Riuniti</td>
<td>Giovanni Rovelli</td>
<td>Italy</td>
</tr>
<tr>
<td>North/South</td>
<td>Simon Crowther</td>
<td>UK</td>
</tr>
</table>
</body>
</html>
214
Example of not selector
<!DOCTYPE html>
<html>
<head>
<script
src="https://code.jquery.com/jquery-
3.2.1.min.js"></script>
<script>
$(document).ready(function(){
$("p:not(.intro)").css("background-
color", "yellow");
});
</script>
</head>
<body>
<h1>Welcome to My Homepage</h1>
215
<ul id="choose">
<li>Goofy</li>
<li>Mickey</li>
<li>Pluto</li>
</ul>
</body>
</html>
216
:only-child $("p:only-child") Selects all <p> elements
that are the only child of
their parent.
:first-of-type $("p:first-of-type") Selects all <p> elements
that are the
first<p> element of their
parent.
:last-of-type $("p:last-of-type") Selects all <p> elements
that are the
last<p> element of their
parent.
:only-of-type $("p:only-of-type") Selects all <p> elements
that have no siblings with
the same element name.
:nth-last-child(n) $("p:nth-last-child(3)") Selects all <p> elements
that are the 3rd-child of
their parent, counting from
the last element to the first.
:nth-of-type(n) $("p:nth-of-type(2)") Selects all <p> elements
that are the
2nd<p> element of their
parent
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
$(document).ready(function(){
$("p:first-child").css("background-color", "yellow");
217
});
</script>
</head>
<body>
</div><br>
</div>
</body>
</html>
218
Example of First-of-type selector
<!DOCTYPE html>
<html>
<head>
<script src="jquery-3.3.1.js"></script>
<script>
$(document).ready(function(){
$("p:first-of-type").css("background-color", "yellow");
});
</script>
</head>
<body>
219
<div style="border:1px solid;">
</div><br>
</div>
</body>
</html>
220
Example of Nth-child Selector
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
$(document).ready(function(){
$("p:nth-child(3)").css("background-color", "yellow");
});
</script>
</head>
<body>
<p>The second paragraph in body (and the 3rd child element in body).</p>
<p>The second paragraph in another div (and the 3rd child element in this div).</p>
</div><br>
221
<div style="border:1px solid;">
<p>The last paragraph in another div (and the 3rd child element in this div).</p>
</div>
</body>
</html>
222
:has() $("p:has(img)") Selects all <p> elements
which contain at least
one<img> element.
:parent $(":parent") Select all elements that
have at least one child
node either an element or
text.
Form Selectors
Selector Example Description
:input $(":input") Selects all input, textarea,
select and button elements
(basically selects all form
controls).
:text $(":text") Selects all input elements
with type="text".
:password $(":password") Selects all input elements
with type="password".
:radio $(":radio") Selects all input elements
with type="radio".
:checkbox $(":checkbox") Selects all input elements
with type="checkbox".
:button $(":button") Selects all input and button
elements withtype="button".
:submit $(":submit") Selects all input and button
elements
withtype="submit".
:reset $(":reset") Selects all input and button
elements withtype="reset".
:image $(":image") Selects all input elements
with type="image".
:file $(":file") Selects all input elements
with type="file".
:selected $(":selected") Selects all elements that
are selected, only works
for<option> elements.
:checked $(":checked") Selects all elements that
are checked or selected,
works for checkboxes, radio
buttons, and select
elements.
223
:focus $(":focus") Selects element if it is
currently focused.
<!DOCTYPE html>
<html>
<head>
<script src="jquery-3.3.1.js"></script>
<script>
$(document).ready(function(){
$(":checkbox").wrap("<span style='background-color:red'>");
});
</script>
</head>
<body>
<form action="">
<input type="submit">
</form>
</body>
</html>
224
Output for above code
<!DOCTYPE html>
<html>
<head>
<script src="jquery-3.3.1.js"></script>
<script>
$(document).ready(function(){
$(":radio").wrap("<span style='background-color:red'>");
});
</script>
</head>
<body>
225
<form action="">
<input type="submit">
</form>
</body>
</html>
Query traversing, which means "move through", are used to "find" (or select) HTML
elements based on their relation to other elements. Start with one selection and move
through that selection until you reach the elements you desire.
226
The image below illustrates an HTML page as a tree (DOM tree). With jQuery
traversing, you can easily move up (ancestors), down (descendants) and sideways
(siblings) in the tree, starting from the selected (current) element. This movement is
called traversing - or moving through - the DOM tree.
• The <div> element is the parent of <ul>, and an ancestor of everything inside of
it
• The <ul> element is the parent of both <li> elements, and a child of <div>
• The left <li> element is the parent of <span>, child of <ul> and adescendant of
<div>
• The <span> element is a child of the left <li> and a descendant of <ul> and
<div>
• The two <li> elements are siblings (they share the same parent)
• The right <li> element is the parent of <b>, child of <ul> and adescendant of
<div>
• The <b> element is a child of the right <li> and a descendant of <ul> and <div>
227
Traversing the DOM
With jQuery you can traverse up the DOM tree to find ancestors of an element.
Three useful jQuery methods for traversing up the DOM tree are:
• parent()
• parents()
• parentsUntil()
The parent() method returns the direct parent element of the selected element.
Example
<!DOCTYPE html>
<html>
<head>
<style>
.ancestors * {
display: block;
228
border: 2px solid lightgrey;
color: lightgrey;
padding: 5px;
margin: 15px;
</style>
<script src="jquery-3.3.1.js"></script>
<script>
$(document).ready(function(){
});
</script>
</head>
<body>
<div class="ancestors">
<ul>ul (grandparent)
<span>span</span>
</li>
</ul>
229
</div>
<span>span</span>
</p>
</div>
</div>
</body>
</html>
230
The parents() method returns all ancestor elements of the selected element, all the way
up to the document's root element (<html>).
<!DOCTYPE html>
<html>
<head>
<script src="jquery-3.3.1.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("li").each(function(){
alert($(this).text())
});
});
});
</script>
</head>
<body>
<ul>
<li>Coffee</li>
<li>Milk</li>
231
<li>Soda</li>
</ul>
</body>
</html>
The parentsUntil() method returns all ancestor elements between two given arguments.
Example
<!DOCTYPE html>
<html>
<head>
<style>
.ancestors * {
232
display: block;
color: lightgrey;
padding: 5px;
margin: 15px;
</style>
<script src="jquery-3.3.1.js"></script>
<script>
$(document).ready(function(){
});
</script>
</head>
<ul>ul (grandparent)
<span>span</span>
</li>
</ul>
</div>
</body>
</html>
233
Output for above code
With jQuery you can traverse down the DOM tree to find descendants of an element.
Two useful jQuery methods for traversing down the DOM tree are:
• children()
• find()
The children() method returns all direct children of the selected element.
234
This method only traverse a single level down the DOM tree.
Example
<!DOCTYPE html>
<html>
<head>
<style>
.descendants * {
display: block;
color: lightgrey;
padding: 5px;
margin: 15px;
</style>
<script src="jquery-3.3.1.js"></script>
<script>
$(document).ready(function(){
});
</script>
</head>
235
<body>
<p>p (child)
<span>span (grandchild)</span>
</p>
<p>p (child)
<span>span (grandchild)</span>
</p>
</div>
</body>
</html>
The find() method returns descendant elements of the selected element, all the way
down to the last descendant.
236
Example
<!DOCTYPE html>
<html>
<head>
<style>
.descendants * {
display: block;
color: lightgrey;
padding: 5px;
margin: 15px;
</style>
<script src="jquery-3.3.1.js"></script>
<script>
$(document).ready(function(){
});
</script>
</head>
<body>
<p>p (child)
<span>span (grandchild)</span>
237
</p>
<p>p (child)
<span>span (grandchild)</span>
</p>
</div>
</body>
</html>
1. next() Method
The jQuery next() method is used to get the immediately following sibling i.e. the next
sibling element of the selected element.
<!DOCTYPE html>
238
<html>
<head>
239
2. nextAll() Method
The jQuery nextAll() method is used to get all following siblings of the selected element.
Example
<!DOCTYPE html>
<html>
<head>
240
<div >
<h1>Hello World</h1>
<p>This is a <em>simple paragraph</em>.</p>
<p>This is another paragraph.</p>
<ul>
<li>Item One</li>
<li>Item Two</li>
</ul>
</div>
</body>
</html>
3. nextUntil() Method
The jQuery nextUntil() method is used to get all the following siblings up to but not
including the element matched by the selector. In simple words we can say it returns all
the next siblings elements between two given elements in a DOM hierarchy.
Example
<!DOCTYPE html>
241
<html>
<head>
242
4. prev() Method
The jQuery prev() method is used to get the immediately preceding sibling i.e. the
previous sibling element of the selected element.
Example
<!DOCTYPE html>
<html >
<head>
<meta charset="utf-8">
<title>Selecting the Previous Sibling Element in jQuery</title>
<style type="text/css">
.highlight{
background: yellow;
}
</style>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("ul").prev().addClass("highlight");
});
</script>
</head>
<body>
243
<div>
<h1>Hello World</h1>
<p>This is a <em>simple paragraph</em>.</p>
<p>This is another paragraph.</p>
<ul>
<li>Item One</li>
<li>Item Two</li>
</ul>
</div>
</body>
</html>
5. prevAll() Method
The jQuery prevAll() method is used to get all preceding siblings of the selected
element.
Example:
<!DOCTYPE html>
<html lang="en">
244
<head>
<meta charset="utf-8">
<title>Selecting All the Preceding Sibling Elements in jQuery</title>
<style type="text/css">
.highlight{
background: yellow;
}
</style>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("ul").prevAll().addClass("highlight");
});
</script>
</head>
<body>
<div class="container">
<h1>Hello World</h1>
<p>This is a <em>simple paragraph</em>.</p>
<p>This is another paragraph.</p>
<ul>
<li>Item One</li>
<li>Item Two</li>
</ul>
</div>
</body>
</html>
245
6. prevUntil() Method
The jQuery prevUntil() method is used to get all the preceding siblings up to but not
including the element matched by the selector. In simple words we can say it returns all
the previous siblings elements between two given elements in a DOM hierarchy.
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style type="text/css">
.highlight{
background: yellow;
</style>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("ul").prevUntil("h1").addClass("highlight");
});
</script>
</head>
<body>
<div class="container">
<h1>Hello World</h1>
246
<p>This is a <em>simple paragraph</em>.</p>
<ul>
<li>Item One</li>
<li>Item Two</li>
</ul>
</div>
</body>
</html>
jQuery gives us the means to easily manipulate an element's attributes and gives us
access to the element so that we can also change its properties.
247
Get Attribute Value
The attr() method can be used to either fetch the value of an attribute from the first
element in the matched set or set attribute values onto all matched elements.
Applying Styles
The addClass( classes ) method can be used to apply defined style sheets onto all
the matched elements. You can specify multiple classes separated by space.
Attribute Methods
html( ) The html( ) method gets the html contents of the first matched
element.
Syntax
selector.html( )
248
Example HTML Method
<html>
<head>
<script src="jquery-3.3.1.js"></script>
$(document).ready(function() {
$("#pid2").html( content );
});
</script>
<style>
.red { color:red; }
.green { color:green; }
</style>
</head>
<body>
</body>
</html>
249
Example of Text Method
<html>
<head>
src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
$(document).ready(function() {
$("#divid").text(title);
});
</script>
</head>
250
<body>
<div>
<div id = "divid"></div>
</div>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
251
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button.insert-after").click(function(){
$("h1").after('<img src="Z:\DHTML\jquery\programs\attribute\arrow.png"
alt="Symbol">');
});
$("button.insert-before").click(function(){
$("h1").before('<img src="Z:\DHTML\jquery\programs\attribute\arrow2.png"
alt="Symbol">');
});
});
</script>
<style type="text/css">
h1{
body{
text-align: center;
</style>
</head>
252
<body>
<h1>Hello World</h1>
<hr>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
253
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("p").prepend("<strong>Note:</strong> ");
$("button").click(function(){
});
});
</script>
</head>
<body>
<div id="container">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam eu sem tempor, varius
quam at, luctus dui. Mauris magna metus, dapibus nec turpis vel, semper malesuada
ante.</p>
</div>
</body>
</html>
254
Output for above code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style type="text/css">
.container{
padding: 10px;
background: #f0e68C;
</style>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
255
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$("p.hint").remove();
});
});
</script>
</head>
<body>
<div class="container">
<h1>Hello World!</h1>
</div>
</body>
</html>
256
14.4 JQuery Effects
The hide() method simply sets the inline style display:none for the selected elements.
Conversely, the show() method restores the display properties
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<style type="text/css">
p{
257
padding: 15px;
background: #F0E68C;
</style>
<script type="text/javascript">
$(document).ready(function(){
$(".hide-btn").click(function(){
$("p").hide();
});
$(".show-btn").click(function(){
$("p").show();
});
});
</script>
</head>
<body>
<p>This is a paragraph.</p>
</body>
</html>
258
Output for above code
Example-2
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<style type="text/css">
p{
padding: 15px;
background: #F0E68C;
</style>
259
<script type="text/javascript">
$(document).ready(function(){
$(".hide-btn").click(function(){
$("p.normal").hide();
$("p.fast").hide("fast");
$("p.slow").hide("slow");
$("p.very-fast").hide(50);
$("p.very-slow").hide(2000);
});
$(".show-btn").click(function(){
$("p.normal").show();
$("p.fast").show("fast");
$("p.slow").show("slow");
$("p.very-fast").show(50);
$("p.very-slow").show(2000);
});
});
</script>
</head>
<body>
260
<p class="very-fast">This paragraph will show/hide with very fast speed.</p>
</body>
</html>
toggle() Method
The jQuery toggle() method show or hide the elements in such a way that if the element
is initially displayed, it will be hidden; if hidden, it will be displayed (i.e. toggles the
visibility).
Example
<!DOCTYPE html>
261
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<style type="text/css">
p{
padding: 15px;
background: #F0E68C;
</style>
<script type="text/javascript">
$(document).ready(function(){
$(".toggle-btn").click(function(){
$("p").toggle();
});
});
</script>
</head>
<body>
<p>This is a paragraph.</p>
</body>
262
</html>
Example-2
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<style type="text/css">
p{
padding: 15px;
background: #F0E68C;
</style>
263
<script type="text/javascript">
$(document).ready(function(){
$(".toggle-btn").click(function(){
$("p.normal").toggle();
$("p.fast").toggle("fast");
$("p.slow").toggle("slow");
$("p.very-fast").toggle(50);
$("p.very-slow").toggle(2000);
});
});
</script>
</head>
<body>
</body>
</html>
264
fadeIn() (show)and fadeOut()(hide) Methods
You can use the jQuery fadeIn() and fadeOut() methods to display or hide the HTML
elements by gradually increasing or decreasing their opacity.
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example of jQuery Fade-In and Fade-Out Effects</title>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<style type="text/css">
p{
padding: 15px;
background: #DDA0DD;
}
</style>
<script type="text/javascript">
$(document).ready(function(){
// Fadeing out displayed paragraphs
$(".out-btn").click(function(){
$("p").fadeOut();
});
265
$(".in-btn").click(function(){
$("p").fadeIn();
});
});
</script>
</head>
<body>
<button type="button" class="out-btn">Fade Out Paragraphs</button>
<button type="button" class="in-btn">Fade In Paragraphs</button>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
</body>
</html>
Example-2
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example of jQuery Fade-In and Fade-Out Effects with Different Speeds</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<style type="text/css">
p{
266
padding: 15px;
background: #DDA0DD;
}
</style>
<script type="text/javascript">
$(document).ready(function(){
// Fading out displayed paragraphs with different speeds
$(".out-btn").click(function(){
$("p.normal").fadeOut();
$("p.fast").fadeOut("fast");
$("p.slow").fadeOut("slow");
$("p.very-fast").fadeOut(50);
$("p.very-slow").fadeOut(2000);
});
267
fadeToggle() Method
The jQuery fadeToggle() method display or hide the selected elements by animating
their opacity in such a way that if the element is initially displayed, it will be fade out; if
hidden, it will be fade in (i.e. toggles the fading effect).
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example of jQuery Fade-Toggle Effect</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<style type="text/css">
p{
padding: 15px;
background: #DDA0DD;
}
</style>
<script type="text/javascript">
$(document).ready(function(){
// Toggles paragraphs display with fading
$(".toggle-btn").click(function(){
268
$("p").fadeToggle();
});
});
</script>
</head>
<body>
<button type="button" class="toggle-btn">Fade Toggle Paragraphs</button>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
</body>
</html>
Example
<!DOCTYPE html>
269
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example of jQuery Slide-Up and Slide-Down Effects</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<style type="text/css">
p{
padding: 15px;
background: #B0C4DE;
}
</style>
<script type="text/javascript">
$(document).ready(function(){
// Slide up displayed paragraphs
$(".up-btn").click(function(){
$("p").slideUp();
});
270
Example-2
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example of jQuery Slide-Up and Slide-Down Effects with Different Speeds</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<style type="text/css">
p{
padding: 15px;
background: #B0C4DE;
}
</style>
<script type="text/javascript">
$(document).ready(function(){
// Sliding up displayed paragraphs with different speeds
$(".up-btn").click(function(){
$("p.normal").slideUp();
$("p.fast").slideUp("fast");
$("p.slow").slideUp("slow");
$("p.very-fast").slideUp(50);
271
$("p.very-slow").slideUp(2000);
});
272
animate() Method
Syntax
The basic syntax of the jQuery animate() method can be given with:
The optional duration parameter specifies how long the animation will run. Durations
can be specified either using one of the predefined string 'slow' or 'fast', or in a number
of milliseconds; higher values indicate slower animations.
The optional callback parameter is a function to call once the animation is complete.
stop() Method
273
The jQuery stop() method is used to stop the jQuery animations or effects currently
running on the selected elements before it completes.
syntax
$(selector).stop(stopAll, goToEnd);
Example-1
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<style type="text/css">
img{
</style>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
274
$("img").animate({
left: 300
});
});
});
</script>
</head>
<body>
<p>
<img src="Z:\DHTML\jquery\programs\effects\images\mushroom.jpg"
alt="Mushroom">
</p>
</body>
</html>
275
Example-2
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<style type="text/css">
.box{
width: 100px;
height: 100px;
background: #9d7ede;
margin-top: 30px;
border-color: #6f40ce;
</style>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$(".box").animate({
width: "300px",
height: "300px",
marginLeft: "150px",
borderWidth: "10px",
276
opacity: 0.5
});
});
});
</script>
</head>
<body>
<div class="box"></div>
</body>
</html>
Example-3
<!DOCTYPE html>
<html>
<head>
277
<title>Example of jQuery Queued Animation</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<style type="text/css">
.box{
width: 100px;
height: 100px;
background: #9d7ede;
margin-top: 30px;
border-color: #6f40ce;
</style>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$(".box")
.animate({width: "300px"})
.animate({height: "300px"})
.animate({marginLeft: "150px"})
.animate({borderWidth: "10px"})
.animate({opacity: 0.5});
});
});
</script>
278
</head>
<body>
<div class="box"></div>
</body>
</html>
Example-4
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
279
<style type="text/css">
.box{
width: 100px;
height: 100px;
background: #9d7ede;
margin-top: 30px;
</style>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$(".box").animate({
top: "+=50px",
left: "+=50px",
width: "+=50px",
height: "+=50px"
});
});
});
</script>
</head>
<body>
280
<p><strong>Note:</strong> Click the "Start Animation" button multiple times to see how
the relative value works.</p>
<div class="box"></div>
</body>
</html>
Events are often triggered by the user's interaction with the web page, such as when a
link or button is clicked, text is entered into an input box or textarea, selection is made in
a select box, key is pressed on the keyboard, the mouse pointer is moved etc.
In some cases, the Browser itself can trigger the events, such as the page load and
unload events.
jQuery enhances the basic event-handling mechanisms by offering the events methods
281
jQuery Event MethodsOrder by Alphabet
This section contains a comprehensive list of event methods belonging to the latest
jQuery JavaScript library. All the methods are grouped into categories.
Mouse Events
Method Description
click() Bind an event handler to be fired when the
element is clicked, or trigger that handler
on an element.
dblclick() Bind an event handler to be fired when the
element is double-clicked, or trigger that
event on an element.
hover() Bind one or two handlers to the selected
elements, to be executed when the mouse
pointer enters and leaves the elements.
mousedown() Bind an event handler to be fired when the
mouse button is pressed within the
element, or trigger that event on an
element.
mouseenter() Bind an event handler to be fired when the
mouse enters an element, or trigger that
handler on an element.
mouseleave() Bind an event handler to be fired when the
mouse leaves an element, or trigger that
handler on an element.
mousemove() Bind an event handler to be fired when the
mouse pointer moves within the element,
or trigger that event on an element.
mouseout() Bind an event handler to be fired when the
mouse pointer leaves the element, or
trigger that event on an element.
mouseover() Bind an event handler to be fired when the
mouse pointer enters the element, or
trigger that event on an element.
282
mouseup() Bind an event handler to be fired when the
mouse button is released within the
element, or trigger that event on an
element.
Keyboard Events
Method Description
keydown() Bind an event handler to be fired when a
key is pressed and the element has
keyboard focus, or trigger that event on an
element.
keypress() Bind an event handler to be fired when a
keystroke occurs and the element has
keyboard focus, or trigger that event on an
element.
keyup() Bind an event handler to be fired when a
key is released and the element has
keyboard focus, or trigger that event on an
element.
Form Events
Method Description
blur() Bind an event handler to be fired when the
element loses keyboard focus, or trigger
that event on an element.
change() Bind an event handler to be fired when the
element's value changes, or trigger that
event on an element.
focus() Bind an event handler to be fired when the
element gains keyboard focus, or trigger
that event on an element.
focusin() Bind an event handler to be fired when the
element, or a descendant, gains keyboard
283
focus.
focusout() Bind an event handler to be fired when the
element, or a descendant, loses keyboard
focus.
select() Bind an event handler to be fired when text
in the element is selected, or trigger that
event on an element.
submit() Bind an event handler to be fired when the
form element is submitted, or trigger that
event on an element.
Document/Browser Events
Method Description
load() Bind an event handler to be fired when the
element finishes loading.
ready() Bind an event handler to be fired when the
DOM is fully loaded.
resize() Bind an event handler to be fired when the
element is resized, or trigger that event on
an element.
scroll() Bind an event handler to be fired when the
window's or element's scroll position
changes, or trigger that event on an
element.
unload() Bind an event handler to be fired when the
user navigates away from the page.
load() Bind an event handler to be fired when
the element finishes loading.
ready() Bind an event handler to be fired when the
DOM is fully loaded.
resize() Bind an event handler to be fired when the
element is resized, or trigger that event on
an element.
284
Example-1
<!DOCTYPE html>
<html>
<head>
<title>Executing a Function on Click Event in jQuery</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<style type="text/css">
p{
padding: 20px;
font: 20px sans-serif;
background: khaki;
}
</style>
<script type="text/javascript">
$(document).ready(function(){
$("p").click(function(){
$(this).slideUp();
});
});
</script>
</head>
<body>
<p>Click on me and I'll disappear.</p>
<p>Click on me and I'll disappear.</p>
<p>Click on me and I'll disappear.</p>
</body>
</html>
285
Example-2
<!DOCTYPE html>
<html>
<head>
286
});
</script>
</head>
<body>
<p>Double-click on me and I'll disappear.</p>
<p>Double-click on me and I'll disappear.</p>
<p>Double-click on me and I'll disappear.</p>
</body>
</html>
Example-3
<!DOCTYPE html>
<html>
<head>
287
p{
padding: 20px;
font: 20px sans-serif;
background: #f2f2f2;
}
p.highlight{
background: yellow;
}
</style>
<script type="text/javascript">
$(document).ready(function(){
$("p").hover(function(){
$(this).addClass("highlight");
}, function(){
$(this).removeClass("highlight");
});
});
</script>
</head>
<body>
<p>Place mouse pointer on me.</p>
<p>Place mouse pointer on me.</p>
<p>Place mouse pointer on me.</p>
</body>
</html>
288
Example-4
<!DOCTYPE html>
<html>
<head>
289
var i = 0;
$('input[type="text"]').keypress(function(){
$("span").text(i += 1);
});
});
</script>
</head>
<body>
<input type="text">
<div>Keypress: <span>0</span></div>
<div><strong>Note:</strong> Enter something inside the input box and see the
result.</div>
</body>
</html>
290
Example-5
<!DOCTYPE html>
<html>
<head>
291
<p>Place mouse pointer on me.</p>
<p>Place mouse pointer on me.</p>
</body>
</html>
bind() Method
The bind() method attaches one or more event handlers for selected elements, and
specifies a function to run when the event occurs.
Syntax
$(selector).bind(event,data,function)
Example
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
292
<script>
$(document).ready(function(){
$("p").bind("click", function(){
alert("The paragraph was clicked.");
});
});
</script>
</head>
<body>
<p>Click me!</p>
</body>
</html>
293
Example-2
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
$(document).ready(function(){
$("p").bind("mouseover mouseout", function(){
$("p").toggleClass("intro");
});
});
</script>
<style>
.intro {
font-size: 150%;
color: red;
}
</style>
</head>
<body>
294
unbind() Method
This method can remove all or selected event handlers, or stop specified functions from
running when the event occurs.
Syntax
$(selector).unbind(event,function,eventObj)
Example:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
$(document).ready(function(){
$("p").click(function(){
$(this).slideToggle();
295
});
$("button").click(function(){
$("p").unbind();
});
});
</script>
</head>
<body>
<p>This is a paragraph.</p>
</body>
</html>
296
14.6Summary
• JQuery Selectors
• JQuery Traversing
• JQuery Attributes
• JQuery Effects
• JQuery Events
297
Unit 15: Introduction to XML
Unit Structure
15.9. Summary
298
15.1 What is XML?
Extensible
XML is extensible. It lets you define your own tags, the order in which they occur, and
how they should be processed or displayed.
Markup
In fact, the elements you’ll create in XML will be very similar to the elements you’ve
already been creating in your HTML documents. However, XML allows you to define
your own set of tags.
Language
• XML is a language that’s very similar to HTML. It’s much more flexible than HTML
because it allows you to create your own custom tags.
• However, it’s important to realize that XML is not just a language.
• XML is a meta-language: a language that allows us to create or define other
languages.
• XML was designed to describe data.
• XML tags are not predefined in XML. You must define your own tags.
• XML is self describing.
• XML uses a DTD (Document Type Definition) to formally describe the data.
The way XML works is that programmers mark-up a text-based document with tags
(similar to HTML tags) that tell what each word, number or group of words represent.
For example, the tag <invoice number> might be used to describe the number of an
invoice.
299
15.2 XML Verses HTML
300
Let us see each component of the above diagram in detail:
XML Declaration
The XML document can optionally have an XML declaration. It is written as below:
Where version is the XML version and encoding specifies the character encoding used
in the document.
301
Syntax Rules for XML declaration
• The XML declaration is case sensitive and must begin with "<?xml>" where "xml"
is written in lower-case.
• If document contains XML declaration, then it strictly needs to be the first
statement of the XML document.
• The XML declaration strictly needs be the first statement in the XML document.
• An HTTP protocol can override the value of encoding that you put in the XML
declaration.
<element>
• text
• attributes
• other elements
• or a mix of the above
Element Syntax: Each XML-element needs to be closed either with start or with end
elements as shown below:
<element>....</element>
<element/>
<?xml version="1.0"?>
<contact-info>
<company>TutorialsPoint
<contact-info>
</company>
302
Following example shows correct nested tags:
<?xml version="1.0"?>
<contact-info>
<company>TutorialsPoint</company>
<contact-info>
Root element: An XML document can have only one root element. For example,
following is not a correct XML document, because both the x and y elements occur at
the top level without a root element:
<x>...</x>
<y>...</y>
<root>
<x>...</x>
<y>...</y>
</root>
Case sensitivity: The names of XML-elements are case-sensitive. That means the name
of the start and the end elements need to be exactly in the same case.
<element></element>
<element />
Attributes
An element can have multiple unique attributes. Attribute gives more information about
XML elements. Syntax Rules for XML Attributes
Syntax
303
An XML attribute has following syntax:
name = "value"
value has to be in double (" ") or single (' ') quotes. Here, attribute1 and attribute2 are
unique attribute labels.
• Same attribute cannot have two values in a syntax. The following example shows
incorrect syntax because the attribute b is specified twice:
• Attribute names are defined without quotation marks, whereas attribute values
must always appear in quotation marks. Following example demonstrates
incorrect xml syntax:
<a b=x>....</a>
In the above syntax, the attribute value is not defined in quotation marks.
Entity References: An entity reference contains a name between the start and the end
delimiters. For example & where amp is name. The name refers to a predefined
string of text and/or markup.
Character References: These contain references, such as A, contains a hash mark
(“#”) followed by a number. The number always refers to the Unicode code of a
character. In this case, 65 refers to alphabet "A".
304
XML Text
The names of XML-elements and XML-attributes are case-sensitive, which means the
name of start and end elements need to be written in the same case.
To avoid character encoding problems, all XML files should be saved as Unicode UTF-8
or UTF-16 files.
Whitespace characters like blanks, tabs and line-breaks between XML-elements and
between the XML-attributes will be ignored.
Some characters are reserved by the XML syntax itself. Hence, they cannot be used
directly. To use them, some replacement-entities are used, which are listed below:
To avoid this error, replace the "<" character with an entity reference:
XML declaration contains details that prepare an XML processor to parse the XML
document.
It is optional, but when used, it must appear in first line of the XML document.
Syntax
<?xml
version="version_number"
305
encoding="encoding_declaration"
standalone="standalone_status"
?>
Each parameter consists of a parameter name, an equals sign (=), and parameter value
inside a quote
XML tags are case sensitive. The tag <Letter> is different from the tag <letter>.
Opening and closing tags must be written with the same case:
<Message>This is incorrect</message>
<message>This is correct</message>
306
<b><i>This text is bold and italic</b></i>
XML elements can have attributes in name/value pairs just like in HTML.
<note date="12/11/2007">
<to>Tove</to>
<from>Jani</from>
</note>
XML does not truncate multiple white-spaces (HTML truncates multiple white-spaces to
one single white-space):
307
15.7 XMLTerminologies
An XML tree starts at a root element and branches from the root to child elements.
<root>
<child>
<subchild>.....</subchild>
</child>
</root>
The terms parent, child, and sibling are used to describe the relationships between
elements.
Parents have children. Children have parents. Siblings are children on the same level
(brothers and sisters).
308
All elements can have text content (Harry Potter) and attributes (category="cooking").
309
Self-Describing Syntax
<bookstore>
<book category="cooking">
The <book> elements have 4 child elements: <title>,< author>, <year>, <price>.
</book>
Namespace Declaration
A Namspace is declared using reserved attributes. Such an attribute name must either
be xmlns or begin with xmlns: shown as below:
<element xmlns:name="description">
Syntax
310
• The URL is the Namespace identifier.
Example
<cont:contact xmlns:cont="contactdetails">
<cont:name>Tanmay Patil</cont:name>
<cont:company>TutorialsPoint</cont:company>
<cont:phone>(011) 123-4567</cont:phone>
</cont:contact><br>
<cont1:contact xmlns:cont1="contactdetails">
<cont1:name>patel</cont1:name>
<cont1:company>tp</cont1:company>
<cont1:phone>s123-4567</cont1:phone>
</cont1:contact>
311
XLink Syntax
In HTML, the <a> element defines a hyperlink. However, this is not how it works in XML.
In XML documents, you can use whatever element names you want
To get access to the XLink features we must declare the XLink namespace. The XLink
namespace is: "http://www.w3.org/1999/xlink".
Example
<?xml version="1.0" encoding="UTF-8"?>
<homepages xmlns:xlink="http://www.w3.org/1999/xlink">
<homepage xlink:type="simple" xlink:href="http://www.w3schools.com">Visit
W3Schools</homepage>
<homepage xlink:type="simple" xlink:href="http://www.w3.org">Visit
W3C</homepage>
</homepages>
XPointer
Example
312
XPath
XPath is a syntax for defining parts of an XML document
<emp>
<designation>consultant</designation>
<emp>
<emp_no>100</emp_no>
<emp_name>atul kahate</emp_name>
</emp>
</emp>
/emp/designation/emp/emp_name
Xpath
XML Schema
It is used to describe and validate the structure and the content of XML data.
Syntax
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<?xml version="1.0" encoding="UTF-8" ?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
...
</xs:schema>
313
We have to define the "shiporder" element.
This element has an attribute and it contains other elements, therefore we consider it as
a complex type.
<xs:element name="shiporder">
<xs:complexType>
<xs:sequence>
...
</xs:sequence>
</xs:complexType>
</xs:element>
Example
The basic idea behind XML Schemas is that they describe the legitimate format that an
XML document can take.
XHTML
314
15.9 Summary
In this chapter you have learned about:
• What is XML
• XML Syntax
• XML References
• XML Declaration
• XML Comments
• XML Terminologies
• XML Namespace
315