0% found this document useful (0 votes)
11 views

Web Explore Javascript Saugata

2024

Uploaded by

rumasahaa1985
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Web Explore Javascript Saugata

2024

Uploaded by

rumasahaa1985
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 121

ABOUT THE E BOOK

This book covers the basic of HTML, CSS3 and


JAVASCRIPT written in the easiest form of language by
Saugata Sarkar, who is working on Web Tools since
1999 with Tata Infotech, IBM, Brainware Groups and
Onward Academy – A sister concern of Corelynx
Solution Technologies. The e book is co-authored
with Riya Jana to cater the practical hands on and this
book aims at creating simple front end application
without any hindrances.

Edition : 2024, September.


Explore Web with Saugata Sarkar

EXPLORE WEB
Saugata Sarkar
Explore Web using HTML, CSS and JavaScript

TABLE OF CONTENTS

Sl Chapters Page

1 HTML – Web Introductions, Basic Formatting Tags 2

2 HTML – Lists and Table 21

3 HTML – Building Forms and Hyperlink 32

4 CSS – Introduction and Different types of CSS 42

5 CSS – Selectors and Box Model 49

6 JavaScript – Introduction, Overview, Basic Operations 63

7 JavaScript – Control Statement, Functions 72

8 JavaScript – Event Handling 87

9 JavaScript – DOM Manipulations, Form Validations 96

10 JavaScript – Lab Assignments 104

11 JavaScript – Form Validation 105

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 1


Explore Web using HTML, CSS and JavaScript

CHAPTER 1
HTML – Web Introductions,
Basic Formatting Tags

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 2


Explore Web using HTML, CSS and JavaScript

What is Web Architecture?


Web architecture refers to the overall structure of a website or web application, including the
way it is designed, implemented, and deployed. It involves the use of technologies and
protocols such as HTML, CSS, JavaScript, and HTTP to build and deliver web pages and
applications to users.

Web architecture consists of several components, including the client, the server, the network,
and the database. The client is the web browser or application that the user interacts with, and
the server is the computer or group of computers that host the website or web application. The
network is the infrastructure that connects the client and the server, such as the internet. The
database is a collection of data that is used to store and retrieve information for the website or
web application.

Web architecture also includes the design and layout of the website or web application, as well
as the way it is organized and the relationships between different pages and components.

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 3


Explore Web using HTML, CSS and JavaScript

Web Architecture Components

There are several components that make up a web architecture −

The client −This is the web browser or application that the user interacts with. The client sends
requests to the server and receives responses from the server.

The server −This is the computer or group of computers that host the website or web
application. The server processes requests from the client and sends back the appropriate
response.

The network This is the infrastructure that connects the client and the server, such as the
internet. It allows for communication between the client and the server.

The database −This is a collection of data that is used to store and retrieve information for the
website or web application. The database can be located on the same server as the website or
web application, or it can be hosted on a separate server.

The design and layout −This refers to the way the website or web application is structured and
organized, including the layout, navigation, and overall appearance.

The frameworks and libraries − These are tools and resources that are used to build and
maintain the website or web application. They can include frameworks like Ruby on Rails or
Django, or libraries like jQuery or React.

The deployment and hosting − This refers to the way the website or web application is
deployed and hosted, including the hosting environment (such as a shared hosting plan or a
cloud platform) and the process for deploying updates and changes to the website or web
application.

Conclusion -
Web servers are the backbone of the internet, enabling us to access and interact with websites
and web applications every day. Understanding their working and architecture is essential for
web developers, administrators, and anyone interested in the digital world. Whether you’re
running a personal blog or managing a complex e-commerce platform, web servers play a pivotal
role in delivering online content efficiently and securely.

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 4


Explore Web using HTML, CSS and JavaScript

What is HTML?
HTML is an acronym which stands for Hyper Text Markup Language which is used for creating
web pages and web applications. Let's see what is meant by Hypertext Markup Language, and
Web page.

Hyper Text: HyperText simply means "Text within Text." A text has a link within it, is a
hypertext. Whenever you click on a link which brings you to a new webpage, you have clicked
on a hypertext. HyperText is a way to link two or more web pages (HTML documents) with each
other.

Markup language: A markup language is a computer language that is used to apply layout and
formatting conventions to a text document. Markup language makes text more interactive and
dynamic. It can turn text into images, tables, links, etc.

Web Page: A web page is a document which is commonly written in HTML and translated by a
web browser. A web page can be identified by entering an URL. A Web page can be of the static
or dynamic type. With the help of HTML only, we can create static web pages.

HTML Tags
HTML tags are like keywords which defines that how web browser will format and display the
content. With the help of tags, a web browser can distinguish between an HTML content and a
simple content.

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 5


Explore Web using HTML, CSS and JavaScript

An HTML file must have some essential tags so that web browser can differentiate between a
simple text and HTML text. You can use as many tags you want as per your code requirement.

 All HTML tags must enclosed within <> these brackets.


 Every tag in HTML perform different tasks.
 A tag has opening and closing tag with exception to few tags like <br> <hr><img>

1. Container Tag

Container tag : These tags are in which we define the text or other tag elements.
These actually consist two tags, a start tag and an end tag, which enclose the text.

<html>
<head> </head>

<body>

</body>

</html>

2. Empty(Non-Container/Blank) tag

Non- container tag/empty tag : These are standalone text do not contain text. Or any other tag element.

<br/>
<hr/>
<input type="text"/>

Container Tag versus Non Container tag

Container Tag Non Container Tag / Empty tag


<p> </p> <hr>
<font> </font> <br>
<h1> </h1> <input>
<ol> </ol> <img>

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 6


Explore Web using HTML, CSS and JavaScript

Example 1

<html>
<head>
<title>Web page title</title>
</head>
<body>
<h1>Write Your First Heading</h1>
<p>Write Your First Paragraph.</p>
</body>
</html>

HTML Comments
HTML comments are not displayed in the browser, but they can help document your HTML source code.

You can add comments to your HTML source by using the following syntax:

<!-- Write your comments here -->

Notice that there is an exclamation World (!) in the start tag, but not in the end tag.

Add Comments

With comments you can place notifications and reminders in your HTML code:

Example

<html>
<body>
<!-- This is a comment -->
<p>This is a paragraph. </p>
<!-- Comments are not displayed in the browser -->

</body>
</html>

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 7


Explore Web using HTML, CSS and JavaScript

Basic HTML Tags

Heading Tags
Heading tags are used to define headings of documents. You can use different sizes for your
headings. HTML also has six levels of headings, which use the
elements <h1>, <h2>, <h3>, <h4>, <h5>, and <h6>.

Example 2

<html>
<head>
<title>Heading Example</title></head>
<body>
<h1>This is heading 1</h1>
<h2>This is heading 2</h2>
<h3>This is heading 3</h3>
<h4>This is heading 4</h4>
<h5>This is heading 5</h5>
<h6>This is heading 6</h6>
</body></html>

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 8


Explore Web using HTML, CSS and JavaScript

Paragraph Tag
The <p> tag offers a way to structure your text into different paragraphs. Each paragraph of
text should go in between an opening <p> and a closing </p> tag.

Example 3

<html>
<head>
<title>Paragraph Example</title>
</head>
<body>
<p>Here is a first paragraph of text.</p>
<p>Here is a second paragraph of text.</p>
</body>
</html>

Line Break Tag


Whenever you use the <br /> element, anything following it starts from the next line. This tag is
an example of an empty element, where you do not need opening and closing tags, as there is
nothing to go in between them.

The <br /> tag has a space between the characters br and the forward slash /. If you omit this
space, older browsers will have trouble rendering the line break, while if you miss the forward
slash character and just use <br>, it is not valid in XHTML.

Example 4

<html>
<head>
<title>Line Break Example</title>
</head>
<body>
<p>Hello<br /> You delivered your assignment on time.<br />
Thanks<br />Mahnaz</p>
</body>
</html>

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 9


Explore Web using HTML, CSS and JavaScript

Center Tag
The <center> tag aligns text, images, or other HTML elements in the middle of a web page.

Note: The <center> tag is deprecated in HTML5. You can use the CSS text-align property to center
elements.

Example

<html>
<head>
<title>Cantering Content Example</title>
</head>
<body>
<p>This text is not in the center.</p>
<center>
<p>This text is in the center.</p>
</center>
</body>
</html>

Horizontal Rule Tag


The horizontal rule (<hr>) tag displays a horizonal line. A horizontal line visually breaks up
sections of a document. The <hr> tag creates a line from the current position in the document
to the right margin and breaks the line accordingly.

Example

<html>
<head>
<title>Horizontal Line Example</title>
</head>
<body>
<p>This is paragraph one and should be on top</p>
<hr />
<p>This is paragraph two and should be at bottom</p>
</body>
</html>

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 10


Explore Web using HTML, CSS and JavaScript

The <hr /> tag is an example of the empty element, where you do not need opening and closing
tags, as there is nothing to go in between them.

Listing Tags
The <ul> and <ol> tags create the unordered and ordered listings, and to display list items, the <li> tag is
used.

Example

<html>
<head>
<title>Listing Tags Example</title>
</head>
<body>
<h2>Unordered list</h2>
<ul>
<li>Item 1</li>
<li>Item 2</li>
</ul>

<h2>Ordered list</h2>
<ul>
<li>Item 1</li>
<li>Item 2</li>
</ul>
</body>
</html>

HTML Elements
HTML elements are the basic building blocks to create a web page; they are created with the
help of an opening tag, content, and ending tag. HTML documents consist of a tree of these
elements, and they specify how HTML documents should be built, and what kind of content
should be placed within various parts of an HTML document.

What is an HTML element?


An HTML element is a fundamental component of an HTML document that can contain data to display
on the webpage, such as text, image, link, or sometimes nothing. An HTML element includes an opening
tag, content, and a closing tag, where the opening tag may also include attributes.

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 11


Explore Web using HTML, CSS and JavaScript

An HTML document consists of a tree of HTML elements, and they define the content and layout of a
webpage, like how and what content should display in the different sections of a webpage.

Example

Some of the examples of HTML elements are as follows:

<p>This is paragraph content.</p>


<h1>This is heading content.</h1>
<div>This is division content.</div>

The following table displays the different parts (opening tag, content, and closing tag) of the
HTML elements used in the above example:

Opening Tag Content Closing Tag

<p> This is paragraph content. </p>

<h1> This is heading content. </h1>

<div> This is division content. </div>

HTML Element Structure

The following image demonstrates the structure of an element, like how an HTML element is
written with the opening and closing tags:

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 12


Explore Web using HTML, CSS and JavaScript

HTML Elements Vs. Tags


HTML elements are created using the HTML tags. An HTML element is defined by a pair of
starting and closing tags having content between them, which defines the content and
structure of the webpage. Whereas, HTML tags are like keywords and part of HTML elements
enclosed in angel brackets (<>).

For example, <p> is the starting tag of a paragraph, and </p> is the closing tag of the same
paragraph, but <p>This is paragraph</p> is a paragraph element.

Nested HTML Elements


