Introduction to HTML Basics and Structure
Introduction to HTML Basics and Structure
1. Introduction to HTML
It forms the building blocks of all websites and is complemented by CSS for
style and JavaScript for interactivity.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>Welcome to My Webpage</h1>
1
</body>
</html>
Features of HTML
HTML History
Currently, we are using HTML5, which is the latest and most advanced
version of HTML.
HTML was initially created by Tim Berners-Lee in 1991 as a way to share and
structure documents on the web.
The first-ever version was HTML 1.0, a basic and limited version. However,
the first standardized version, HTML 2.0, was published in 1995, laying the
foundation for web development as we know it today
2
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 Element and HTML Tags are related but distinct. An HTML element is
the complete structure, including the opening tag, content (if any), and the
closing tag (if applicable).
On the other hand, A tag is the actual keyword or name enclosed in angle
brackets (< >) that tells the browser what kind of content to expect.
3
2. HTML Tag Basics
Every HTML document begins with a document type declaration, setting the
foundation for the webpage. This section introduces basic HTML tags that
structure the page, such as <head>, <body>, and <title>. Although this is not
mandatory, it is a good convention to start the document with the below-
mentioned tag.
4
<h1> to These are a <h1>..</h1> <h1>This h1 tag</h1>
<h6> group of to <h6>..</h6> <h6>This h6 tag</h6>
heading tags
used to create
heading in a
webpage
Types of Tags:
Paired Tags:
An HTML tag is known as a paired tag when the tag consists of an opening
tag and a closing tag as its companion tag. An HTML Paired tag starts with
an opening tag: the tag name enclosed inside the angle brackets; for example,
a paragraph opening tag is written as ‘<p>’. The content follows the opening
tag, which ends with an ending tag: the tag name starting with a forward
slash; for example, an ending paragraph tag is written as ‘</p>’. The first tag
can be referred to as the ‘Opening Tag’, and the second tag can be called
Closing Tag.
Example 1:
Output:
NOTE: Here, the opening tag is, and the closing tag is </p>.
Example 2:
Output:
5
NOTE: These paired tags are also called Container Tags.
Unpaired Tags:
An HTML tag is called an unpaired tag when the tag only has an opening tag
and does not have a closing tag or a companion tag. The Unpaired HTML tag
does not require a closing tag; an opening tag is sufficient in this type.
Unpaired tags are sometimes also named as Standalone Tags or Singular Tags
since they do not require a companion tag.
Example:
<hr>
Output:
NOTE: Here, the <hr> is the unpaired tag used to create a horizontal line. In
older versions, you might see hr tag written as <hr/> instead of <hr>. These
tags are also called Empty Tag.
Self-Closing Tags are those HTML tags that do not have a partner tag, where
the first tag is the only necessary tag that is valid for the formatting. The main
and important information is contained WITHIN the element as its attribute.
An image tag is a classic example of a self-closing tag.
Example:
6
Note: In the older versions, the self-closing tags use a ‘forward slash’ before
the ending or closing ‘greater than’ sign/symbol, as written below:
The basic structure of an HTML page is shown below. It contains the essential
building-block elements (i.e. doctype declaration, HTML, head, title, and body
elements) upon which all web pages are created.
7
<head> – The head tag contains the “behind the scenes” elements for a
webpage. Elements within the head aren’t visible on the front end of a
webpage. Typical elements inside the <head> include:
o <title>: Defines the title displayed on the browser tab.
o <meta>: Provides information like the character set or viewport
settings.
o <link>: Links external stylesheets or resources.
o <style>: Embeds internal CSS styles.
o <script>: Embeds JavaScript for functionality.
<title> – The title is what is displayed on the top of your browser when
you visit a website and contains the title of the webpage that you are
viewing.
<h2> – The <h2> tag is a second-level heading tag.
<p>– The <p> tag represents a paragraph of text.
<body> – The body tag is used to enclose all the visible content of a
webpage. In other words, the body content is what the browser will
show on the front end.
Example:
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
8
<!-- Main content of website -->
<h1>GeeksforGeeks</h1>
</body>
</html>
9
4. Adding Comments
HTML Comments are text in an HTML document that is not displayed by the
browser. They allow you to leave notes and explanations directly in the code,
which can be especially helpful during the development process or when you
need to make future updates.
To add a comment in your HTML code, you enclose the text you want to hide
from display within <!-- and -->
<!-- This is a comment and will not be displayed on the webpage -->
In this example:
The text within the <!-- and --> tags will not appear on the webpage.
These comments can include reminders, warnings, or explanations
about the code, which can be useful for anyone reading or editing the
HTML document.
There are two main ways to write comments in HTML: single-line and multi-
line comments. Both use the same basic syntax but differ in how they are
implemented
10
Uses of HTML Comments:
Text in HTML is displayed using various tags that define the structure, style,
and organization of the content. The most common tags used to control text
are <p>, <br>, <h1> to <h6>, <b>, <i>, <u>, and others.
Example:
The <br> tag is used to create a line break within text without starting
a new paragraph.
11
Unlike the <p> tag, the <br> tag does not add any extra space and
continues the same paragraph from a new line.
Example:
<p>This is an example of text with a line break.<br>This line will appear right
below without extra spacing.</p>
6. Emphasizing Text
HTML provides several tags to emphasize text, each serving a specific purpose:
12
i.) Bold (<b> and <strong> Tags):
The <b> tag makes text bold, but it does not add any extra importance
to the text.
The <strong> tag also makes text bold but indicates that the text is of
strong importance.
Example:
Example:
The <mark> tag highlights text with a background color, usually yellow,
to indicate relevance.
Example:
The <small> tag makes the text smaller than the surrounding text.
Example:
13
v.) Subscript and Superscript (<sub> and <sup> Tags):
The <sub> tag displays text as subscript (below the text line).
The <sup> tag displays text as superscript (above the text line).
Example:
Example:
You can also combine these tags to create text with multiple forms of
emphasis.
Example:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
14
<p>This text is <b>bold</b> and <i>italic</i>, with <sub>subscript</sub>
and <sup>superscript</sup> elements.</p>
</body>
</html>
Output:
15
7. Headings and Horizontal Rules
HTML Headings are used to define the content hierarchy and structure of a
webpage. They range from <h1> to <h6>, with <h1> being the most important
heading and <h6> the least important. Proper use of headings helps improve
readability, SEO, and accessibility.
<!DOCTYPE html>
<html>
<body>
</body>
</html>
16
Output:
Represents the primary focus of the page, usually used for the main
title.
Use only one <h1> tag per page for the best SEO practices.
Makes it clear to both users and search engines what the main topic is.
<h2> – Subheadings
17
<h3> is used for subsections under <h2>, while <h4> to <h6> are used
for additional, less important subdivisions.
<h6> defines the least important heading.
Example: Here’s how you can apply basic styles to HTML heading tags:
<!DOCTYPE html>
<html>
<body>
<h1>H1 Heading</h1>
</body>
</html>
Output:
18
ii.) Horizontal Rule (<hr>):
The <hr> tag in HTML is used to create a horizontal rule or line that visually
separates content.
NOTE: It is a self-closing tag and does not require an end tag. It also supports
the Global Attributes and Event Attributes.
<!DOCTYPE html>
<html>
<body>
<p>
</p>
<hr>
<p>
</p>
</body>
</html>
Output:
19
8. Lists
1. Unordered Lists
2. Ordered Lists
3. Description Lists
<!DOCTYPE html>
<html>
<head>
<title>GFG</title>
</head>
<body>
<ul>
<li>Web Technology</li>
<li>Programming Languages</li>
</ul>
20
<ol>
<li>Array</li>
<li>Linked List</li>
<li>Stacks</li>
<li>Queues</li>
<li>Trees</li>
<li>Graphs</li>
</ol>
</body>
</html>
Output:
21
HTML List Tags
Tag Description
<ul> Defines an unordered list
<ol> Defines an ordered list
<li> Defines a list item
<dl> Defines a description list
<dt> Defines a term in a description list
<dd> Details the term in a description list
The unordered list items are marked with bullets, also known as bulleted lists.
An unordered list starts with the <ul> tag, and each list item begins with the
<li> tag.
Syntax:
Attribute: This tag contains two attributes which are listed below:
<!DOCTYPE html>
<html>
<body>
<h2>Grocery list</h2>
<ul>
<li>Bread</li>
22
<li>Eggs</li>
<li>Milk</li>
<li>Coffee</li>
</ul>
</body>
</html>
Output:
In an ordered list, all list items are marked with numbers by default. An
ordered list starts with the <ol> tag, and each list item begins with the <li>
tag.
Syntax:
<ol>
<li>Item1</li>
<li>Item2</li>
<li>Item3</li>
</ol>
Attributes:
23
start: It defines from which number or alphabet the order will start.
type: It defines which type(1, A, a, I, and i) of the order you want in
your list of numeric, alphabetic, or roman numbers.
Example: This example illustrates the use of the reverse attribute, control list
counting & type attribute.
<!DOCTYPE html>
<html>
<head>
<title>HTML ol tag</title>
</head>
<body>
<h3>HTML ol tag</h3>
<p>reversed attribute</p>
<ol reversed>
<li>HTML</li>
<li>CSS</li>
<li>JS</li>
</ol>
<p>start attribute</p>
<ol start="5">
<li>HTML</li>
<li>CSS</li>
<li>JS</li>
</ol>
24
<p>type attribute</p>
<ol type="i">
<li>HTML</li>
<li>CSS</li>
<li>JS</li>
</ol>
</body>
</html>
Output:
25
iii.) Description List:
A description list is a list of terms, with a description of each term. The <dl>
tag defines the description list, the <dt> tag defines the term name, and the
<dd> tag describes each term.
Syntax:
<!DOCTYPE html>
<html>
<body>
<dl>
<dt>Coffee</dt>
<dt>Milk</dt>
</dl>
</body>
</html>
Output:
26
9. Font Size, Face, and Color (Deprecated in HTML5)
The HTML <font> Tag plays an important role in the web page to create an
attractive and readable web page. The font tag is used to change the color,
size, and style of a text and it was used in HTML4. The base font tag is used
to set all the text to the same size, color, and face.
<!DOCTYPE html>
<html>
<body>
</font>
</body>
</html>
Output:
Syntax:
27
Font Attributes
Font Size
Font Type
Font Color
The Font size attribute is used to adjust the size of the text in the HTML
document using a font tag with the size attribute. The range of size of the font
in HTML is from 1 to 7 and the default size is 3.
<!DOCTYPE html>
<html>
<body>
<font size="7">GFG!</font>
</body>
</html>
28
Output:
The Font type can be set by using face attribute with font tag in HTML
document. But the fonts used by the user need to be installed in the system
first.
<!DOCTYPE html>
<html>
<body>
</font><br />
Verdana!!
</font><br />
29
<font face="Comic sans MS" size=" 6">
</font><br />
WildWest!!
</font><br />
Bedrock!!
</font><br />
</body>
</html>
Output:
30
iii.) Font Color
The Font color is used to set the text color using a font tag with the color
attribute in an HTML document. Color can be specified either with its name
or with its hex code.
<!DOCTYPE html>
<html>
<body>
</body>
</html>
Output:
i.) Alignment:
HTML align Attribute in HTML is used to specify the alignment of the text
content of The Element. This attribute is used in all elements. The Align
attribute can also be set using the CSS property “text-align: ” or in <img>
“vertical-align: “. For horizontal alignment, use align with values like “left,”
“center,” or “right” within appropriate tags.
NOTE: The align attribute is deprecated in HTML5, and styles should be used
via CSS for better practices.
31
Syntax:
Attribute Values:
Example 1: This example shows the use of the align attribute with an
example.
<!DOCTYPE html>
<html>
<head>
<title>
</title>
</head>
<body>
<h1>GFG</h1>
<p align="left">
</p>
<p align="center">
32
center align content
</p>
<p align="right">
</p>
</body>
</html>
Output:
Example 2: This example shows the use of the align attribute with another
example.
<!DOCTYPE html>
<html>
<head>
<title>align Attribute</title>
</head>
<body>
<h1>GFG</h1>
<h2>
33
div align Attribute
</h2>
<div align="center">
div align="center"
</div>
<div align="left">
div align="left"
</div>
<div align="right">
div align="right"
</div>
<div align="justify">
div align="justify"
</div>
</body>
</html>
Output:
34
ii.) Links:
HTML Links, also known as hyperlinks, are defined by the <a> tag in HTML,
which stands for “anchor.” These links are essential for navigating between
web pages and directing users to different sites, documents, or sections within
the same page.
The basic attributes of the <a> tag include href, title, and target, among
others.
<!DOCTYPE html>
<html>
<head>
<title>HTML Links</title>
</head>
<body>
</body>
</html>
35
Output:
Target Attribute
The target attribute in the <a> tag specifies where to open the linked
document. It controls whether the link opens in the same window, a new
window, or a specific frame.
36
Attribute Description
_blank Opens the linked document in a new window or tab.
_self Opens the linked document in the same frame or window as
the link. (Default behavior)
_parent Opens the linked document in the parent frame.
_top Opens the linked document in the full body of the window.
framename Opens the linked document in a specified frame. The frame’s
name is specified in the attribute.
11. Tables
HTML Tables allow you to arrange data into rows and columns on a web page,
making it easy to display information like schedules, statistics, or other
structured data in a clear format.
HTML Table
An HTML table is created using the <table> tag. Inside this tag, you use
Each <tr> represents a row, and within each row, <th> or <td> tags represent
the cells in that row, which can contain text, images, lists, or even another
table.
37
HTML Table Code Example
<!DOCTYPE html>
<html>
<body>
<table>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>
<tr>
<td>Priya</td>
<td>Sharma</td>
<td>24</td>
</tr>
<tr>
<td>Arun</td>
<td>Singh</td>
<td>32</td>
</tr>
<tr>
<td>Sam</td>
<td>Watson</td>
38
<td>41</td>
</tr>
</table>
</body>
</html>
Output:
In this example:
<table>: This tag starts the table. Everything between the opening
<table> and closing </table> tags makes up the table.
<tr>: Stands for “table row”. Each <tr> tag defines a row in the table.
<th>: Stands for “table header”. It’s used for the headers of the
columns. In this case, “Firstname“, “Lastname“, and “Age” are headers.
Text in <th> tags is usually bold and centered by default.
<td>: Stands for “table data”. This tag is used for actual data cells under
each column. For instance, “Priya” is the data under the “Firstname”
header, “Sharma” under the “Lastname“, and “24” under the “Age“.
The first <tr> has three <th> elements, setting up the column titles.
The subsequent <tr> tags each contain three <td> elements,
representing the data for each person listed in the table.
When this HTML code is rendered in a web browser, it will display a table with
four rows (one header row plus three data rows) and three columns
(Firstname, Lastname, Age), showing the names and ages of Priya, Arun, and
Sam.
39
Tags used in HTML Tables
<!DOCTYPE html>
<html>
<body>
<table>
40
<tr>
<th>Book Name</th>
<th>Author Name</th>
<th>Genre</th>
</tr>
<tr>
<td>Markus Zusak</td>
<td>Historical Fiction</td>
</tr>
<tr>
<td>Holly Black</td>
<td>Fantasy</td>
</tr>
<tr>
<td>Psychological Fiction</td>
</tr>
</table>
</body>
</html>
41
Output:
12. Frames
HTML <frame> tag is used to divide web browser windows into multiple
sections, each capable of loading content independently. This is achieved
using a collection of frames within a frameset tag.
<!DOCTYPE html>
<html>
<body>
<frame name="top"
src="./[Link]" />
<frame name="main"
src="./[Link]" />
<frame name="bottom"
src="./[Link]" />
<noframes>
</noframes>
</frameset>
42
</body>
</html>
The above example basically used to create three horizontal frames i.e. top,
middle and bottom using row attribute of frameset tag and the noframe tag is
used for those browser who doesn’t support noframe.
Syntax
<frame src="[Link]">
<frame src="[Link]">
</frameset>
When you use frameset you split the visual real estate of a browser window
into multiple frames. Each frame has it’s own contents and the content in one
don’t spill into the next.
An iframe, on the other hand, embeds a frame directly inline with the other
elements of a webpage.
Create Frames
While frames should not be used for new websites, learning how to use frames
can be beneficial for webmasters who are managing older websites.
43
The Basic Idea Behind Frames
Let’s look at a few examples of how this works. First we need a few HTML
documents to work with. Let’s create four different HTML documents. Here’s
what the first will contain:
<!DOCTYPE html>
<html>
<body>
<h1>Frame 1</h1>
</body>
</html>
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.
44
Here’s what our HTML markup looks like.
<!DOCTYPE html>
<html>
<frameset cols="*,*,*,*">
<frame src="../file_path/frame_1.html">
<frame src="frame_2.html">
<frame src="frame_3.html">
<frame src="frame_4.html">
</frameset>
</html>
Output:
Rows of frames can be created by using the rows attribute rather than the
cols attribute as shown in the HTML below.
45
<!DOCTYPE html>
<html>
<frameset rows="*,*,*,*">
<frame src="frame_1.html">
<frame src="frame_2.html">
<frame src="frame_3.html">
<frame src="frame_4.html">
</frameset>
</html>
Output:
46
Mixing Columns and Rows
Columns and rows of frames can both appear on the same webpage by nesting
one frameset inside of another. To do this, we first create a frameset and then
nest a child frameset within the parent element. Here’s an example of how we
could nest two rows within a set of three columns.
<frameset cols="*,*,*">
<frameset rows="*,*">
<frame src="frame_1.html">
<frame src="frame_2.html">
</frameset>
<frame src="frame_3.html">
<frame src="frame_4.html">
</frameset>
Output:
47
One more way to create a combination of rows and columns is to define a grid
of columns and rows in a single frameset. For example, if you wanted a grid
of four equally sized frames, you could use the following code.
<frame src="frame_1.html">
<frame src="frame_2.html">
<frame src="frame_3.html">
<frame src="frame_4.html">
</frameset>
Output:
48
UNIT – 2
Before beginning to design a website a user has to be clear about what web
designing is. It is the art of making websites look and feel good to the user
and providing easy access to the website features to the client. It focuses on
improving the user experience rather than development.
The following are the types in which you can do Web Design:
49
Flat Design: Minimalist approach characterized by clean, simple
elements, vibrant colors, and absence of textures or gradients.
Neuromorphic Design: Mimics physical interactions and textures,
creating interfaces that blend realism with digital functionality.
Minimalism Design: Focuses on stripping away unnecessary elements,
favoring simplicity, clean lines, and ample white space for an
uncluttered user experience.
There are many types of Web Graphics but let us understand only the most
used Web Graphics.
50
effortless to recognize and process than words but also easier to recall.
There are many image formats such as jpg/jpeg, png, etc.
Videos: Video can be part of the website UI or be used to convey
additional information that can’t be conveyed using text or images. But
videos can slow down the site and take much more time to load than
any other graphic so it’s better to embed video from other platforms.
Some video formats are mkv, mp4, etc.
Animations: We can use animations such as GIF in the website or code
directly in the site using CSS, JSS or any other technology. Animation
can be very helpful to boost the UI look and feel. Clever use of animation
make the user experience must better and worth remembering. Micro
interactions are commonly used animation in the websites.
SVG (Scalable Vector Graphics): One of the most popular format used
in the website to display icon or any scalable graphics. It is because the
width and height of the graphic can be change to any size which is good
for a responsive design. If we want to make our page responsive then
raster images should be changes to SVG if possible.
Logo: A SVG or image used in the sites to represent brand identity. A
logo if very important for the site because the user can forget the site
name or URL but most of the time user will remember the logo. It better
to create a logo that matches the site name or brand name.
51
Benefits of Using Web Graphics
Web Graphics use in not only limited to websites visual appeal but it is used
for many other reasons:
Brand Image: We can use logo, banner, videos to increase the brand
identify and its goals. Graphics can be used to sell the brands products.
We always want user to revisit our website so incepting the brand logo
helps a lot. Wherever it is appropriate we must use brand logo and
imagery.
User Interactions: A button designed to look different is a guaranteed
method to attract attention. User can also get the idea which button is
what based on the looks thus increasing instant response from the
user. A good-looking button or micro interactions always provide a good
user experience but overwhelming amount of it can cause
repercussions.
SEO (Search Engine Optimization): A site with moderate use of
graphics can result in high page rank and can bring more traffic to the
page. Nowadays crawlers are design to parse the pages as closely as a
normal users would so, adding graphics increases the chance to show
up in the search results.
Promotion: We can use graphics to promote products or put
advertisement in the site. Most websites are filled with adds and these
add maximum of the time used pictures to advertise. This pictorial adds
are easy to load and very easily catch the attention of the users.
Scalable: Some graphics are device independent and can be use in site
used in different devices with different width and height. For a
responsive design its better to use SVG as it is scalable and take up
very less size when compare to a raster image of same width and height.
52
Comparison Between Graphic Design and Web Design
53
2. Work Efficiently with Images in Web Pages
First, we will understand why images are being used in web design, The
following are reasons we use images for
Benefits in SEO: If you use well-optimized images they are good points
for website SEO and also users will spend more time on the website if
you use engaging images.
Visual Communication: Images explain very complex things in a
simple way. Instead of using lengthy descriptions, you can use images
or drawings. for example, e-commerce websites have different angle
images of their products so that users can choose.
Brand Identity: You can create your brand identity using eye-catching
icons and logos for your websites. Images are shared very often on social
media and google instead of texts.
Easy Navigation: Images can be used to guide users through a
website's content. They can serve as navigation elements, such as icons
or buttons, helping users find what they're looking for or prompting
specific actions.
54
Sense of Trust: High-quality front and background images help build
a sense of trust while if you do not images or use bad-quality images
people will start thinking your site is fake or boring to look at.
Now after choosing the right image, its time to optimise the image placement
in your web design. Following aspects should be considered for optimising
image placement.
55
Alignment: Images should be aligned properly with other elements of
webpage. There should not be gaps between that would disrupt the
readibitlity of page You can use CSS properties like float, display,
position, margin, padding, and flexbox to control the alignment of your
images.
Balance: There should be a proper balance between images and text of
webpage. There should not be like lot of images and less text or lot of
text but no images. You should aim for a harmonious and proportional
distribution of visual weight and white space on your web page.
Hierarchy: The images should be arranged accordingly on page, for ex.
you should place the images which are very important content above in
page while use less important images below. Because showing less
important images which distract users. You can use various techniques
such as proper scaling, colors, shapes and use of animation to create
visual hierarchy of images
If we found right image and right place for it. Then the third step is to make
is easily accessible to users. For you consider following things
Alt Text: It means alternative text, it is shown in the case the image
does not open or fails to open. It should represent he content of image
in form of text. Its also very good for seo, because it helps understanding
the search engine what the image is about?
Captions: The images should have captions that provide additional
information or context about the image content to users who can see
them. Captions are also useful for SEO, as they can include keywords
and phrases that relate to your content.
Fixing problems: You should prevent and fix the errors which are
causing your images fail to open, like sometimes images does not open
because the size of image is too big, sometimes its on server which have
problem.
56
Benefits of Efficient Placement of Images
Use of high quality, relevant images at good place on page will grab
users attention in first look and will be memorable for them.
Clear relevant images clarify concepts when combined with images.
Good image placement ensures a balanced layout.
Images enhance storytelling by illustrating concepts or narratives.
Sequential images can guide users through a story or process.
High-resolution images in the wrong places can slow down your
website's loading time, resulting in a poor user experience and potential
loss of visitors But the good placement do exactly opposite
Things to Avoid
57
3. Image Maps
An HTML Image Map is a type of image that contains one or more clickable
areas. These clickable areas, known as “hotspots,” are defined using
coordinates on the image. Each hotspot can link to different URLs or trigger
different actions when clicked. Image maps are often used in web applications
where images represent navigational elements, such as maps, diagrams, or
complex graphics.
<map name="imagemap">
58
</map>
Where:
An image map works on an image using <map> and <area> elements. Each
<area> element defines a clickable region on the image using shape attributes
(like rect, circle, poly) and coordinates.
The <area> tag within a <map> tag defines the clickable regions of the image
map. You can create different shapes, including rectangles, circles, and
polygons.
Rectangular Area
To define a rectangular clickable area, use the rect shape with four
coordinates: top-left corner (x1, y1) and bottom-right corner (x2, y2).
59
<area shape="rect" coords="34,44,270,350" href="[Link]" alt="Rectangle
Link">
Circular Area
To create a circular clickable area, use the circle shape with three values:
center point (x, y) and radius.
Polygonal Area
For more complex shapes, use the poly shape with multiple coordinates
defining each point of the polygon.
Let’s create a simple image map where we use rectangular areas to create
clickable sections.
<html>
<head>
</head>
<body>
<img src="[Link]
content/uploads/20190227165729/[Link]"alt="" width="300"
height="119" class="aligncenter size-medium wp-image-910965"
usemap="#shapemap" />
<map name="shapemap">
60
href="[Link]
content/uploads/20190227165802/[Link]" alt="Triangle">
href="[Link]
content/uploads/20190227165934/[Link]" alt="Circle">
href="[Link]
content/uploads/20190227170021/[Link]" alt="Square">
</map>
</body>
</html>
Output:
4. GIF Animation
GIFs (Graphics Interchange Format) are widely used on the web for creating
simple animations. They are advantageous for adding visual interest to a
webpage without the complexity or bandwidth requirements of video files.
61
Advantages of GIFs:
To integrate a GIF into your HTML document, use the <img> tag. Here is a
simple example:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<img src="[Link]
alt="Animated Example">
62
</body>
</html>
Explanation:
5. Adding Multimedia
A variety of tags such as the <img> tag, <video> tag, and <audio> tag are
available in HTML to include media on your web page. Multimedia combines
different media, such as images, audio, and videos. Users will have a better
experience when multimedia is embedded into HTML. Early web browsers
only supported text and were limited to a single font in a single color. However,
later browsers introduced support for various fonts, images, and multimedia
elements.
NOTE: Provide multiple video formats such as .wav, .mp3, .mp4, .mpg, .wmv,
etc.
Syntax:
// Embedding image
// Embedding video
63
<source src="Small_movie.mp4" type="video/mp4">
</video>
// Embedding audio
<audio controls>
</audio>
Embedding Image
The <img> tag is self-closing because they don't have a closing tag. The src
attribute is the required attributes in the <img> tag, it helps to specify the
source URL. The alt attribute provides the alternative text to an image. If the
image does not load up then this message will be displayed.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<img src="[Link]
[Link]" alt="web-design stock image">
</body>
</html>
64
Output:
Embedding Video
The <video> tag helps us to embed the required video into the webpage. The
width and height properties determine the size of the video. The control
property adds playback control like play, pause, volume. etc. The <source>
tag specifies the specific video file and the type attribute is used to specify the
MIME (Multipurpose Internet Mail Extensions) type. If the browser does not
support a video tag then the content present inside will be displayed. Provide
multiple video formats such as MP4, MOV, AVI, WEBM.. etc.
<!DOCTYPE html>
<html>
<style>
h1:first-letter{
color:skyblue ;
65
</style>
<body>
<center>
<h1 style="color:red;">DM</h1>
controls preload="auto">
<source src=
"[Link]
content/uploads/20190616234019/Canvas.move_.mp4" type="video/mp4">
</video>
</center>
</body>
</html>
Output:
66
Embedding Audio
The <audio> tag, helps us to embed the required audio into the webpage. The
control property adds playback control like play, pause, volume. etc. The
<source> tag specifies the specific audio file and the type attribute is used to
specify the MIME (Multipurpose Internet Mail Extensions) type. If the browser
does not support video a tag then the content present inside will be displayed.
<!DOCTYPE html>
<html>
<body>
<p>Audio Sample</p>
<audio controls>
</audio>
</body>
</html>
Output:
67
6. Data Collection with HTML Forms
The HTML <form> Tag are essential for collecting user input on web pages.
They provide a structured way for users to submit data, which can then be
processed and used for various purposes, such as user registration, feedback,
surveys, and more. HTML forms consist of multiple input elements, allowing
for diverse types of data collection.
Form Elements:
<form>: The main container for form elements. Defines how and where
to send the form data.
Text Input (<input type="text">): Single-line text entry.
Password Input (<input type="password">): Secure text entry with
masked characters.
Email Input (<input type="email">): For collecting email addresses.
Number Input (<input type="number">): Numeric input with optional
range limits.
Textarea (<textarea>): Multi-line text entry.
Checkbox (<input type="checkbox">): Selection of multiple options.
Radio Button (<input type="radio">): Selection of one option from a
set.
Drop-down List (<select>): Dropdown selection.
68
File Input (<input type="file">): File uploads.
Hidden Input (<input type="hidden">): Stores data not visible to the
user.
Submit Button (<input type="submit">): Submits form data.
Reset Button (<input type="reset">): Resets form fields.
Button (<button>): Custom actions with buttons.
Syntax:
<label for="username">Username:</label>
<label for="password">Password:</label>
</form>
NOTE: In this example, the form is set to submit data to "/submit" using the
POST method when the user clicks the "Submit" button. The actual form fields
can vary depending on the information you want to collect.
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
"width=device-width, initial-scale=1.0">
69
</head>
<body>
<label for="username">Username:</label>
<input type="text"
id="username"
name="username" required>
<br><br>
<label for="password">Password:</label>
<input type="password"
id="password"
name="password" required>
<br><br>
<input type="submit"
value="Submit">
</form>
</body>
</html>
Output:
70
7. Tools for Building Web Pages
Google Chrome: Widely used for its extensive developer tools, including
the ability to inspect elements, debug JavaScript, and emulate mobile
devices.
Mozilla Firefox: Known for its strong adherence to web standards and
powerful development tools.
Microsoft Edge: Modern browser with built-in tools for web
development and testing.
Safari: The default browser for macOS, with tools to inspect and debug
web pages on Apple devices.
71
Bootstrap: A popular framework for building responsive, mobile-first
websites using CSS, JavaScript, and HTML.
72
viii.) Content Management Systems (CMS)
Conclusion
These tools, when used effectively, can greatly enhance the web development
process, making it easier to build, test, and deploy web pages. By leveraging
the right combination of text editors, frameworks, version control systems,
design tools, and deployment platforms, developers can create robust, user-
friendly, and visually appealing websites.
73
UNIT – 3
What is CSS?
CSS allows you to control the look and feel of websites, enabling design
consistency across different devices. It also helps optimize performance
through reusable stylesheets and allows customization of default browser
styles.
When you declare multiple styles for the same element (e.g., from an external
stylesheet, inline styling, or browser defaults), the cascade helps ensure the
correct styles are applied based on the following order of precedence:
There are several ways to include CSS in an HTML file. Each technique has
its own use case, and choosing the right one depends on the project
requirements.
74
Technique Description Syntax
Internal CSS Internal CSS is written directly <style>
within the <style> element inside h1 { color: crimson; }
the <head> section of an HTML </style>
document.
External CSS External CSS uses a separate .css <link rel="stylesheet"
file, linked to the HTML document. href="[Link]">
This is ideal for maintaining large
projects with multiple pages.
Inline CSS Inline CSS applies styles directly to <p
specific HTML elements using the style="color:green;">
style attribute. It is not GeeksforGeeks
recommended for large-scale </p>
projects due to maintainability
concerns.
CSS Selectors
A CSS selector selects the HTML element(s) for styling purposes. CSS selectors
select HTML elements according to their id, class, type, attribute, etc. The
HTML Elements can be styled either as a single or grouped with the help of
the following CSS Selectors, depending on the styled-type used:
75
Attribute Selector Targets elements based on input[type="text"] {
attribute values. border: 1px solid
gray; }
Pseudo-classes Defines a special state of an a:hover { color: red; }
Selector element, such as when it is
hovered or focused.
Pseudo-elements Styles specific parts of an p::first-letter { font-
Selector element, such as the first letter or size: 2em; }
first line.
CSS Properties
CSS Property are used to style HTML elements. Each property consists of two
parts:
Syntax:
property: "value";
Advantages of CSS
Uses of CSS
Helps in Styling
76
We can target the tags of HTML for decorating the web pages by using
these features or attributes provided by CSS.
It mainly helps in the responsiveness of a web page so that we can
access the web page on any existing device with proper height, width,
and other required specifications.
Time efficient
There are three ways by which we can implement or apply CSS on web pages.
Internal CSS: Used in the head tag of HTML within the style tag.
External CSS: This external CSS file is linked to the HTML using a link
tag in the head section of the HTML file.
Inline CSS: It is used in HTML files directly. CSS styling is used in
elements of HTML.
External CSS mainly helps save a lot of time while loading web pages on
Bowser. As external CSS changes will not break the code of HTML and for
change in any kind of design only CSS files need to be changed.
CSS has lots of styling that helps in adding more and more features to web
pages.
Grid
Flexbox
Position
Background properties
CSS has many properties that help to change and provide many extra
features to the web page.
We only need to change the CSS file for any change in web page design.
CSS is convenient for any change in web pages.
77
Applications of CSS
Used in animation, As many web pages use animation for more user
interactivity so it helps in implementing that features on web browsers.
Used in creating social media. It is highly used in styling the UI of social
media.
Used in dynamic templates. Many CSS frameworks help to create the
dynamic element of the web page.
CSS (Cascading Style Sheets) is used to style and layout of web pages, and
controlling the appearance of HTML elements. CSS targets HTML elements
and applies style rules to dictate their appearance.
Inline CSS
Internal or Embedded CSS
External CSS
1. Inline CSS
Inline CSS involves applying styles directly to individual HTML elements using
the style attribute. This method allows for specific styling of elements within
the HTML document, overriding any external or internal styles.
<p style="color:#009900;
font-size:50px;
font-style:italic;
text-align:center;">
Inline CSS
</p>
78
Output:
<!DOCTYPE html>
<html>
<head>
<style>
.main {
text-align: center;
.GFG {
color: #009900;
font-size: 50px;
font-weight: bold;
79
.geeks {
font-style: bold;
font-size: 20px;
</style>
</head>
<body>
<div class="main">
<div class="geeks">
</div>
</div>
</body>
</html>
Output:
80
3. External CSS
External CSS contains separate CSS files that contain only style properties
with the help of tag attributes (For example class, id, heading, … etc). CSS
property is written in a separate file with a .css extension and should be linked
to the HTML document using a link tag. It means that, for each element, style
can be set only once and will be applied across web pages.
HTML:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div class="main">
<div id="geeks">
</div>
</div>
</body>
</html>
CSS:
body {
background-color: powderblue;
81
.main {
text-align: center;
.GFG {
color: #009900;
font-size: 50px;
font-weight: bold;
#geeks {
font-style: bold;
font-size: 20px;
Output:
NOTE: Inline CSS has the highest priority, so it overrides internal and
external styles. Internal CSS comes next, overriding external styles, while
external CSS is applied only if no inline or internal styles are set.
82
Grouping in CSS
Syntax:
selector1, selector2 {
property: value;
Instead of writing this long code, specifying the same properties to different
selectors:
h1 {
padding: 5px;
color: grey;
p{
padding: 5px;
color: grey;
We can group them and write like this & we need the comma(,) to group the
various selectors.
h1, p {
padding: 5px;
color: grey;
83
Approach:
<!DOCTYPE html>
<html>
<head>
<style>
h1, h2, p, a {
text-align: center;
color: green;
</style>
</head>
<body>
<h1>GFG</h1>
<h2>Smaller heading!</h2>
<p>This is
<a href="[Link]
anchor tag
</a>
</p>
<p>This is a paragraph.</p>
84
</body>
</html>
Output:
History of XML
85
<element attribute="value">Text content</element>
Let's unpack this: <element> represents the name of the container, attribute
is like a label describing the container's contents, and Text content is the
actual information stored within the container.
<book> acts as the main container, housing details about a book such as its
title, author, and publication year.
Example:
<book>
<author>J.K. Rowling</author>
<year>1997</year>
</book>
Example:
<student id="001">
<name>John Doe</name>
<age>25</age>
<grade>A</grade>
</student>
86
<book>
<author>J.K. Rowling</author>
<year>1997</year>
</book>
Applications of XML
In the world of web development, XML serves as a handy tool for sorting
and moving data around. It's like the organizer of the digital world,
helping to structure everything from news feeds to website maps and
setup files. And when it comes to web services like SOAP, XML plays a
crucial role in enabling different systems to share information
seamlessly over the internet.
When it comes to exchanging data between different computer systems,
XML acts as a kind of universal translator. It bridges the gap between
systems that speak different languages, making it possible for
businesses and organizations to communicate effectively, even if their
software systems don't normally understand each other.
Think of XML as a digital filing cabinet for managing documents. It's
used across industries like publishing, healthcare, and law to store and
organize documents in a way that's easy to find and manage. Whether
it's technical manuals or legal documents, XML-based standards like
DocBook and DITA provide a structured framework for storing
important information.
Imagine XML as the settings menu of your favorite app. It's the behind-
the-scenes tool that developers use to create organized lists of options
and preferences for users to customize their experience. With XML, you
can tweak your app settings without needing to know the ins and outs
of coding.
87
XML is like a shared language between computers and humans. It's
perfect for storing data in databases because it provides a clear and
structured way to organize information. And with tools like XML
Schema Definition (XSD), you can ensure that your data follows specific
rules and formats, making it easier to work with.
In the world of software integration, XML plays the role of a mediator
between different systems. It helps bridge the gap between apps that
speak different "languages," allowing them to communicate and share
information seamlessly. This makes it easier for businesses to
streamline their operations by connecting all their software systems
together.
And finally, XML has inspired popular data formats like JSON and
YAML. These simplified versions of XML are easier for computers to read
and write, making them perfect for exchanging data between
applications and services. They're the modern-day equivalents of XML,
designed to make data interchange faster and more efficient.
Advantages of XML
88
3. Introduction to DHTML
89
NOTE: Many times DHTML is confused with being a language like HTML but
it is not. It must be kept in mind that it is an interface or browsers
enhancement feature which makes it possible to access the object model
through Javascript language and hence make the webpage more interactive.
Key Features:
Use of DHTML
DHTML makes a webpage dynamic but Javascript also does, the question
arises that what different does DHTML do? So the answer is that DHTML has
the ability to change a webpages look, content and style once the document
has loaded on our demand without changing or deleting everything already
existing on the browser’s webpage. DHTML can change the content of a
webpage on demand without the browser having to erase everything else, i.e.
being able to alter changes on a webpage even after the document has
completely loaded.
90
Advantages:
91
Database Does not require database Requires database connectivity.
Connectivity connectivity.
File Files are stored using .htm Files are stored using .dhtm
Extensions or .html extensions. extension.
Browser Requires no processing Requires processing from the
Processing from the browser. browser.
92
UNIT – 4
DHTML stands for Dynamic Hypertext Markup language i.e., Dynamic HTML.
The DHTML application was introduced by Microsoft with the release of the
4th version of IE (Internet Explorer) in 1997.
HTML 4.0
CSS
JavaScript
DOM.
93
Think of it as a tree of objects where each part of your HTML document
(elements, attributes, text) is represented as a node, allowing you to
dynamically change or interact with the content and structure of the page.
DOM Required
94
Cross-Platform Compatibility: It provides a standard way for scripts
to interact with web documents, ensuring browser compatibility.
DOM Works
Method Description
getElementById(id) Selects an element by its ID.
getElementsByClassName(class) Selects all elements with a given class.
querySelector(selector) Selects the first matching element.
querySelectorAll(selector) Selects all matching elements.
createElement(tag) Creates a new HTML element.
appendChild(node) Adds a child node to an element.
remove() Removes an element from the DOM.
addEventListener(event, fn) Attaches an event handler to an element.
95
Example: In this example, We use HTML element id to find the DOM HTML
element.
<html>
<body>
<h2>GFG</h2>
<p id="intro">
</p>
<p>
</p>
<p id="demo"></p>
<script>
[Link]("demo").innerHTML =
</script>
</body>
</html>
96
Output:
<table>
<ROWS>
<tr>
<td>Car</td>
<td>Scooter</td>
</tr>
<tr>
<td>MotorBike</td>
<td>Bus</td>
</tr>
</ROWS>
</table>
97
Output:
DOM is not
It is not a binary description where it does not define any binary source
code in its interfaces.
It is not used to describe objects in XML or HTML whereas the DOM
describes XML and HTML documents as objects.
It is not represented by a set of data structures; it is an interface that
specifies object representation.
It does not show the criticality of objects in documents i.e it doesn’t
have information about which object in the document is appropriate to
the context and which is not.
98
Example: This example illustrates the dom-manipulation using
getElementById() Method.
<html>
<head>
<title>DOM manipulation</title>
</head>
<body>
<br />
<br />
<br />
<p id="result"></p>
<script type="text/javascript">
function getAdd() {
[Link](add);
99
// Displays the result in paragraph using dom
[Link]("result").[Link] = "red";
</script>
</body>
</html>
Output:
Generally, most developers use unique ids in the whole HTML document. The
user has to add the id to the particular HTML element before accessing the
HTML element with the id. Users can use getElementById() method to access
the HTML element using the id. If any element doesn’t exist with the passed
id into the getElementById method, it returns the null value.
100
Syntax:
[Link](element_ID);
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
<h1 id="GFG">
GFG
</h1>
<script>
[Link](temp);
[Link]([Link]);
</script>
</body>
</html>
101
Output:
Syntax:
[Link](element_classnames);
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
102
<p>DOM getElementsByclassName() Method</p>
<script>
[Link](temp[0]);
[Link](temp[1]);
[Link](temp[2]);
</script>
</body>
</html>
Output:
Users can select the HTML elements using the different CSS selectors such
as class, id, and tag name at a single time. HTML elements can be retrieved
using CSS selectors in two ways. The querySelector() method returns the first
element that matches the particular CSS selector. The querySelectorAll()
method returns all element that matches the particular CSS selector.
To use id/class as a parameter users have to add the ‘#‘/’.‘ sign before it.
Users can pass directly the tag name into the above 2 methods. Users don’t
need to separate CSS selectors when passing multiple CSS selectors as
parameters.
103
Syntax:
[Link](selectors);
[Link](selectors);
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
<script>
// using querySelector
[Link](temp);
temp = [Link]("#g2");
[Link](temp);
temp = [Link](".gfg1#g2");
[Link](temp);
temp = [Link]("p.gfg1");
[Link](temp);
</script>
</body>
</html>
Output:
105
Key Concepts:
Involves moving elements around the page using CSS properties like
left, top, right, and bottom.
Uses absolute, relative, fixed, or sticky positioning to control the
placement of elements.
Example:
<!DOCTYPE html>
<html>
<head>
<style>
#dynamicDiv {
position: absolute;
left: 50px;
top: 50px;
background-color: blue;
width: 100px;
height: 100px;
106
</style>
</head>
<body>
<div id="dynamicDiv"></div>
<script>
function moveAndStyleDiv() {
[Link] = "200px";
[Link] = "100px";
[Link] = "red";
[Link] = "150px";
[Link] = "150px";
setTimeout(moveAndStyleDiv, 2000);
</script>
</body>
</html>
Output:
107
After Transition O/P:
Explanation
[Link] = "red";
108
ii.) Resizing Elements:
[Link] = "150px";
[Link] = "150px";
Adjust the left, top, right, and bottom properties for dynamic
positioning.
[Link] = "200px";
[Link] = "100px";
Event bubbling is a way that events (like clicks or key presses) move through
the elements in an HTML document. When an event happens in a specific
element (like a button), it first affects that element and then moves up to its
parent elements, triggering any event listeners attached to those parents. This
process is called “bubbling” because it starts at the bottom (the innermost
element) and bubbles up to the top (the outer elements).
109
Syntax:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
</head>
<body>
<div id="parent">
<button>
<h2>Parent</h2>
</button>
110
<button id="child">
<p>Child</p>
</button>
</div><br>
<script>
[Link](
"child").addEventListener("click", function () {
}, false);
[Link](
"parent").addEventListener("click", function () {
}, false);
</script>
</body>
</html>
Output:
111
1.5 Data Binding
Data Binding: Data binding in DHTML using JavaScript refers to the process
of automatically updating the user interface (UI) based on changes in the data
model and vice versa. This is achieved by linking HTML elements to JavaScript
variables or objects so that any change in the data model is immediately
reflected in the UI.
Key Concepts
Only updates the UI when the data model changes, but not the other
way around.
<!DOCTYPE html>
<html>
<head>
<style>
.inputField {
display: block;
112
margin: 10px 0;
</style>
</head>
<body>
<script>
// Data Model
function updateName() {
userName = [Link]("nameInput").value;
[Link]("nameOutput").innerText = userName;
// Initial Binding
[Link]("nameInput").value = userName;
[Link]("nameOutput").innerText = userName;
</script>
</body>
</html>
113
Output:
Explanation:
<!DOCTYPE html>
<html>
<head>
<style>
.inputField {
display: block;
margin: 10px 0;
</style>
114
</head>
<body>
<script>
// Data Model
let userAge = 0;
function displayAge() {
userAge = [Link]("ageInput").value;
[Link]("ageOutput").innerText = userAge;
</script>
</body>
</html>
Output:
115
Explanation:
Automatically keeps the data model and UI in sync, reducing the need
for manual updates.
Reduces boilerplate code for updating the UI, making the code easier to
maintain and understand.
2. JavaScript
JavaScript is a powerful and flexible programming language for the web that
is widely used to make websites interactive and dynamic. JavaScript can also
able to change or update HTML and CSS dynamically. JavaScript can also
run on servers using tools like [Link], allowing developers to build entire
applications with it.
116
2.2 How to Develop JavaScript
<script>
alert("Hello, World!");
</script>
<script src="[Link]"></script>
Variables are used to store data in JavaScript so that we can later access the
data. JavaScript is a dynamically typed language so the type of variables is
decided at runtime. Therefore there is no need to explicitly define the type of
a variable. We can declare variables in JavaScript in three ways:
117
Example:
[Link](a);
[Link](b);
[Link](c);
Output:
10
20
30
Example Program:
<!DOCTYPE html>
<html>
<head>
<title>var Example</title>
</head>
<body>
<script>
</script>
</body>
</html>
Example Program:
<!DOCTYPE html>
<html>
<head>
<title>let Example</title>
</head>
<body>
<script>
[Link](age); // Output: 25
age = 30;
[Link](age); // Output: 30
119
[Link](age);// Output: Error: age is not defined
</script>
</body>
</html>
Example Program:
<!DOCTYPE html>
<html>
<head>
<title>const Example</title>
</head>
<body>
<script>
country = "America";
</script>
</body>
</html>
120
Comparison of properties of let, var, and const keywords in JavaScript:
Example:
function sum(x, y) {
return x + y;
[Link](sum(6, 9));
Output:
15
121
A list of parameters enclosed within parentheses and separated by
commas (In the above example, parameters are x and y)
A list of statements composing the body of the function enclosed within
curly braces {} (In the above example, statement is “return x + y”).
Return Statement
There are some situations when we want to return some values from a
function after performing some operations. In such cases, we make use of the
return. This is an optional statement. In the above function, “sum()” returns
the sum of two as result.
Function Parameters
Parameters are input passed to a function. In the above example, sum() takes
two parameters, x and y.
Calling Functions
After defining a function, the next step is to call them to make use of the
function. We can call a function by using the function name separated by the
value of parameters enclosed between the parenthesis.
Example:
// Function Definition
function welcomeMsg(name) {
[Link](welcomeMsg(nameVal));
122
Output:
Why Functions?
Function Invocation
The function code you have written will be executed whenever it is called.
Function Expression
Syntax:
// Set of statements
};
[Link](x);
123
Output:
16
Arrow Function:
Arrow Function is one of the most used and efficient methods to create a
function in JavaScript because of its comparatively easy implementation. It is
a simplified as well as a more compact version of a regular or normal function
expression or syntax.
Syntax:
return [Link];
});
Output:
Normal way [ 8, 6, 7, 9 ]
124
i.) Using if Statement
Example:
let x = 20;
if (x % 2 === 0) {
[Link]("Even");
if (x % 2 !== 0) {
[Link]("Odd");
};
Output:
Even
The if-else statement will perform some action for a specific condition. Here
we are using the else statement in which the else statement is written after
the if statement and it has no condition in their code block.
Example:
[Link]("Adult")
} else {
[Link]("Not an Adult")
};
125
Output:
Adult
Example:
const x = -3;
if (x > 0) {
[Link]("Positive.");
} else if (x < 0) {
[Link]("Negative.");
} else {
[Link]("Zero.");
};
Output:
Negative.
126
Example:
let Branch;
switch (true) {
break;
break;
break;
break;
break;
default:
break;
127
Output:
Example:
const result =
[Link](result);
Output:
Example:
128
if (temperature > 30) {
} else {
} else {
};
Output
Conditional Description
Statement
if statement Executes a block of code if a specified condition is true.
else statement Executes a block of code if the condition of the
preceding if statement is false.
else if statement Adds more conditions to the if statement, allowing
multiple alternative conditions to be tested.
switch statement Evaluates an expression, then executes the case
statement that matches the expression’s value.
Ternary operator Provides a concise way to write if-else statements in a
single line.
Nested if-else Allows for multiple conditions to be checked in a
statement hierarchical manner.
129
2.6 Loops and Repetition
JavaScript loops are essential for efficiently handling repetitive tasks. They
execute a block of code repeatedly as long as a specified condition remains
true. These loops are powerful tools for automating tasks and streamlining
your code.
For example, suppose we want to print “Hello World” 5 times. This can be
done using JS Loop easily. In Loop, the statement needs to be written only
once and the loop will be executed 5 times as shown below:
[Link]("Hello World!");
Output:
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
for Loop
while Loop
do-while Loop
for-in Loop
for-of Loop
Labeled Statement
Break Statement
Continue Statement
Infinite Loop (Loop Error)
130
i.) JavaScript for Loop
The JS for loop provides a concise way of writing the loop structure. The for
loop contains initialization, condition, and increment/decrement in one line
thereby providing a shorter, easy-to-debug structure of looping.
Syntax:
statement(s)
Flowchart:
131
Loop termination: When the condition becomes false, the loop
terminates marking the end of its life cycle.
Example:
let x;
Output:
Value of x: 2
Value of x: 3
Value of x: 4
The JS while loop is a control flow statement that allows code to be executed
repeatedly based on a given Boolean condition. The while loop can be thought
of as a repeating if statement.
Syntax:
loop statements...
132
Flowchart:
Example:
let val = 1;
[Link](val);
val += 1;
133
Output:
The JS do-while loop is similar to the while loop with the only difference is
that it checks for the condition after executing the statements, and therefore
is an example of an Exit Control Loop. It executes loop content at least once
event the condition is false.
Syntax:
do {
Statements...
while (condition);
Flowchart:
134
The do-while loop starts with the execution of the statement(s). There
is no checking of any condition for the first time.
After the execution of the statements and update of the variable value,
the condition is checked for a true or false value. If it is evaluated to be
true, the next iteration of the loop starts.
When the condition becomes false, the loop terminates which marks
the end of its life cycle.
It is important to note that the do-while loop will execute its statements
at least once before any condition is checked and therefore is an
example of the exit control loop.
Example:
let test = 1;
do {
[Link](test);
test++;
} while(test <= 5)
Output:
JS for-in loop is used to iterate over the properties of an object. The for-in loop
iterates only over those keys of an object which have their enumerable
property set to “true”.
135
Syntax:
// Statement
let myObj = { x: 1, y: 2, z: 3 };
[Link](key, myObj[key]);
Output:
x1
y2
z3
JS for-of loop is used to iterate the iterable objects for example – array, object,
set and map. It directly iterate the value of the given iterable object and has
more concise syntax than for loop.
Syntax:
// Statement
[Link](value);
Output:
JS label keyword does not include a goto keyword. Users can use the continue
keyword with the label statement. Furthermore, users can use the break
keyword to terminate the loop/block. You can also use the break keyword
without defining the label but it terminates only the parent loop/block. To
terminate the outer loop from the inner loop using the break keyword, users
need to define the label.
Syntax:
Label:
Example:
let sum = 0, a = 1;
a = 1;
137
// Label for inner loop
sum += a;
break outerloop;
a++;
Output:
sum = 1
sum = 3
sum = 4
sum = 6
sum = 7
sum = 9
sum = 10
sum = 12
138
Syntax:
break;
Example:
if (i == 4)
break;
[Link](i);
Output:
JS continue statement is used to break the iteration of the loop and follow
with the next iteration. The break in iteration is possible only when the
specified condition going to occur. The major difference between the continue
and break statement is that the break statement breaks out of the loop
completely while continue is used to break one statement and iterate to the
next statement.
Syntax:
continue;
139
Example:
if (i % 2 == 0)
continue;
[Link](i);
Output:
One of the most common mistakes while implementing any sort of loop is that
it may not ever exit, i.e. the loop runs for infinite times. This happens when
the condition fails for some reason.
for (let i = 5; i != 0; i -= 2) {
[Link](i);
let x = 5;
140
// Infinite loop because update statement
// is not provided
while (x == 5) {
Output:
-1
-3
141
UNIT – 5
There are two primary ways to create an object in JavaScript: Object Literal
and Object Constructor.
The object literal syntax allows you to define and initialize an object with curly
braces {}, setting properties as key-value pairs.
Example:
let obj = {
name: "Sourav",
age: 23,
job: "Developer"
};
[Link](obj);
Output:
142
2.) Creation Using new Object() Constructor
Example:
[Link]= "Sourav",
[Link]= 23,
[Link]= "Developer"
[Link](obj);
Output:
You can access an object’s properties using either dot notation or bracket
notation
[Link]([Link]);
[Link](obj["age"]);
Output:
Sourav
23
143
ii.) Modifying Object Properties
[Link](obj);
[Link] = 23;
[Link](obj);
Output:
You can dynamically add new properties to an object using dot or bracket
notation.
[Link] = "Red";
[Link](obj);
Output:
delete [Link];
[Link](obj);
144
Output:
{ model: 'Tesla' }
[Link]("color" in obj);
[Link]([Link]("model"));
Output:
false
true
Output:
name: Sourav
age: 23
145
vii.) Merging Objects
[Link](obj3);
Output:
[Link]([Link](obj).length);
Output:
To check if a value is an object, use typeof and verify it’s not null.
Output:
true
146
Key Differences Between {} and new Object()
JavaScript includes several built-in objects for handling data and operations
efficiently. These built-in objects come with pre-defined methods and
properties that make it easier to perform common tasks such as mathematical
calculations, date and time manipulation, and string operations. Here is a
detailed explanation of some of the most commonly used built-in objects in
JavaScript:
[Link](result); // Output: 4
147
Explanation:
The Date object is used for working with dates and times. It allows you to
create, manipulate, and format dates and times. You can create a new date
object using the new Date() constructor, and there are various methods
available to get and set different components of a date (such as year, month,
day, hour, minute, second).
Explanation:
new Date(): Creates a new Date object representing the current date and
time.
[Link](): Converts the date to a readable string format.
[Link]([Link]()): Outputs the current date as a string.
The String object is used for string manipulation. It provides methods for
various string operations, such as finding the length of a string, converting to
uppercase or lowercase, finding substrings, replacing parts of a string, and
more.
148
Explanation:
The DOM represents the structure of a web page as a tree of nodes. It enables
developers to dynamically interact with HTML elements, modify styles, or
create new elements.
The Window object represents the browser window or frame. It is the global
object in a web browser environment, meaning all global JavaScript objects,
functions, and variables automatically become members of the Window
object. This object provides methods to manipulate the browser window, such
as opening, closing, resizing, and moving the window, as well as controlling
the history and setting timeouts.
149
[Link] and [Link]: Get the height and width
of the window's content area.
Example:
// Display an alert
[Link]("Hello, World!");
The Document object represents the web page loaded in the browser. It is part
of the DOM (Document Object Model) and provides methods and properties
to access and manipulate the content, structure, and style of the web page.
This object allows developers to dynamically modify the HTML and CSS of a
page.
150
Example:
[Link](paragraph);
[Link] = "lightblue";
The Navigator object provides information about the web browser and the
user's environment. It includes properties that reveal details about the
browser's version, the user's operating system, and whether certain browser
features are enabled. This information is useful for tailoring the user
experience based on the user's browser and device capabilities.
151
Example:
[Link](`User-Agent: ${userAgent}`);
[Link](`Platform: ${platform}`);
JavaScript Form Validation is a way to ensure that the data users enter into
a form is correct before it gets submitted. This helps ensure that things like
emails, passwords, and other important details are entered properly, making
the user experience smoother and the data more accurate.
152
Commonly Used Input Types in HTML Forms
In HTML forms, various input types are used to collect different types of data
from users. Here are some commonly used input types:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Html Forms</title>
</head>
<body>
<h2>HTML Forms</h2>
<form>
<label for="username">Username:</label><br>
<label for="password">Password:</label><br>
</form>
</body>
</html>
153
Output:
This HTML form collects user personal information, including name, email,
password, gender, date of birth, and address. It features proper styling for
input fields and submission buttons.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>HTML Form</title>
<style>
body {
display: flex;
154
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background-color: #f0f0f0;
form {
width: 400px;
background-color: #fff;
padding: 20px;
border-radius: 8px;
fieldset {
padding: 10px;
margin: 0;
legend {
font-weight: bold;
margin-bottom: 10px;
155
label {
display: block;
margin-bottom: 5px;
input[type="text"],
input[type="email"],
input[type="password"],
textarea,
input[type="date"] {
padding: 8px;
margin-bottom: 10px;
box-sizing: border-box;
border-radius: 4px;
.gender-group {
margin-bottom: 10px;
.gender-group label {
display: inline-block;
margin-left: 10px;
156
input[type="radio"] {
margin-left: 10px;
vertical-align: middle;
input[type="submit"] {
border-radius: 5px;
cursor: pointer;
</style>
</head>
<body>
<form>
<fieldset>
157
<label>Enter your gender:</label>
<div class="gender-group">
<label for="male">Male</label>
<label for="female">Female</label>
<label for="others">Others</label>
</div>
</fieldset>
</form>
</body>
</html>
158
Output:
Here are some of the key attributes that can be used with the <form> element:
159
target: This attribute specifies where to display the response received
after submitting the form. The values can be “_blank”, “_self”, “_parent”,
“_top”, or the name of an iframe.
enctype: This attribute is used when method=“post”. It specifies how
the form-data should be encoded when submitting it to the server. The
values can be “application/x-www-form-urlencoded”, “multipart/form-
data”, or “text/plain”.
autocomplete: This attribute specifies whether a form should have
autocomplete on or off. When autocomplete is on, the browser
automatically completes values based on values that the user has
entered before.
novalidate: This Boolean attribute specifies that the form-data should
not be validated on submission.
JavaScript Form Validation is a way to ensure that the data users enter into
a form is correct before it gets submitted. This helps ensure that things like
emails, passwords, and other important details are entered properly, making
the user experience smoother and the data more accurate.
Data Retrieval:
The first step is to get the user’s values entered into the form fields (like name,
email, password, etc.). This is done using [Link], which
refers to the form with the name “RegForm”.
Data Validation:
Name Validation: We check to make sure the name field isn’t empty and
doesn’t contain any numbers.
160
Email Validation: We make sure that the email field isn’t empty and that it
includes the “@” symbol.
Password Validation: We ensure that the password field isn’t empty and that
the password is at least 6 characters long.
Course Selection Validation: We check that a course has been selected from
a dropdown list.
Error Handling:
If any of the checks fail, an alert message is shown to the user using
[Link], telling them what’s wrong.
The form focuses on the field that needs attention, helping the user easily fix
the error.
Submission Control:
If all the validation checks pass, the function returns true, meaning the form
can be submitted. If not, it returns false, stopping the form from being
submitted.
Focus Adjustment:
The form automatically focuses on the first field that has an error, guiding the
user to fix it.
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Form Validation</title>
161
<link rel="stylesheet" href="[Link]" />
</head>
<body>
<h1>REGISTRATION FORM</h1>
<p>
<label for="name">Name:</label>
</p>
<p>
<label for="address">Address:</label>
</p>
<p>
</p>
<p>
162
<label for="password">Password:</label>
</p>
<p>
<option value="">
Select Course
</option>
<option value="BTECH">
BTECH
</option>
<option value="BBA">
BBA
</option>
<option value="BCA">
BCA
</option>
<option value="[Link]">
[Link]
</option>
</select>
163
</p>
<p>
</p>
<p>
information</label>
</p>
<p>
</p>
</form>
<script src="[Link]"></script>
</body>
</html>
CSS:
body {
background-color: #f5f5f5;
164
h1 {
text-align: center;
color: #333;
form {
max-width: 600px;
margin: 0 auto;
padding: 20px;
background-color: #fff;
border-radius: 8px;
input[type="text"],
input[type="password"],
select,
textarea {
width: 100%;
padding: 10px;
margin: 5px 0;
border-radius: 5px;
box-sizing: border-box;
font-size: 16px;
165
select {
width: 100%;
padding: 10px;
margin: 5px 0;
border-radius: 5px;
box-sizing: border-box;
font-size: 16px;
background-color: #fff;
appearance: none;
-webkit-appearance: none;
-moz-appearance: none;
textarea {
resize: vertical;
input[type="submit"],
input[type="reset"],
input[type="checkbox"] {
background-color: #007bff;
color: #fff;
border: none;
border-radius: 5px;
166
cursor: pointer;
font-size: 16px;
input[type="submit"]:hover,
input[type="reset"]:hover,
input[type="checkbox"]:hover {
background-color: #0056b3;
.error-message {
color: red;
font-size: 14px;
margin-top: 5px;
JAVASCRIPT:
function validateForm() {
167
const passwordError = [Link]("password-error");
[Link] = "";
[Link] = "";
[Link] = "";
[Link] = "";
[Link] = "";
[Link] = "";
[Link] =
isValid = false;
[Link] =
isValid = false;
[Link] =
isValid = false;
168
}
[Link] =
isValid = false;
[Link] =
isValid = false;
if (!agree) {
[Link] =
isValid = false;
return isValid;
169
Output:
Client-side Validation:
This is done in the user’s browser before the form is submitted. It provides
quick feedback to the user, helping them fix errors without sending data to
the server first.
Server-side Validation:
Even though client-side validation is useful, it’s important to check the data
again on the server. This ensures that the data is correct, even if someone
tries to bypass the validation in the browser.
170
2.) Number validation in JavaScript
Sometimes the data entered into a text field needs to be in the right format
and must be of a particular type in order to effectively use the form. For
instance, Phone number, Roll number, etc are some details that must be in
digits not in the alphabet.
171
Classes
data member;
method;
constructor;
nested class;
interface;
172
Objects
Objects correspond to things found in the real world. For example, a graphics
program may have objects such as “circle”, “square”, and “menu”. An online
shopping system might have objects such as “shopping cart”, “customer”, and
“product”.
NOTE: When we create an object which is a non primitive data type, it’s
always allocated on the heap memory.
173
Declaring Objects (Also called instantiating a class)
Example:
Class Object
A class is the blueprint of an An object is an instance of the class.
object. It is used to create objects.
No memory is allocated when a Memory is allocated as soon as an
class is declared. object is created.
A class is a group of similar An object is a real-world entity such as
objects. a book, car, etc.
A class is a logical entity. An object is a physical entity.
A class can only be declared once. Objects can be created many times as
per requirement.
174
Example: A class can represent a Example: Objects of the class car can
car. be BMW, Mercedes, Ferrari, etc.
Encapsulation
Example:
class BankAccount {
constructor(owner, balance) {
[Link] = owner;
deposit(amount) {
if (amount > 0) {
this._balance += amount;
getBalance() {
return this._balance;
175
}
Inheritance
Example:
// Superclass
class Animal {
constructor(name) {
[Link] = name;
speak() {
// Subclass
constructor(name, breed) {
[Link] = breed;
176
}
speak() {
[Link](`${[Link]} barks.`);
Polymorphism
Example:
class Shape {
draw() {
[Link]("Drawing a shape.");
draw() {
[Link]("Drawing a circle.");
177
draw() {
[Link]("Drawing a square.");
[Link](shape => {
[Link]();
});
// Output:
// Drawing a shape.
// Drawing a circle.
// Drawing a square.
Conclusion
178