HTML allows nesting of elements. The nested elements are created by placing one or more
HTML elements inside an HTML element. Where the container element can be considered as a
parent element and others are as child elements. The child elements are nested inside the
parent element. We can have multiple levels of nesting; however, it requires some guidelines to
follow −

 Every opening tag must have a corresponding closing tag.


 The closing tag of the parent element must come after the closing tag of the child
element.
 The nested elements must be valid HTML elements.

Example

In the following example, we are nesting the italicized element (<i>...</i>) within
the h1 element and underline (<u>...</u>) element within the paragraph element.

<html>
<head>
<title>Nested Elements Example</title>
</head>
<body>
<h1>This is <i>italic</i> heading</h1>
<p>This is <u>underlined</u> paragraph</p>
</body>
</html>

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 13


Explore Web using HTML, CSS and JavaScript

HTML Void Elements


HTML void elements are those elements that don't require closing tags. These tags don't have
any content model and even don't allow nesting of elements. The void elements are also known
as empty or self-closing elements.

Some of the void elements are such as <img />, <hr />, and <br /> elements. The below table
shows a list of void elements −

Elements & Description


S.No
<img />
1 Used for inserting images within HTML documents.
<hr />
2 It displays a horizontal rule.
<br />
3 It is used to provide a line break.
<source />
4 It is used for embedding media resources like audio and video.

Example

The following example demonstrates the example of HTML void elements −

<html>
<body>
<p>This line contains a line break tag, <br> hence content is visible in two separate lines.</p>
<p>This line is <hr>separated by a horizontal rule.</p>
</body>
</html>

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 14


Explore Web using HTML, CSS and JavaScript

HTML Formatting Tags


HTML Formatting Tags are used to change appearance of text for better look and feel than the default
text. The formatting tags can make text bold, italic, underlined etc.

Therearedifferenttagsforvariousformattingtags.EachTaghasitsowntypeofformattingassociatedwithit.

Some HTML Formatting tags are:

 Bold Tag <b>


 Italic Tag <i>
 Underline Tag <u>
 Strong Tag <strong>
 Emphasized Tag <em>
 Subscripted Tag <sub>
 Superscripted Tag <sup>

HTML Bold Tag

The HTML <b> Tag defines bold text. Bold text is wider and darker text than the default text,
without any extra importance to the browser. Look at the example below.

<html>
<head>
<title> Bold Text </title>
</head>
<body>
<p>This is Normal Text. </p>
<b>This is Bold Text. </b>
</body>
</html>

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 15


Explore Web using HTML, CSS and JavaScript

HTML Strong Text

The HTML <strong> Tag displays same formatting like a <b> tag. But the Strong text has some
importance to the browser and search engines. It is always recommended to write keywords
within <strong> Tag to give them extra importance.

<html>

<head>

<title> Strong Text </title>

</head>

<body>

<p>This is Normal text </p>

<strong> This Text is Strong </strong>

</body>

</html>

HTML Italic Text

The HTML <i> Tag defines italic text. This type of formatting displays cursive font based text
that slant slightly to the right.

<html>
<head>
<title> Italic Text </title>
</head>
<body>
<p>This is normal text </p>
<i>This text in Italic </i>
</body>
</html>

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 16


Explore Web using HTML, CSS and JavaScript

HTML Underlined Text

The HTML <u> Tag defines Underlined text. All the text within the <u> and </u> tags will have an
underline throughout.

Underlined Text is used to draw attention of the user and is a default formatting for a hyperlinked text.

<html>

<title> Underlined Text </title>

</head>

<body>

<p>This is Normal text </p>

<u>This is Underlined Text </u>

</body>

</html>

HTML Subscripted Text

The HTML <sub> element defines subscripted text. This type of text is small in size and is placed slightly
below the normal line of text.

<html>
<head>
<title> Subscript Text </title>
</head>
<body>
<p> This is Subscripted Text </p>
<p> H<sub>2 </sub> O
</body>
</html>

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 17


Explore Web using HTML, CSS and JavaScript

HTML Superscripted Text

<html>
<head>
<title> Superscript Text </title>
</head>
<body>
<p> This is Superscripted Text </p>
<p> (a+b)<sup>2</sup>
</body>
</html>

Font tag
The <font> tag was used in earlier versions of HTML to define the size, color, and face of the text.
However, it has been deprecated in HTML5, and it's better to use CSS for styling text. But for learning
purposes, here’s how the <font> tag worked.

<!DOCTYPE html>
<html>
<head>
<title>Font Tag Example</title>
</head>
<body>
<p>This is a normal paragraph.</p>
<p><font color="red" size="4" face="Arial">This is a red Arial text with size 4.</font></p>
<p><font color="blue" size="6" face="tahoma"> family is Tahoma </font></p>
</body>
</html>

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 18


Explore Web using HTML, CSS and JavaScript

Lab Assignment

1. Create the below web page using HTML basic tags

HTML Assignment 1

It is my First HTML Assignment. I am exited to learn HTML, and i want to make


career in web designing. CHAPTER 2
HTML
Introduction to HTML – List and Table
HTML (Hypertext Markup Language) is used to create document on the World
Wide Web. It is simply a collection of certain key words called "Tags" that are
helpful in writing the document to be displayed using a browser on Internet. HTML
was developed by Tim Berners-Lee in 1992.

2. Create the below web page using <b> <i> <u> <strong> <p> tags

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 19


Explore Web using HTML, CSS and JavaScript

3. Create a page with <p> tags and its alignment with <sup> and <sub> tags

4: Apply Different Font Styles to a Paragraph

Objective: Use the <font> tag to apply different styles like color, size, and face to a paragraph.

Task:

1. Create an HTML file named four.htm


2. Inside the body, add three paragraphs:
o One paragraph with red text, size 6, and the font face as Verdana.
o One paragraph with green text, size 3, and the font face as Courier.
o One paragraph with blue text, size 7, and the font face as Comic Sans MS.

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 20


Explore Web using HTML, CSS and JavaScript

CHAPTER 2
HTML – List and Table

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 21


Explore Web using HTML, CSS and JavaScript

HTML Lists
Our day-to-day lives often involve the use of lists. For example, when we go shopping, the bill
we receive includes a list of all the items we've purchased. In a similar manner, web developers
use lists to neatly display data on websites.

Types of HTML Lists

HTML provides different types of lists to display data in various forms. Each list contains one or
more list items.

Unordered List: Displays items using bullets.

Ordered List: Displays items in a numerical sequence, and supports various numbering styles
like Arabic numerals, Roman numerals, and so on.

Definition List: Organizes items in a format similar to a dictionary, with terms and their
corresponding definitions.

An Unordered List

An unordered list starts with the <ul> tag. Each list item starts with the <li> tag.
The list items will be marked with bullets (small black circles) by default:
Example

<html>
<body>

<h2>An unordered HTML list</h2>

<ul>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>

</body>
</html>

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 22


Explore Web using HTML, CSS and JavaScript

An Ordered List

An ordered list starts with the <ol> tag. Each list item starts with the <li> tag.
The list items will be marked with numbers by default:

Example

<html>
<body>

<h2>An ordered HTML list</h2>

<ol>
<li>Hardware</li>
<li>Software</li>
<li>Tally</li>
</ol>

</body>
</html>
A Description List

HTML also supports description lists.


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:

Example

<html>
<body>
<h2>A Description List</h2>
<dl>
<dt>Coffee</dt>
<dd>- black hot drink</dd>
<dt>Milk</dt>
<dd>- white cold drink</dd>
</dl>
</body>
</html>

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 23


Explore Web using HTML, CSS and JavaScript

HTML Table Tag


We all are familiar with the concept of table, we are not talking about the numeric tables here,
the HTML table we are going to learn is the one with rows and column. It’s similar like the
structure of a matrix with proper rows and columns. This type of structure with rows and
columns is very helpful in representing data in an easy and simple manner.

Use of HTML Table


An HTML table is defined with the <table> tag. A table is used to display data in tabular form
(rows * column). It is a paired tag. Just use these tags with their attributes to create tables.

Tables are also used in websites to present any data to the user. It looks really neat and also
everyone prefers tabular form of data nowadays. The HTML tables allows to arrange data like
text, images, etc. into rows and columns.

Example
<html>
<HTML>
<head> <title> HTML Table </title> </head>
<body>
<table>
<tr>
<th> Name </th>
<th> Salary </th>
<th> Age </th>
</tr>
<tr>
<td>Anshuman</td>
<td>Rs. 2,00,000 </td>
<td> 25 </td>
</tr>
<tr><td>Kuldeep</td>
<td>Rs. 5,00,000 </td>
<td> 22 </td>
</tr>
</table>
</body>
</html>

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 24


Explore Web using HTML, CSS and JavaScript

Table Row
A table row can be defined with the <tr> tag It is also a paired tag with </tr> as a closing tag.
Whatever written between these tags will be displayed in a single row of the table. To create a
new row another <tr> tag is written after closing the previous one.

Table heading
A table header in HTML tables is a special case of a table row. It starts with <th> tag and ends
with </th> tag. There only difference between a row and a heading is that text written inside

<th> tags is displayed in bold fonts and is by default centered aligned by the browser. Because
of its properties this tag is used only for writing Heading of the table. You can also make a <tr>
tags content bold and centered by using CSS It will work exactly like <th> tag.

Table Cells
A table cell in an HTML table is defined by <td> tag. It is also a paired tag with </td> as a closing
tag. Each pair of these tags represents a cell in a row. It is used inside &glt;tr> tags only.
Without <tr> tags it is of no value. After declaring the rows the <td> tags are used to enter data
in the table. Whatever is written inside the <td> and </td> tags will be displayed by the browser
in the tables as it is.

Table Attributes
The <table> Tag in HTML table has many attributes which can be used to further define the
structure of the table than just a standard one. These attributes can make a table look a bit
more attractive. Let’s see one by one the different attributes of the table tag and then we will
use them in an example and will see the changes in the table.

The 'border' Attribute


A border attribute is used to specify visible borders in a table. It means that by default the
borders in the table are hidden and if you don’t specify borders then your table will only display
data but there would be no border between them. The border attribute has two values 0 and 1.
0 means no border and 1 means visible borders. You can also increase the values to 2, 3, 4, etc.
it will increase the width of the border.

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 25


Explore Web using HTML, CSS and JavaScript

There are two ways to specify border for HTML tables.

 By border attribute of table in HTML.


 By border property in CSS.

Example

<html>
<head>
<title> HTML Table Border Attribute </title>
</head>
<body>
<table border="1" width="30%">
<tr>
<th> Product </th>
<th> Price </th>
</tr>
<tr>
<td>Bag </td>
<td> Rs. 2500 </td>
</tr>
<tr>
<td>Jacket</td>
<td>Rs. 5000 </td>
</tr>
</table>
</body>
</html>

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 26


Explore Web using HTML, CSS and JavaScript

The 'Cellpadding' and 'Cellspacing' Attribute


These "cellpadding" and "Cellspacing" attributes are used to adjust the white spaces in your table cells.

Cellpadding attribute

The Cellpadding attribute is used to specify the space between the content of the cell and its borders. It
provides padding to the content of the cell. As its value increases the space between the cell’s content
and its border is also increases. The value of this attribute is taken in pixels by the browser. The
cellpadding is applied to all the four sides of the content. The value can also be defined in percentages.

Cellspacing attribute

The Cellspacing attribute is used to specify the space between the cells of the table. Its value can be in
pixels or in percentages. It works similar to the Cellpadding attribute but only between cells. It is applied
to all the sides of the cells.

Example

<html>
<head>
<title> HTML Table Cellpadding Attribute </title>
</head>
<body>
<table border="1" cellpadding="5" cellspacing="5" style="width:30%">
<tr>
<th>Name</th>
<th>Salary</th>
</tr>
<tr>
<td>Peter</td>
<td>5000</td>
</tr>
<tr>
<td>John</td>
<td>7000</td>
</tr>
</table>
</body>
</html>

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 27


Explore Web using HTML, CSS and JavaScript

The 'Colspan' and 'Rowspan' Attribute


These two attributes are used with the <td> tag. As the name suggests ‘colspan’ is related to
columns and ‘rowspan’ is related to rows. These two attributes are used to merge two or more
columns and rows. The colspan attribute’s value suggest the amount of column space it will
occupy. For example ‘<td colspan= 2>’ will create a cell taking space of two cells horizontally i.e.
it will occupy the space of a cell of the next column.

HTML tables can have cells that span over multiple rows and/or columns.

NAME 2022
APRIL

FIESTA

The 'Rowspan'

The rowspan attribute is used to merge two or more rows together to form a single row. A single row
occupies space of the number of merged rows.

<html>
<head> </head>
<body>
<h2>Cell that spans two rows</h2>
<table style="width:50%" border='1'>
<tr>
<th>Name</th>
<td>Jill</td>
</tr>
<tr>
<th rowspan="2">Phone</th>
<td>555-1234</td>
</tr>
<tr>
<td>555-8745</td>
</tr>
</table>
</body>
</html>

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 28


Explore Web using HTML, CSS and JavaScript

The 'Colspan'
The colspan attribute is used to merge two or more columns into a single column. single column
occupies space of the number of merged columns.

<html>
<head>
</head>
<body>
<h2>Cell that spans two columns</h2>
<p>To make a cell span more than one column, use the colspan attribute.</p>
<table style="width:50%" border='1'>
<tr>
<th colspan="2">Name</th>
<th>Age</th>
</tr>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>43</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>57</td>
</tr>
</table>
</body>
</html>

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 29


Explore Web using HTML, CSS and JavaScript

Lab Assignment
1. Create the below webpage with basic HTML List tags

List of Courses

 Programming Courses

1. PYTHON
2. Java
3. C Programming

 Web Designing Courses

a. HTML
b. CSS
c. Bootstrap

2. Create the below webpage with basic HTML List tags

1. Fruit
1. Apples
2. Oranges
3. Pears
4. Mango
2. Vegetables
1. Broccoli
2. Peas
3. Capsicum
1. Green Capsicum
2. Yellow Capsicum
3. Red Capsicum
4. Corn

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 30


Explore Web using HTML, CSS and JavaScript

3. Create the below table with basic HTML Table tags

Basic Course
Sr. Course Name Fees Duration Eligibility
No
1 CCC - Course on Computer Concept ₹ 4000 3 10th
Months
2 CCA - Course on Computer ₹ 3000 3 10th
Application Months
3 Tally ₹ 4000 3 10th
Months
4 O Level ₹ 1 Year 12th
20,000
4. Create the below table with basic HTML Table tags

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 31


Explore Web using HTML, CSS and JavaScript

CHAPTER 3
HTML – Building Forms and Hyperlinks

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 32


Explore Web using HTML, CSS and JavaScript

HTML Forms

An HTML form is used to collect user input. The user input is most often sent
to a server for processing.

The <form> Element

The HTML <form> element is used to create an HTML form for user input:

<form>
form elements
</form>

The <form> element is a container for different types of input elements, such as: text fields, checkboxes,
radio buttons, submit buttons, etc.

The <input> Element

The HTML <input> element is the most used form element.

An <input> element can be displayed in many ways, depending on the type attribute.

Here are some examples:

Type Description

<input type="text"> Displays a single-line text input field

<input type="radio"> Displays a radio button (for selecting one of many choices)

<input type="checkbox"> Displays a checkbox (for selecting zero or more of many choices)

<input type="submit"> Displays a submit button (for submitting the form)

<input type="button"> Displays a clickable button

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 33


Explore Web using HTML, CSS and JavaScript

HTML forms are used to collect user inputs, and several form elements are available to facilitate
this. Here is an overview of important form elements:

1. Text Field (<input type="text">)

 Description: Used to create a single-line text input field.


 Attributes:
o name: Specifies the name of the input field.
o value: Defines the default value.
o placeholder: Provides a hint inside the text field.
o maxlength: Sets the maximum number of characters.
o required: Marks the field as mandatory.

<input type="text" name="username" placeholder="Enter your name" maxlength="30" required>

2. Radio Button (<input type="radio">)

 Description: Allows users to select only one option from a group.


 Attributes:
o name: Groups radio buttons together (must be the same for related options).
o value: Specifies the value that will be sent when the form is submitted.
o checked: Pre-selects an option.

<input type="radio" name="gender" value="male" checked> Male

<input type="radio" name="gender" value="female"> Female

3. Checkbox (<input type="checkbox">)

 Description: Allows users to select one or more options from a group.


 Attributes:
o name: Name of the checkbox field.
o value: Specifies the value sent when the checkbox is checked.
o checked: Pre-checks the checkbox.

Example:

<input type="checkbox" name="hobby" value="reading"> Reading

<input type="checkbox" name="hobby" value="sports" checked> Sports

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 34


Explore Web using HTML, CSS and JavaScript

4. Select (<select>)

 Description: Creates a dropdown menu.


 Attributes:
o name: Name of the dropdown list.
o multiple: Allows multiple selections.
o size: Specifies the number of visible options.

<select name="country">

<option value="india">India</option>

<option value="usa">USA</option>

<option value="uk">UK</option>

</select>

5. Textarea (<textarea>)

 Description: Provides a multi-line text input field.


 Attributes:
o name: Name of the text area.
o rows: Specifies the number of visible text lines.
o cols: Defines the width of the textarea.
o placeholder: Provides a hint inside the textarea.

<textarea name="comments" rows="5" cols="40" placeholder="Enter your comments"></textarea>

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 35


Explore Web using HTML, CSS and JavaScript

Text Fields
The <input type="text"> defines a single-line input field for text input.

Example

<html>
<body>
<h2>Text input fields</h2>
<form>
Enter name
<input type="text" name="fna" value="">
<br> <br>
Enter age
<input type="text" name="age" size="4">

</body>
</html>

The <label> Element

The <label> tag defines a label for many form elements.

The <label> element is useful for screen-reader users, because the screen-reader will read out loud the
label when the user focuses on the input element.

Radio Buttons

The <input type="radio"> defines a radio button. Radio buttons let a user select ONE of a limited
number of choices.

Example

<html>
<body>
<h2>Radio button</h2>
<form>
Enter Gender
<input type="radio" name="gender" value="">Male
<input type="radio" name="gender" value="">Female
</body>
</html>

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 36


Explore Web using HTML, CSS and JavaScript

Checkboxes

The <input type="checkbox"> defines a checkbox. Checkboxes let a user select ZERO or MORE options
of a limited number of choices.
<html>
<body>
<h2>Checkbox </h2>
<form>
Soft Drink you prefer <br> <br>
<input type="checkbox" name="c2" value="">Coke
<input type="checkbox" name="c2" value="">Limca
<input type="checkbox" name="c3" value=""> Fanta
</body>
</html>
</body>
</html>

Select

<html>
<head>
<title>Country Selection</title>
</head>
<body>
<form>
<h2>Select your country:</h2>
<select name="country">
<option value="india">India</option>
<option value="usa">USA</option>
<option value="canada">Canada</option>
<option value="uk">UK</option>
</select><br>
<input type="submit" value="Submit">
</form>
</body>
</html>

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 37


Explore Web using HTML, CSS and JavaScript

Anchor Tag
Links are fundamental to navigating the web. In HTML, links are created using the <a> tag, also known as
the Anchor tag.

Key Characteristics of HTML Links


 Specified by the <a> tag.
 Also known as hyperlinks.
 Used to link one document to another.
 Includes a closing tag </a>.

Syntax of HTML Links

<a href="Your specified path">


content
</a>

Essential Attributes of the Anchor Tag

HTML links primarily use two attributes:


 href attribute: Defines the URL the link Worlds to.
 target attribute: Specifies where to open the linked document.

Target Attribute Values


 _blank: Opens the linked document in a new window or tab.
 _top: Opens document in the full body of the window.
 _self: Opens document in the same window or tab (default behavior).
 _parent: Opens the linked document in the parent frame.

Linking to Specific Page Sections


 Use the name or id attribute of the target section.
 Use a hyperlink with a hash (#) followed by the target id or name.

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 38


Explore Web using HTML, CSS and JavaScript

Linking and anchor in same page – An Example


Let's say you have a long webpage with multiple sections, and you want to create a link at the top that,
when clicked, takes the user directly to a specific section further down the page. You can do this using
HTML links that target specific sections.

<html lang="en">
<head>
<title>Linking to Sections on Same Page</title>
</head>
<body>
<h1>Care Container Lines - Shipping Services</h1>

<!-- Links to different sections within the same page -->


<nav>
<a href="#cargo">Cargo Services</a> |
<a href="#tracking">Tracking Services</a> |
<a href="#contact">Contact Us</a>
</nav>

<h2 id="cargo">Cargo Services</h2>


<p>We offer international and domestic cargo shipping with a variety of container sizes to suit your
needs.</p>

<h2 id="tracking">Tracking Services</h2>


<p>Our real-time tracking system allows you to monitor your shipment at every step of the way.</p>

<h2 id="contact">Contact Us</h2>


<p>For more information, reach out to our customer service team at
[email protected].</p>

<!-- Back to top link -->


<p><a href="#top">Back to Top</a></p>
</body>
</html>

Link Colors
Links typically appear in different colors based on their state:
 Active: Displayed in red and underlined like this sentence
 Visited: Appears purple and underlined like this sentence
 Unvisited: Shown as blue and underlined like this sentence

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 39


Explore Web using HTML, CSS and JavaScript

Lab Assignment 1: Booking Form for Cargo Shipment

Objective: Create a basic form for booking cargo shipment with details about
sender, receiver, and shipment.

Task:

1. Create an HTML file named booking1.html.


2. The form should collect:
o Sender's Name (Text Field)
o Receiver's Name (Text Field)
o Shipment Weight (Text Field)
o A submit button to confirm the booking.
o An image with CCL / Logo at end of the form
o

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 40


Explore Web using HTML, CSS and JavaScript

Assignment 2: Shipping Service Selection Form


Objective: Create a form where users can select their preferred shipping service.
Task:
1. Create an HTML file named service.htm
2. The form should allow customers to select:
o Shipping Method (Air Freight, Sea Freight, Road Transport) using radio buttons.
o An option for "Express Delivery" using a checkbox.

Assignment 3: Container Size Selection Form


Objective: Create a form where users can select the size of a shipping container.
Task:
1. Create an HTML file named container.htm
2. The form should provide a dropdown menu to select the container size (20ft, 40ft, 45ft).

Assignment 4: User Registration Form with Text Fields


Objective: Create a basic user registration form using text field and put this in a table.
<!DOCTYPE html>
<html>
<head> <title>User Registration</title> </head>
<body>
<h2>User Registration Form</h2>
<form>
<h2>First Name:</ h2>
<input type="text" name="firstName" required>
<h2> Last Name:</h2>
<input type="text" name="lastName" value=””>
<h2> Email">Email: <h2>
<input type="text" name="email" required><br><br>
<h2>Password:</h2>
<input type="password" name="password" required><br><br>
<input type="submit" value="Register">
</form>
</body>
</html>

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 41


Explore Web using HTML, CSS and JavaScript

CHAPTER 4
CSS – Introduction,
Different Types of CSS

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 42


Explore Web using HTML, CSS and JavaScript

What is CSS?
CSS stands for Cascading Style Sheets, it is a simple design language intended to simplify the
process of making web pages presentable using CSS properties. CSS specify how an HTML
element should be displayed on the web page. If you think of the human body as a web page
then CSS is styling part of the body. Like color of the eyes, size of the nose, skin tone, etc.

Who should learn CSS?


This CSS tutorial is designed for aspiring Web Designers and Developers from basics to advance.
CSS knowledge is must whoever wants to be a web developer, there are a lot of CSS
frameworks like Bootstrap, Tailwind CSS, etc. But having CSS knowledge is must as a web
developer.

Types of CSS
There is no types in CSS, it actually refer - "In how many ways we can use CSS?" So there are
three ways to use CSS on HTML document.

 Inline CSS: Inline CSS are directly applied on the HTML elements and it is the most
prioritize CSS among these three. This will override any external or internal CSS.
 Internal CSS: Internal CSS are defined in the HTML head section inside of <style> tag to
let the browser know where to look for the CSS.
 External CSS: External CSS are defined in a separate file that contains only CSS
properties, this is the recommended way to use CSS when you are working on projects.
It is easy to maintain and multiple CSS files can be created and you can use them by
importing it into your HTML document using HTML <link> tag.

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 43


Explore Web using HTML, CSS and JavaScript

CSS Example
Here in this example we will show you above mentioned ways to use CSS on an HTML document.

<html>
<head>
<title>CSS Tutorial</title>
<!-- Internal CSS -->

<style>
span{
color: green;
}
</style>

<!-- External CSS -->


<link rel="stylesheet" href="/css/style.css">
</head>

<body>
<h1><span>Tutorial</span>World</h1>

<!-- Inline CSS -->


<p style="font-weight: bold;
margin-top: -15px;
padding-left: 5px">
Simple & Easy <span>Learning</span>
</p>
</body>

</html>

External CSS File: We are importing this file into the above codethrough <link> tag. And the file
name is style.css. Above code will follow the style of this file on the portal you have to create
files locally and try it on your system.

body {
margin-left: 40%;
margin-top: 40%;
}

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 44


Explore Web using HTML, CSS and JavaScript

Reason to use CSS


 Responsive Design: CSS offers features like media queries that enable developers to
create responsive layouts that adapt to different screen sizes and devices, ensuring a
consistent user experience.
 Flexibility and Control: CSS provides precise control over the presentation of HTML
elements, allowing developers to customize layout, typography, colors, and other visual
properties.
 Consistency and Reusability: Developers can ensure consistency across the entire
website, by defining styles in a central CSS file. Styles can be reused across multiple
pages, reducing redundancy and making updates easier.
 Search Engine Optimization (SEO): CSS can be used to structure content in a way that
improves search engine visibility.
 Ease of Maintenance: Centralized CSS files make it easier to maintain and update styles
across a website. Changes can be applied globally, ensuring uniformity and reducing the
risk of inconsistencies.
 Faster Page Loading: External CSS files can be cached by browsers, resulting in faster
page loading times for subsequent visits to a website. This caching mechanism reduces
server load and bandwidth consumption.

CSS Syntax
One has to check the three components i.e, selector, property and value.

Selector: CSS selectors are used to select the element or groups of elements to style on a web page.

Property: A CSS property is an aspect or characteristic of an HTML element that can be styled or
modified using CSS, such as color, font-size, or margin.

Value: Values are assigned to properties. For example, color property can have value like red, green etc.

For Example:

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 45


Explore Web using HTML, CSS and JavaScript

Multiple Style Rules


If you want to define multiple rules for a single selectors you can specify those in single block
separated by a semicolon (;).

Syntax

selector{
property1: value1;
property2: value2;
property3: value3;
}

Example

<html>
<head>
<style>
p{
background-color: black; color: white; padding: 5px;
}

.special {
color: lightblue; /* Change text color */
}
</style>
</head>

<body>
<p> This a normal paragraph... </p>
<br>
<p class="special"> This is a paragraph with class special... </p>
<br>
</body>
</html>

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 46


Explore Web using HTML, CSS and JavaScript

Lab Assignment 1: Styling Text with CSS

Objective: Learn how to apply basic text styles using CSS.

Instructions:

1. Create an HTML file with a paragraph of text.


2. Use CSS to change the color, font size, and font style of the text.
3. Apply different styles for h1 and p elements.

Lab Assignment 2: Applying Backgrounds in CSS

Objective: Learn how to set background colors and background images in CSS.

Instructions:

1. Create an HTML file with a div element.


2. Apply a background color to the div.
3. Apply a background image to the same div and adjust its size.

Lab Assignment 3: CSS Borders and Padding

Objective: Learn how to use borders and padding in CSS.

Instructions:

1. Create an HTML file with a div containing some text.


2. Use CSS to apply a solid border around the div.
3. Add padding inside the div to create space between the text and the border.

Lab Assignment 3: Styling a Table with CSS

Instructions:

1. Create an HTML file with a table displaying a list of shipping services offered by "Care Container
Lines."
2. Style the table using CSS to add borders, background colors, and align text within the table cells.
3. Apply different styles to the table headers and table rows.

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 47


Explore Web using HTML, CSS and JavaScript

Lab Assignment 4: Styling an Ordered List (ol) with CSS


Instructions:
1. Create an HTML file with an ordered list that displays the steps for booking a shipping service.
2. Use CSS to change the numbering style, font size, and spacing between the items.
3. Style the ordered list to have a unique numbering style (e.g., Roman numerals, letters, etc.).

(The HTML page is created here for your reference namely Lab4.htm

<html>
<head>
<title>How to Book a Service</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>How to Book a Shipping Service</h1>
<ol>
<li>Visit our website and sign in.</li>
<li>Choose the shipping service you require.</li>
<li>Enter the shipping details, including destination and package size.</li>
<li>Review and confirm your booking.</li>
<li>Make the payment to complete the booking process.</li>
</ol>
</body>
</html>

style.css

/* Styling for the ordered list */


ol {
list-style-type: upper-roman; /* Changes numbering style to Roman numerals */
margin-left: 30px;
padding-left: 10px;
font-size: 18px;
color: darkblue;
}

/* Styling for individual list items */


ol li {
margin-bottom: 10px;
}

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 48


Explore Web using HTML, CSS and JavaScript

CHAPTER 5
CSS – Selectors and Box Model

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 49


Explore Web using HTML, CSS and JavaScript

CSS - Selectors
CSS Selectors are used to select the HTML elements you want to style on a web page. They
allow you to target specific elements or groups of elements to apply styles like colors, fonts,
margins, and more.

The element or elements that are selected by the selector are referred to as subject of the
selector.

Types of Selectors

1. Universal Selectors
2. Element Selectors
3. Class Selectors
4. Id Selectors
5. Attribute Selectors
6. Group Selectors
7. Pseudo-element Selectors
8. Pseudo-class Selectors

CSS Universal Selector


Universal selector, denoted by an asterisk mark (*), is a special selector that matches all
elements in an HTML document. These are generally used to add a same length margin and
padding to all the elements in document.

Syntax

*{
margin: 0;
padding: 0;
}
As per the above syntax, the universal selector is used to apply a margin and padding of 0 to all
HTML elements.

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 50


Explore Web using HTML, CSS and JavaScript

Example

<html>
<head>
<style>
*{
margin: 0;
padding: 0;
background-color: peachpuff;
color: darkgreen;
font-size: 25px;
}
</style>
</head>
<body>
<h1>Universal selector (*)</h1>

<div>
Parent element
<p>Child paragraph 1</p>
<p>Child paragraph 2</p>
</div>

<p>Paragraph 3</p>
</body>
</html>

CSS Element Selector


A element selector targets an HTML element, such as <h1>, <p>, etc. This is used when we want to apply
similar style to all the <p> tags or <h1> tags in the document.

Syntax

/* Sets text color of all p tags to green */


p{
color: green;
}

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 51


Explore Web using HTML, CSS and JavaScript

Example

<html>
<head>
<style>
div {
border: 5px inset gold;
width: 300px;
text-align: center;
}

p{
color: green;
}

h1 {
text-decoration-line: underline;
}
</style>
</head>
<body>
<div>
<h1>Element selector</h1>
<p>Div with border </p>
<p>Text aligned to center</p>
<p>Paragraph with green color</p>
<p>h1 with an underline</p>
</div>
</body>
</html>

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 52


Explore Web using HTML, CSS and JavaScript

CSS Class Selector


A class selector targets an element with a specific value for its class attribute to style it. A class in CSS is
denoted by "." (period) symbol.

Syntax

.sideDiv {
text-decoration-line: underline;
}

.topDiv {
color: green;
font-size: 25px;
}

Example

Following example demonstrates the use of a class selector, where .style-div,


.topDivs and .bottomDivs are class selectors:

<html>
<head>
<style>
.class1{
border: 5px solid black; height:80px; width: 180px; text-align: center;
padding:70px;
font-size:40px;
}
</style>
</head>
<body>
<div class="class1">
This is box
</div>
</body>
</html>

CSS ID Selector

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 53


Explore Web using HTML, CSS and JavaScript

An ID selector targets single element with a particular value for id attribute to style it. An id in CSS is
denoted by "#" (hash) symbol. Same class can be applied to multiple elements, but an id is unique for an
element.

Syntax

#style-p {
color: green;
font-size: 25px;
}
#style-h1 {
text-decoration-line: underline;
color: red;
}

Example

Following example demonstrates the use of an id selector, where #style-div,


#tutorial and #styleWorld are the id selectors applied on the elements:

<html>
<head>
<style>
#style-div {
border: 5px solid red;
width: 300px;
text-align: center;
height : 200px;
background-color:green;
}
</style>
</head>
<body>
<div id="style-div">
This is box
</div>
</body>
</html>

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 54


Explore Web using HTML, CSS and JavaScript

CSS Group Selector


CSS group selector allow us to apply same style to multiple elements at a time. Name of
elements can be separated by commas. This method is recommended as it keep CSS concise
and avoid redundancy.

Syntax

/* Apply same background color for h1 and h2 */


h1, h2 {
background-color: grey;
}

Example

<html>
<head>
<style>
/* This applies to both <h1> and <h2> elements */
h1, h2 {
background-color: grey;
padding: 4px;
}

</style>
</head>
<body>
<h1>CSS Selectors</h1>
<h2>Group Selectors</h2>
</body>
</html>

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 55


Explore Web using HTML, CSS and JavaScript

CSS Pseudo Class Selector


A pseudo-class selector is used to style a specific state of an element, such as :hover is used to style an
element when hovered.

Syntax

/* Change background color on hover */


a :hover {
background-color: peachpuff;
}
/* Change background color on clicking button */
button:active {
background-color: yellow;
}
/* Change border color on focusing input */
input:focus {
border-color: blue;
}

Example
<html>
<head>
<style>
a:hover {
background-color: peachpuff; color: green; font-size: 2em;
}
button:active {
background-color: yellow;
}
</style>
</head>
<body>
<h2>Pseudo-class selector</h2>
<p> Styling applied to anchor element and button with a pseudo-class: </p>
<a href="https://www.onwardacademy.in"> Onward Academy </a>
<br><br> <button>Click Me</button>
</body>
</html>

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 56


Explore Web using HTML, CSS and JavaScript

CSS Pseudo Element Selector


A pseudo-element selector is used to style a specific part of an element rather than the element itself.

Syntax

/* Define contents before paragraph */


a::before {
content: " ";
}

/* Style first letter of paragraph */


p::first-letter {
font-size: 2em;
}

Example
<html>
<head>
<style>
/* Add and style contents before paragraph */
p::before {
content: "Note: ";
font-weight: bold;
color: red;
}

/* Add and style contents after paragraph */


p::after {
content: " [Read more]";
font-style: italic;
color: blue;
}
</style>
</head>
<body>
<h2>Pseudo-element selector</h2>
<p>This is a paragraph.</p>
</body>
</html>

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 57


Explore Web using HTML, CSS and JavaScript

CSS Box Model


In CSS, the term "box model" is used when talking about design and layout.

The CSS box model is essentially a box that wraps around every HTML element. It consists of:
content, padding, borders and margins. The image below illustrates the box model:

Explanation of the different parts:

 Content - The content of the box, where text and images appear
 Padding - Clears an area around the content. The padding is transparent
 Border - A border that goes around the padding and content
 Margin - Clears an area outside the border. The margin is transparent

The box model allows us to add a border around elements, and to define space between
elements.

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 58


Explore Web using HTML, CSS and JavaScript

Example

<!DOCTYPE html>
<html>
<head>
<style>
div {
background-color: lightgrey;
width: 300px;
border: 15px solid green;
padding: 50px;
margin: 20px;
}
</style>
</head>
<body>
<h2>Demonstrating the Box Model</h2>
<div></div>
</body>
</html>

Width and Height of an Element


<html>
<head>
<style>
div {
width: 320px;
height: 50px;
padding: 10px;
border: 5px solid gray;
margin: 0;
}
</style>
</head>
<body>
<div> The total width of this element is also 350px. The total height of this element is 80px.</div>
</body>
</html>

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 59


Explore Web using HTML, CSS and JavaScript

Lab Assignment 1: Styling Heading Tags

Objective: Learn how to style different heading tags (h1 to h6) using CSS.

Instructions:

1. Create an HTML page with a title and at least six headings (h1 to h6).
2. Use CSS to style each heading with different font sizes, colors, and text alignments.
3. Add different background colors or borders for each heading.

html >
style2.css
<head>
<title>Styling Headings</title>
<link rel="stylesheet" href="style2.css"> h1 {
</head> color: darkblue;
<body> font-size: 40px;
<h1>Main Heading (h1)</h1>
text-align: center;
<h2>Subheading (h2)</h2>
<h3>Subheading Level 3 (h3)</h3> background-color: lightgray;

<h4>Subheading Level 4 (h4)</h4> padding: 10px;


<h5>Subheading Level 5 (h5)</h5> }
<h6>Subheading Level 6 (h6)</h6> // same way do for h2 – h6 with different style
</body>
</html>

Lab Assignment 2: Styling Unordered List (Bullets)

Objective: Learn how to style unordered lists using different bullet types and text styles.

Instructions:

1. Create an HTML page with an unordered list of items (e.g., services provided by "Care Container
Lines").
2. Use CSS to change the bullet style of the unordered list (ul).
3. Experiment with different list styles like circle, square, and none. Also, apply custom styles
like padding, margins, and background colors.

Hint: ul { list-style-type: square; padding-left: 30px; }

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 60


Explore Web using HTML, CSS and JavaScript

Lab Assignment 3: Styling Unordered Lists with CSS

Objective: Learn how to style unordered lists (ul) and list items (li) using CSS.

Instructions:

1. Create an unordered list with five items, describing services offered by "Care Container Lines."
2. Use CSS to change the bullet style, list item text color, and spacing.
3. Add hover effects for the list items (e.g., changing the color when hovered).

<html>
// style3.css
<head>
ul {
<title>Unordered List Example</title>
list-style-type: square;
<link rel="stylesheet" href="style3.css">
padding-left: 20px;
</head>
}
<body>
<h2>Our Services</h2>
<ul> li {
font-size: 18px;
<li>Cargo Shipping</li>
color: darkblue;
<li>Container Tracking</li>
margin-bottom: 10px;
<li>Customs Clearance</li>
}
<li>Warehousing</li>
<li>Freight Forwarding</li>
li:hover {
</ul>
color: green;
font-weight: bold;
</body>
</html> }

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 61


Explore Web using HTML, CSS and JavaScript

Lab Assignment 4: Styling Images with CSS

Objective: Learn how to style images using CSS, including width, height, borders, and
alignment.

Instructions:

1. Create an HTML file with an image of a cargo ship (use a placeholder image if necessary).
2. Style the image using CSS to control its size, add borders, and align it to the center of the page.
3. Apply hover effects to the image (e.g., increasing its size on hover).

<!DOCTYPE html>
<html lang="en">
// style4.css
<head>
.cargo-image {
<title>Image Styling Example</title>
<link rel="stylesheet" href="image-styles.css"> width: 60%;
</head> display: block;
<body> margin: 20px auto;
<h1> Simple stylesheet with Image </h1> border: 5px solid darkblue;
border-radius: 10px;
<h2>Our Cargo Ship</h2> }

<img src="cargo-ship.jpg" alt="Cargo Ship" .cargo-image:hover {


class="cargo-image"> transform: scale(1.05); /* Slight zoom on
hover */
</body> transition: transform 0.3s ease;
</html> }

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 62


Explore Web using HTML, CSS and JavaScript

CHAPTER 6
JavaScript – Introduction and Overview

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 63


Explore Web using HTML, CSS and JavaScript

Introduction to JavaScript
 JavaScript is the scripting language of the Web.

 JavaScript is used in millions of Web pages to add functionality, validate forms, detect
browsers, and much more.

 JavaScript is used in millions of Web pages to improve the design, validate forms, detect
browsers, create cookies, and much more.

 JavaScript is the most popular scripting language on the Internet, and works in all major
browsers, such as Internet Explorer, Mozilla Firefox, and Opera.

What is JavaScript?

 JavaScript was designed to add interactivity to HTML pages


 JavaScript is a scripting language
 A scripting language is a lightweight programming language
 JavaScript is usually embedded directly into HTML pages
 JavaScript is an interpreted language (means that scripts execute without preliminary
compilation)
 Everyone can use JavaScript without purchasing a license

Java and JavaScript are two completely different languages in both concept and design!

Java (developed by Sun Microsystems) is a powerful and much more complex programming language -
in the same category as C and C++.

What can a JavaScript Do?

 JavaScript gives HTML designers a programming tool - HTML authors are normally not
programmers, but JavaScript is a scripting language with a very simple syntax! Almost
anyone can put small "snippets" of code into their HTML pages
 JavaScript can put dynamic text into an HTML page - A JavaScript statement like this:
document.write("<h1>" + name + "</h1>") can write a variable text into an HTML page
 JavaScript can react to events - A JavaScript can be set to execute when something
happens, like when a page has finished loading or when a user clicks on an HTML
element
 JavaScript can read and write HTML elements - A JavaScript can read and change the
content of an HTML element
Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 64
Explore Web using HTML, CSS and JavaScript

 JavaScript can be used to validate data - A JavaScript can be used to validate form data
before it is submitted to a server. This saves the server from extra processing
 JavaScript can be used to detect the visitor's browser - A JavaScript can be used to
detect the visitor's browser, and - depending on the browser - load another page
specifically designed for that browser

JavaScript Variables
 Variables are "containers" for storing information. JavaScript variables are used to hold values or
expressions.

 A variable can have a short name, like x, or a more descriptive name, like carname. Rules for
JavaScript variable names:

 Variable names are case sensitive (y and Y are two different variables)

 Variable names must begin with a letter or the underscore character Note: Because JavaScript is
case-sensitive, variable names are case-sensitive. Example

 A variable's value can change during the execution of a script. You can refer to a variable by its
name to display or change its value.

Example

<html>
<body>
<script type="text/javascript">
var firstname;
firstname="Hello! This is first javascript code";
document.write(firstname);
</script>

<p>The script above declares a variable,


assigns a value to it, displays the value, change the value, and displays the value again.</p>

</body>
</html>

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 65


Explore Web using HTML, CSS and JavaScript

Declaration
var: Declares a variable that is function-scoped or globally scoped. It's an older way to declare variables
and has some quirks due to hoisting.

var x; // Declaration

let: Declares a block-scoped variable, meaning it's limited to the block in which it is defined (like inside a
loop or an if statement).

let y; // Declaration

const: Declares a block-scoped variable that cannot be reassigned. You must initialize it at the time of
declaration.

const z = 10; // Declaration and initialization

Assignment
You can assign a value to a variable using the assignment operator =:

var x = 5; // Assigning 5 to x
let y = 10; // Assigning 10 to y
const z = 20; // z is initialized to 20 and cannot be reassigned

Examples

// Using var
var name = "Alice"; // Declaration and assignment
document.write(name); // Output: Alice

// Using let
let age = 25; // Declaration and assignment
age = 26; // Reassignment is allowed
document.write(age); // Output: 26

// Using const
const PI = 3.14; // Declaration and assignment
// PI = 3.14159; // This would throw an error because const cannot be reassigned
Document.write(PI); // Output: 3.14

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 66


Explore Web using HTML, CSS and JavaScript

Summary

 Use var for function-scoped variables (generally not recommended in modern code).
 Use let for block-scoped variables when you expect to change the value.
 Use const for block-scoped variables when you want to prevent reassignment.

DataTypes

 Numbers - are values that can be processed and calculated. You don't enclose them in quotation
marks. The numbers can be either positive or negative.

 Strings - are a series of letters and numbers enclosed in quotation marks. JavaScript uses the
string literally; it doesn't process it. You'll use strings for text you want displayed or values you
want passed along.

 Boolean (true/false) - lets you evaluate whether a condition meets or does not meet specified
criteria.

 Null - is an empty value. null is not the same as 0 -- 0 is a real, calculable number, whereas null is
the absence of any value.

Data Types

TYPE EXAMPLE
Numbers Any number, such as 17, 21, or 54e7
Strings "Greetings!" or "Fun"
Boolean Either true or false
Null A special keyword for exactly that – the null value (that is, nothing)

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 67


Explore Web using HTML, CSS and JavaScript

JavaScript Arithmetic Operators

Arithmetic operators are used to perform arithmetic between variables and/or values. Given that y=5,
the table below explains the arithmetic operators:

Operator Description Example Result


+ Addition x=y+2 x=7
- Subtraction x=y-2 x=3
* Multiplication x=y*2 x=10
/ Division x=y/2 x=2.5
% Modulus (division remainder) x=y%2 x=1
++ Increment x=++y x=6
-- Decrement x=--y x=4

JavaScript Assignment Operators

Assignment operators are used to assign values to JavaScript variables. Given that x=10 and y=5, the
table below explains the assignment operators:

Operator Example Same As Result


= x=y x=5
+= 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

In JavaScript, the + operator serves two primary purposes: addition and string concatenation.
Here's how it works in each case:

1. Addition

When used with numbers, the + operator performs arithmetic addition:

let a = 5;
let b = 10;
let sum = a + b; // sum will be 15
document.write(sum); // Output: 15

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 68


Explore Web using HTML, CSS and JavaScript

2. String Concatenation

When used with strings, the + operator concatenates (joins) them:

let greeting = "Hello, ";


let name = "Alice";
let message = greeting + name; // message is concatenation of two string objects
document.write(message); // Output: Hello, Alice

3. Mixed Types

If the + operator is used with a mix of numbers and strings, JavaScript will convert numbers to
strings and concatenate:

let num = 5;
let str = " apples";
let result = num + str; // result will be "5 apples"
document.write(result); // Output: 5 apples

Summary
 Addition for numbers: 5 + 10 results in 15.
 Concatenation for strings: "Hello" + " World" results in "Hello World".
 Mixed types result in string concatenation, with numbers converted to strings.

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 69


Explore Web using HTML, CSS and JavaScript

Comparison Operators
Comparison operators are used in logical statements to determine equality or difference between
variables or values.

Given that x=5, the table below explains the comparison operators:

Operator Description Example


== is equal to x==8 is false
=== is exactly equal to (value and type) x===5 is true x==="5" is false
!= is not equal x!=8 is true
> is greater than x>8 is false
< is less than x<8 is true
>= is greater than or equal to x>=8 is false
<= is less than or equal to x<=8 is true

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:

Operator Description Example


&& and (x < 10 && y > 1) is true
|| or (x==5 || y==5) is false
! not !(x==y) is true

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 70


Explore Web using HTML, CSS and JavaScript

Conditional Operator
JavaScript also contains a conditional operator that assigns a value to a variable based on some
condition

Syntax

variablename=(condition)?value1:value2

Example

greeting=(visitor=="PRES")?"Dear President ":"Dear ";

If the variable visitor has the value of "PRES", then the variable greeting will be assigned the value "Dear
President " else it will be assigned "Dear".

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 71


Explore Web using HTML, CSS and JavaScript

CHAPTER 7
JavaScript – Controls Statement, Functions

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 72


Explore Web using HTML, CSS and JavaScript

Conditional Statements
Very often when you write code, you want to perform different actions for different decisions.
You can use conditional statements in your code to do this.

In JavaScript we have the following conditional statements:

 if statement - use this statement if you want to execute some code only if a specified
condition is true

 if...else statement - use this statement if you want to execute some code if the
condition is true and another code if the condition is false

 if...else if......else statement - use this statement if you want to select one of many
blocks of code to
be executed

 switch statement - use this statement if you want to select one of many blocks of code
to be executed

1. if statement

The if statement in JavaScript is used for conditional execution. It allows you to execute a block
of code if a specified condition evaluates to true. Here’s a breakdown of how it works, along
with some examples.

Basic Syntax

if (condition) {
// Code to be executed if the condition is true
}

Example 1: Basic if Statement

var temperature = 30;

if (temperature > 25) {


document.write("It's a hot day!");
}

Output: It's a hot day!

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 73


Explore Web using HTML, CSS and JavaScript

Example 2: if...else Statement

var temperature = 20;

if (temperature > 25) {


document.write("It's a hot day!");
}

else {
document.write ("It's a nice day!");
}

Output: It's a nice day!

Example 3: if...else if...else Statement

var temperature = 15;

if (temperature > 25) {


document.write("It's a hot day!");
}
else if (temperature > 15) {
document.write ("It's a warm day!");
}
else {
document.write ("It's a cold day!");
}

Output: It's a cold day!

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 74


Explore Web using HTML, CSS and JavaScript

Example 4: Using Logical Operators

var temperature = 22;


var isRaining = false;

if (temperature > 20 && !isRaining) {


document.write("It's a great day for a walk!");
} else {
document.write ("Maybe stay indoors.");
}

Output: It's a great day for a walk!

2. if statement

The switch statement in JavaScript is a control structure that allows you to execute different
blocks of code based on the value of a variable or expression. It can be a cleaner alternative to
multiple if...else if statements, especially when dealing with many conditions.

Basic Syntax

switch (expression) {
case value1:
// Code to be executed if expression === value1
break;
case value2:
// Code to be executed if expression === value2
break;
// You can add more cases as needed
default:
// Code to be executed if expression doesn't match any case
break;
}

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 75


Explore Web using HTML, CSS and JavaScript

Example 1: Basic switch Statement

var day = 3;
var dayName;

switch (day) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
case 4:
dayName = "Thursday";
break;
case 5:
dayName = "Friday";
break;
case 6:
dayName = "Saturday";
break;
case 7:
dayName = "Sunday";
break;
default:
dayName = "Invalid day";
}

document.write(dayName);

Output : Wednesday

Loops in JavaScript are used to execute a block of code repeatedly as long as a specified condition is
true. JavaScript provides several types of loops, each suited for different scenarios. Here’s a detailed
look at the various types of loops and their usage:

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 76


Explore Web using HTML, CSS and JavaScript

Loops in JavaScript
1. For Loop

The for loop is commonly used when you know how many times you want to execute a block of
code.

Syntax:
for (initialization; condition; increment) {
// Code to be executed
}

Example:

for (let i = 0; i < 5; i++) {


document.write("Iteration " + i);
}

// Output:
// Iteration 0
// Iteration 1
// Iteration 2
// Iteration 3
// Iteration 4

2. While Loop
The while loop continues to execute as long as the specified condition is true. It checks the
condition before executing the code block.

Syntax:

while (condition) {
// Code to be executed
}

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 77


Explore Web using HTML, CSS and JavaScript

Example:

let i = 0;
while (i < 5) {
document.write("Iteration " + i);
i++;
}

// Output:
// Iteration 0
// Iteration 1
// Iteration 2
// Iteration 3
// Iteration 4

3. Do...While Loop
The do...while loop is similar to the while loop, but it checks the condition after executing the
code block. This means the code will run at least once.

Syntax:

do {
// Code to be executed
} while (condition);

Example:

var i = 0;
do {
console.log("Iteration " + i);
i++;
} while (i < 5);

// Output:
// Iteration 0
// Iteration 1
// Iteration 2
// Iteration 3
// Iteration 4

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 78


Explore Web using HTML, CSS and JavaScript

4. For...of Loop
The for...of loop is used to iterate over iterable objects (like arrays, strings, etc.). It provides a
simpler syntax for looping through elements.

Syntax:

for (const element of iterable) {


// Code to be executed
}

Example:

const fruits = ["apple", "banana", "cherry"];

for (const fruit of fruits) {


document.write(fruit);
}

// Output:
// apple
// banana
// cherry

5. For...in Loop
The for...in loop is used to iterate over the properties of an object. It is not recommended for
arrays due to potential issues with inherited properties.

Syntax:

for (const key in object) {


// Code to be executed
}

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 79


Explore Web using HTML, CSS and JavaScript

Example:
const person = {
name: "Alice",
age: 25,
city: "New York"
};

for (const key in person) {


document.write(key + ": " + person[key]);
}

// Output:
// name: Alice
// age: 25
// city: New York

6. Breaking Out of Loops


You can use the break statement to exit a loop early.

Example:

for (let i = 0; i < 10; i++) {


if (i === 5) {
break; // Exit the loop when i is 5
}
document.write(i);
}

// Output:
// 0
// 1
// 2
// 3
// 4

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 80


Explore Web using HTML, CSS and JavaScript

7. Skipping Iterations with Continue


The continue statement skips the current iteration and moves to the next one.

Example:

for (let i = 0; i < 10; i++) {


if (i % 2 === 0) {
continue; // Skip even numbers
}
document.write(i);
}

// Output:
// 1
// 3
// 5
// 7
// 9

Summary

 For Loop: Use when you know the number of iterations.


 While Loop: Use when the number of iterations is not known and depends on a condition.
 Do...While Loop: Similar to while, but guarantees at least one iteration.
 For...of Loop: Use for iterating over iterable objects like arrays and strings.
 For...in Loop: Use for iterating over object properties.
 Break and Continue: Control flow within loops to exit or skip iterations.

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 81


Explore Web using HTML, CSS and JavaScript

JavaScript Functions
A function (also known as a method) is a self-contained piece of code that performs a particular
"function". You can recognise a function by its format - it's a piece of descriptive text, followed
by open and close brackets. A function is a reusable code-block that will be executed by an
event, or when the function is called.

To keep the browser from executing a script when the page loads, you can put your script into a
function. A function contains code that will be executed by an event or by a call to that
function.
You may call a function from anywhere within the page (or even from other pages if the
function is embedded in an external .js file).

Functions can be defined both in the <head> and in the <body> section of a document.
However, to assure that the function is read/loaded by the browser before it is called, it could
be wise to put it in the
<head> section.

Example

<html>
<head>
<script type="text/javascript">
function displaymessage()
{
alert("Hello World!");
}
</script>
</head>
<body>
<form>
<input type="button" value="Click me!" onclick="displaymessage()" >
</form>
</body>
</html>

If the line: alert("Hello world!!") in the example above had not been put within a function, it
would have been executed as soon as the line was loaded. Now, the script is not executed
before the user hits the button. We have added an onClick event to the button that will execute
the function displaymessage() when the button is clicked.

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 82


Explore Web using HTML, CSS and JavaScript

1. Function Declaration

A function can be declared using the function keyword followed by a name, parentheses for
parameters, and curly braces to enclose the code block.

Syntax:

function functionName(parameters) {
// Code to be executed
}

Example:

function greet(name) {
console.log("Hello, " + name + "!");
}

greet("Alice"); // Outputs: Hello, Alice!

2. Function Expression

A function expression defines a function inside an expression. This can be anonymous (without
a name) or named.

Syntax:

const functionName = function(parameters) {


// Code to be executed
};

Example:

const add = function(x, y) {


return x + y;
};

document.write(add(5, 3)); // Outputs: 8

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 83


Explore Web using HTML, CSS and JavaScript

3. Arrow Functions

Arrow functions provide a shorter syntax for writing function expressions. They also do not
have their own this, making them useful for certain contexts (like callbacks).

Syntax:

const functionName = (parameters) => {


// Code to be executed
};

Example:

const multiply = (a, b) => a * b;

document.write(multiply(4, 5)); // Outputs: 20

4. Function Parameters and Arguments

Functions can take parameters, which are values passed into them when they are called. You
can also set default values for parameters.

Example:

function greet(name = "Guest") {


document.log("Hello, " + name + "!");
}

greet("Alice"); // Outputs: Hello, Alice!


greet(); // Outputs: Hello, Guest!

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 84


Explore Web using HTML, CSS and JavaScript

How to Define a Function

The syntax for creating a function is:

function functionname(var1,var2,...,varX)

{
some code

var1, var2, etc are variables or values passed into the function. The { and the } defines the start and end
of the function.

Note: A function with no parameters must include the parentheses () after the function name:

function functionname()
{
some code
}

Note: Do not forget about the importance of capitals in JavaScript! The word function must be written
in lowercase letters, otherwise a JavaScript error occurs! Also note that you must call a function with
the exact same capitals as in the function name.

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 85


Explore Web using HTML, CSS and JavaScript

The return Statement

The return statement is used to specify the value that is returned from the function. So,
functions that are going to return a value must use the return statement.

Example

The function below should return the product of two numbers (a and b):

function prod(a,b)
{
x=a*b;
return x;
}

When you call the function above, you must pass along two parameters:

product=prod(2,3);

The returned value from the prod() function is 6, and it will be stored in the variable called product.

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 86


Web Tools using HTML,CSS and Javascript 2024

CHAPTER 8
JavaScript – Event Handling

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 87


Web Tools using HTML,CSS and Javascript 2024

What is an Event?

An event is an action or occurrence recognized by the browser, which can trigger a response. Examples
include:

 User actions: clicks, mouse movements, keyboard presses, etc.


 Browser actions: page load, resize, etc.
 Other actions: form submissions, media playback, etc.

Event Handlers

Event Handlers are JavaScript methods, i.e. functions of objects, that allow us as JavaScript programmers to
control what happens when events occur.

Directly or indirectly, an Event is always the result of something a user does. For example, we've already seen
Event Handlers like onClick and onMouseOver that respond to mouse actions. Another type of Event, an
internal change-of-state to the page (completion of loading or leaving the page). An onLoad Event can be
considered an indirect result of a user action.

Although we often refer to Events and Event Handlers interchangeably, it's important to keep in mind the
distinction between them. An Event is merely something that happens - something that it is initiated by an
Event Handler (onClick, onMouseOver, etc...).

The elements on a page which can trigger events are known as "targets" or "target elements," and we can
easily understand how a button which triggers a Click event is a target element for this event. Typically,
events are defined through the use of Event Handlers, which are bits of script that tell the browser what to
do when a particular event occurs at a particular target. These Event Handlers are commonly written as
attributes of the target element's HTML tag.

The Event Handler for a Click event at a form field button element is quite simple to understand:

<INPUT TYPE="button" NAME="click1" VALUE="Click me for fun!"


onClick="event_handler_code">

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 88


Web Tools using HTML,CSS and Javascript 2024

The event_handler_code portion of this example is any valid JavaScript and it will be executed when the
specified event is triggered at this target element. This particular topic will be continued in Incorporating
JavaScripts into your HTML pages.

There are "three different ways" that Event Handlers can be used to trigger Events or Functions.

1. Method 1 (Link Events):

Places an Event Handler as an attribute within an <A HREF= > tag, like this:

<A HREF="foo.html" onMouseOver="doSomething()"> ... </A>

You can use an Event Handler located within an <A HREF= > tag to make either an image or a text link
respond to a mouseover Event. Just enclose the image or text string between the <A HREF= > and the
</A> tags.

Whenever a user clicks on a link, or moves her cursor over one, JavaScript is sent a Link Event. One Link Event
is called onClick, and it gets sent whenever someone clicks on a link. Another link event is called
onMouseOver. This one gets sent when someone moves the cursor over the link.

You can use these events to affect what the user sees on a page. Here's an example of how to use link
events. Try it out, View Source, and we'll go over it.

<A HREF="javascript:void('')"
onClick="open('index.htm', 'links', 'height=200,width=200');">How to Use Link Events
</A>

The first interesting thing is that there are no <SCRIPT> tags. That's because anything that appears in the
quotes of an onClick or an onMouseOver is automatically interpreted as JavaScript. In fact, because
semicolons mark the end of statements allowing you to write entire JavaScripts in one line, you can fit an
entire JavaScript program between the quotes of an onClick. It'd be ugly, but you could do it.

Here are the three lines of interest:

 <A HREF="#" onClick="alert('Ooo, do it again!');">Click on me!</A>


 <A HREF="javascript:void('')" onClick="alert('Ooo, do it again!');"> Click on me! </A>
 <A HREF="javascript:alert('Ooo, do it again!')" >Click on me!</A>

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 89


Web Tools using HTML,CSS and Javascript 2024

In the first example we have a normal <A> tag, but it has the magic onClick="" element, which says, "When
someone clicks on this link, run the little bit of JavaScript between my quotes." Notice, there's even a
terminating semicolon at the end of the alert. Question: is this required? NO.

Let's go over each line:

 HREF="#" tells the browser to look for the anchor #, but there is no anchor "#", so the browser
reloads the page and goes to top of the page since it couldn't find the anchor.

 <A HREF="javascript:void('')" tells the browser not to go anywhere - it "deadens" the link when you
click on it.
HREF="javascript: is the way to call a function when a link (hyperlink or an HREFed image) is clicked.

 HREF="javascript:alert('Ooo, do it again!')" here we kill two birds with one stone. The default
behavior of a hyperlink is to click on it. By clicking on the link we call the window Method alert() and
also at the same time "deaden" the link.

The next line is

<A HREF="javascript:void('')" onMouseOver="alert('Hee hee!');"> Mouse over me!


</A>

This is just like the first line, but it uses an onMouseOver instead of an onClick.

2. Method 2 (Actions within FORMs):

The second technique we've seen for triggering a Function in response to a mouse action is to place an
onClick Event Handler inside a button type form element, like this:

<FORM>
<INPUT TYPE="button" onClick="doSomething()">
</FORM>

While any JavaScript statement, methods, or functions can appear inside the quotation marks of an Event
Handler, typically, the JavaScript script that makes up the Event Handler is actually a call to a function
defined in the header of the document or a single JavaScript command. Essentially, though, anything that
appears inside a command block (inside curly braces {}) can appear between the quotation marks.

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 90


Web Tools using HTML,CSS and Javascript 2024

For instance, if you have a form with a text field and want to call the function checkField() whenever the
value of the text field changes, you can define your text field as follows:

<INPUT TYPE="text" onChange="checkField(this)">

Nonetheless, the entire code for the function could appear in quotation marks rather than a function call:

<INPUT TYPE="text" onChange="if (this.value <= 5) {


alert("Please enter a number greater than 5");
}">

To separate multiple commands in an Event Handler, use semicolons

<INPUT TYPE="text" onChange="alert(‘Thanks for the entry.’);


confirm(‘Do you want to continue?’);">

The advantage of using functions as Event Handlers, however, is that you can use the same Event Handler
code for multiple items in your document and, functions make your code easier to read and understand.

3. Method 3 (BODY onLoad & onUnLoad):

The third technique is to us an Event Handler to ensure that all required objects are defined involve
the onLoad and onUnLoad. These Event Handlers are defined in the <BODY> or <FRAMESET> tag of
an HTML file and are invoked when the document or frameset are fully loaded or unloaded. If you
set a flag within the onLoad Event Handler, other Event Handlers can test this flags to see if they can safely
run, with the knowledge that the document is fully loaded and all objects are defined.

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 91


Web Tools using HTML,CSS and Javascript 2024

For example:
<SCRIPT>
var loaded = false;
function doit() {
// alert("Everything is \"loaded\" and loaded = " + loaded);
alert('Everything is "loaded" and loaded = ' + loaded);
}
</SCRIPT>
<BODY onLoad="loaded = true;">
-- OR --

<BODY onLoad="window.loaded = true;">

<FORM>
<INPUT TYPE="button" VALUE="Press Me"
onClick="if (loaded == true) doit();">

-- OR --

<INPUT TYPE="button" VALUE="Press Me"


onClick="if (window.loaded == true) doit();">

-- OR --

<INPUT TYPE="button" VALUE="Press Me"


onClick="if (loaded) doit();">
</FORM>

</BODY>

The onLoad Event Handler is executed when the document or frameset is fully loaded, which means that all
images have been downloaded and displayed, all subframes have loaded, any Java Applets and Plugins
(Navigator) have started running, and so on. The onUnLoad Event Handler is executed just before the page is
unloaded, which occurs when the browser is about to move on to a new page. Be aware that when you are
working with multiple frames, there is no guarantee of the order in which the onLoad Event Handler is
invoked for the various frames, except that the Event Handlers for the parent frame is invoked after the
Event Handlers of all its children frames -- This will be discussed in detail in Week 8.

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 92


Web Tools using HTML,CSS and Javascript 2024

Example : Addition of two numbers using onClick event

<html>
<head>
<script>
function doAdd()
{
a=document.f1.aa.value;
b=document.f1.bb.value;

a=parseInt(a); // wrapper class conversion


b=parseInt(b); // wrapper class conversion

c=a+b;
document.write(" <h2> ADD= "+c);

}
</script>
</head>
<body>
<h1> ADD two number </h1>
<form name="f1">
<h2>
Enter 1st no=
<input type="text" name="aa">
</h2>

<h2>
Enter 2nd no=
<input type="text" name="bb">
</h2>

<h2>
Click to get add
<input type="submit" name="cc" value="add" onClick="doAdd()">
</h2>
</form>
</body>

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 93


Web Tools using HTML,CSS and Javascript 2024

Example : Multiplication table of a number numbers using onClick event

<html>
<script>
function findNow()
{
n=document.f1.aa.value;
n=parseInt(n);

document.write("<h1> <font color='red'> Table of "+n+" </font> </h1>");

for(i=1;i<=10;i++)
{
t=n*i;
document.write(" <h2> "+n+" x "+i+" = "+t);
}

</script>

<body>
<form name="f1">
<h2> Find the Multiplication Table </h2>
<h3> Enter any number
<input type="text" name="aa">
</h3>

<h3> Click here to find


<input type="submit" name="bb" value="GET RESULT" onClick="findNow()">
</h3>

</form>
</body>
</html>

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 94


Web Tools using HTML,CSS and Javascript 2024

Example : Square a number numbers using onKeyup event

<html>
<script>
function findSquare()
{
n=document.f1.aa.value;
n=parseInt(n);

document.write("<h1> <font color='red'>Square of "+n+" </font> </h1>");

v = n*n;
document.write(" <h2> “+ v+ “</h2>”);

</script>

<body>
<form name="f1">
<h2> Find the Square </h2>
<h3> Enter any number
<input type="text" name="aa">
</h3>

<h3> Click here to find


<input type="submit" name="bb" value="GET RESULT" onClick="findSquare()">
</h3>

</form>
</body>
</html>

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 95


Web Tools using HTML,CSS and Javascript 2024

CHAPTER 9
JavaScript – DOM Manipulations,
Form Validations

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 96


Web Tools using HTML,CSS and Javascript 2024

DOM manipulation in JavaScript refers to the process of dynamically changing the structure, style, or content
of a web page. The Document Object Model (DOM) represents the document as a tree of objects, allowing
you to interact with HTML elements using JavaScript. Here’s a breakdown of the key methods and
techniques for DOM manipulation:

Selecting Elements
1. getElementById: Selects an element by its ID.

const element = document.getElementById('myId');

2. getElementsByClassName: Selects elements by their class name (returns a live HTMLCollection).

const elements = document.getElementsByClassName('myClass');

3. getElementsByTagName: Selects elements by their tag name (also returns a live HTMLCollection).

const elements = document.getElementsByTagName('div');

4. querySelector: Selects the first element that matches a specified CSS selector.

const element = document.querySelector('.myClass');

5. querySelectorAll: Selects all elements that match a specified CSS selector (returns a static
NodeList).

const elements = document.querySelectorAll('div.myClass');

Modifying Elements
1. Changing Text Content:

element.textContent = 'New Text';

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 97


Web Tools using HTML,CSS and Javascript 2024

2. Changing HTML Content:

element.innerHTML = '<span>New HTML</span>';

3. Changing Attributes:

element.setAttribute('src', 'newImage.png');

4. Changing Styles:

element.style.color = 'red';

element.style.backgroundColor = 'blue';

Adding and Removing Elements


1. Creating Elements:

const newElement = document.createElement('div');

newElement.textContent = 'I am a new div!';

2. Appending Elements:

document.body.appendChild(newElement); // Appends to the end of the body

3. Inserting Before an Element:

const referenceNode = document.getElementById('referenceId');

document.body.insertBefore(newElement, referenceNode);

4. Removing Elements:

const elementToRemove = document.getElementById('removeId');

elementToRemove.remove();

Example : Change background colour of a box using onClick and getElementById


Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 98
Web Tools using HTML,CSS and Javascript 2024

<!DOCTYPE html>
<html lang="en">
<head>
<title>Change Background Color</title>
<style>
#colorBox {
width: 200px;
height: 200px;
background-color: lightblue; /* Initial background color */
border: 1px solid #000;
}
</style>

<script>

function changeBack()
{
// JavaScript to change the background color
var box = document.getElementById('colorBox');

box.style.backgroundColor = "green";
}
</script>
</head>
<body>
<div id="colorBox"></div>
<button id="changeColorBtn" onclick="changeBack()">Change Color</button>

</body>
</html>

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 99


Web Tools using HTML,CSS and Javascript 2024

JavaScript Form Validation


It is important to validate the form submitted by the user because it can have inappropriate values. So,
validation is must to authenticate user.

JavaScript provides facility to validate the form on the client-side so data processing will be faster than
server-side validation. Most of the web developers prefer JavaScript form validation.

Through JavaScript, we can validate name, password, email, date, mobile numbers and more fields.

Example 1 : JavaScript Form Validation Example

In this example, we are going to validate the name and password. The name can’t be empty and password can’t be less
than 6 characters long.

Here, we are validating the form on form submit. The user will not be forwarded to the next page until given values are
correct.

<script>
function validateform(){
var name=document.myform.name.value;

if (name==null || name==""){
alert("Name can't be blank");
return false;
}else{
return true;
}
}
</script>
<body>
<form name="myform" method="post" action="abc.jsp" onsubmit="return validateform()" >
Name: <input type="text" name="name"><br/>
<input type="submit" value="register">
</form>

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 100
Web Tools using HTML,CSS and Javascript 2024

Example 2 : JavaScript Retype Password Validation

<script type="text/javascript">
function matchpass(){
var firstpassword=document.f1.password.value;
var secondpassword=document.f1.password2.value;

if(firstpassword==secondpassword){
return true;
}
else{
alert("password must be same!");
return false;
}
}
</script>

<form name="f1" action="register.jsp" onsubmit="return matchpass()">


Password:<input type="password" name="password" /><br/>
Re-enter Password:<input type="password" name="password2"/><br/>
<input type="submit">
</form>

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 101
Web Tools using HTML,CSS and Javascript 2024

Example 3 : JavaScript Number Validation

Let's validate the textfield for numeric value only. Here, we are using isNaN() function.

<script>
function validate(){
var num=document.myform.num.value;
if (isNaN(num)){
document.getElementById("numloc").innerHTML="Enter Numeric value only";
return false;
}else{
return true;
}
}
</script>
<form name="myform" onsubmit="return validate()" >
Number: <input type="text" name="num"><span id="numloc"></span><br/>
<input type="submit" value="submit">
</form>

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 102
Web Tools using HTML,CSS and Javascript 2024

Example 4 : JavaScript email validation

We can validate the email by the help of JavaScript.


There are many criteria that need to be follow to validate the email id such as:

 email id must contain the @ and . character


 There must be at least one character before and after the @.
 There must be at least two characters after . (dot).

<script>
function validateemail()
{
var x=document.myform.email.value;
var atposition=x.indexOf("@");
var dotposition=x.lastIndexOf(".");
if (atposition<1 || dotposition<atposition+2 || dotposition+2>=x.length){
alert("Please enter a valid e-mail address \n atpostion:"+atposition+"\n dotposition:"+dotposition);
return false;
}
}
</script>
<body>
<form name="myform" method="post" action="#" onsubmit="return validateemail();">
Email: <input type="text" name="email"><br/>

<input type="submit" value="register">


</form>

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 103
Web Tools using HTML,CSS and Javascript 2024

CHAPTER 10
JavaScript – Lab Assignments

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 104
Web Tools using HTML,CSS and Javascript 2024

WEB TOOLS PRACTICE SESSION


1.1 Compute the AREA of CIRCLE with the given interface below:

If you give 7 as input the output will show as given below

1.2 Modify the above program to compute AREA of triangle where inputs will be

ENTER LENGTH 10

ENTER BREADTH 8

Output will be

AREA OF TRIANGLE IS 9

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 105
Web Tools using HTML,CSS and Javascript 2024

2. 1 Create a simple Calculator to addition with ADD button, using form atrributes

Use the onClick event to get the addition total as show below.

2.2 You can later modify to implement more buttons with SUBTRACT, MULTIPLY and DIVIDE.

3 Compute the Area and Perimeter of Rectangle with the given interface below:

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 106
Web Tools using HTML,CSS and Javascript 2024

4 Change the background color of the box using dropdown (select tag)

If you choose Red from the option then background color should change to Red

You should also validate the dropdown if option chosen then it should give alert message ‘No
Option Chosen’

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 107
Web Tools using HTML,CSS and Javascript 2024

5. Choose your favorite season using radio button

6. Select your skills using Checkbox with the help of JavaScript

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 108
Web Tools using HTML,CSS and Javascript 2024

7. Validate the following form using JavaScript

If any textbox remains blank then give an alert message ‘Fields cannot be blank’ otherwise
display ‘Registration Done’

8 Convert Celsius to kelvin and Fahrenheit with the following interface

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 109
Web Tools using HTML,CSS and Javascript 2024

9.1 Calculate total bill by choosing the menu using checkbox

If no option chosen then give an alert message ‘Choose at least one item’

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 110
Web Tools using HTML,CSS and Javascript 2024

9.2 Create a login page with proper validation

9.3 Also the above task implement CSS design with hover button

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 111
Web Tools using HTML,CSS and Javascript 2024

10.1 Create a submit button with input of your name and validate it

10.2 Add also age and phone and validate the field with JavaScript on the above, i.e, 10.1

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 112
Web Tools using HTML,CSS and Javascript 2024

11. 1 Create a conversion of Celsius to Fahrenheit as given below

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 113
Web Tools using HTML,CSS and Javascript 2024

11.2 Create a banner which will come with SetTimeout and array images

Or image 2 will come, then image3 will come followed by image 4

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 114
Web Tools using HTML,CSS and Javascript 2024

12. 1 Create a round oval and fill color like this

Or it may come other colors once radio button is checked

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 115
Web Tools using HTML,CSS and Javascript 2024

12.2 Create an interface application like this

13.1 Create two texts BRAINWARE and UNIVERSITY in div like this and once they come closer
to each other it will print Best No. 1 University.

It will give output like this

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 116
Web Tools using HTML,CSS and Javascript 2024

13.2 Create now four texts in four directions of each positions of the browsers in different
four colours. and all come to center and gives a message WELCOME BRAINWARE
UNIVERSITY.

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 117
Web Tools using HTML,CSS and Javascript 2024

14. After the checkbox done in 12.2 do the following events and output with Javascript as
shown below:

Once you check custom clearance the output will be as given below:

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 118
Web Tools using HTML,CSS and Javascript 2024

15. Create a form with select

Once you select an option

The output for Cargo will be like this

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 119
Web Tools using HTML,CSS and Javascript 2024

Some keynotes to my journey of this ebook…

I would like to express my heartfelt gratitude to everyone who has supported me throughout the journey of
authoring Explore Web: HTML, CSS, and JavaScript for B.Tech., BCA, and MCA students.

This book is the culmination of over 25 years of experience in the field of web development, and it wouldn't
have been possible without the encouragement and contributions of my students, colleagues, and parents.

To my students: Your curiosity and dedication to learning have always inspired me to dive deeper and strive
for excellence. When a reputed corporate company invited me write a specific book for its employees/trainees,
it is at this juncture, inspired me to begin this book which of course needs more scope of development in terms
of more examples and elaborations of the topics. This books is not a bible of Web Tools but a pocket bible for
all Web Developers and who are novice to IT skills and Web Tools. You are really inspired me to pen this
book for your better subject knowledge.

To my colleagues: Your collaboration and insights have been invaluable in refining the concepts and approach
presented in this book. Riya Jana particularly was always there for my codes and debugs to be processed in
most easiest manner and it is great to have this kind of colleagues who can always act as an interpreter.

Thank you all for being a part of this journey. I hope this book serves as a comprehensive guide for students
exploring the fascinating world of web development.

Warm regards,
Saugata Sarkar
29/09/2024

 Any query you may please  [email protected]  90880-14097

Copyright reserved with Saugata Sarkar @ Onward Academy @ 2024 Page 120

You might also like