0% found this document useful (0 votes)
14 views284 pages

BIT - Web3

The document provides an overview of HTML, CSS, and JavaScript as essential components of web development, detailing their roles in structure, styling, and interactivity. It discusses the evolution of web generations from Web 1.0 to Web 4.0, highlighting the advancements in technology and user engagement. Additionally, it covers XHTML, HTML elements, tags, attributes, and their differences, emphasizing the importance of semantic HTML for better accessibility and search engine optimization.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views284 pages

BIT - Web3

The document provides an overview of HTML, CSS, and JavaScript as essential components of web development, detailing their roles in structure, styling, and interactivity. It discusses the evolution of web generations from Web 1.0 to Web 4.0, highlighting the advancements in technology and user engagement. Additionally, it covers XHTML, HTML elements, tags, attributes, and their differences, emphasizing the importance of semantic HTML for better accessibility and search engine optimization.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 284

HTML, CSS & JS

HTML,
CSS & JS
The Building Blocks of the Web diagram
showcases how HTML, CSS, and JavaScript
contribute to web development. HTML
provides structure, CSS adds styling, and
JavaScript enabled interactivity in web
development. Their integration creates
functional and visually appealing websites.
History

Inventor of the
World wide
web and HTML
at CERN 1993
What is HTML ?
<!DOCTYPE html>
● HTML stands for HyperText Markup <html>
Language. <head>
<title>HTML</title>
● It is used to structure content on the web. </head>
● HTML is not a programming language; it is <body>
<h1>Welcome to HTML</h1>
a markup language. <p>This is a paragraph.</p>
● Works alongside CSS for styling and </body>
</html>
JavaScript for interactivity
Evolution of Markup Language
First website on WWW

Assignment - Design a same as the first website


HTML Code to Webpage

Foundation of web page


Normal Text in HTML

Normal text is simple, plain text that is displayed on a webpage without any
special linking capabilities. It does not have any interactive features.
Hyper text in HTML

Hypertext is text that contains links to other pages, sections, or resources. It is


clickable and allows navigation between different web pages.
Web Generation

Web generation describes the different evolutionary stages of the internet's development,
where each phase introduces new technologies and ways people use the web.
Different Generations of web

Web 1.0 - The Early Web (1990s to early 2000s)

Web 2.0 - The Interactive Web (Mid-2000s to Present)

Web 3.0 - The Intelligent Web (Emerging)

Web 4.0 (Future Web) - The Intelligent and Ubiquitous Web


<html>

Web 1.0 (Static Web) <head>

<title>Web 1.0 Example</title>


Mostly read-only (static websites).
</head>
Minimal user interaction (just reading content).
<body>
Examples: Personal blogs, early news websites.
<h1>Welcome to My Website</h1>

<p>This is a simple static web page.</p>

</body>

</html>
Web 2.0 <html>
<head>
<title>Web 2.0 Example</title>
User-generated content (social media, blogs, </head>
forums). <body>
<h1>Leave a Comment</h1>
Dynamic and interactive web applications. <input type="text" placeholder="Enter your
comment">
Examples: Facebook, YouTube, Wikipedia.
<button onclick="alert('Comment
submitted!')">Submit</button>
</body>
</html>
Web 3.0

Web 3.0 is the next generation of the internet that focuses on decentralization, meaning no
single company controls data. It uses blockchain technology, artificial intelligence, and the
semantic web to create a smarter, more private, and user-controlled online experience.
Web 4.0

Fully AI-integrated, interconnected devices.

Internet of Things (IoT) and 5G integration.

Examples: Smart homes, self-driving cars, real-time AI assistants.


XHTML

XHTML (Extensible HyperText Markup Language) is a stricter, XML-based version of HTML


that ensures cleaner, well-structured, and more consistent coding practices. It was developed
by the W3C (World Wide Web Consortium) to improve web standards and ensure
compatibility with XML-based systems.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>XHTML Example</title>
</head>
<body>
<h1>Welcome to XHTML</h1>
<p>This is a paragraph written in XHTML.</p>
<img src="image.jpg" alt="Image" />
</body>
</html>
Features of XHTML
1. Stricter Syntax: Requires properly nested, closed, and case-sensitive tags.
2. XML-Based: Follows XML (Extensible Markup Language) rules, making it more structured
and compatible with other XML applications.
3. Error Handling: Unlike HTML, XHTML does not tolerate errors—any mistake can break the
page.
4. Cross-Browser Compatibility: Designed to work consistently across different browsers and
devices.
5. Well-Formatted Code: Helps in maintaining cleaner and more readable code.
Difference between HTML & XHTML
Feature HTML XHTML

Syntax More flexible and forgiving. Stricter rules, follows XML


syntax.

Tag Closing Some tags can remain All tags must be properly
unclosed (e.g., <br>, <img>, closed (e.g., <br />, <img />).
<p>).

Case Sensitivity Not case-sensitive (<title> = Case-sensitive (<title> ≠


<TITLE>). <TITLE>).
Difference between HTML & XHTML
Feature HTML XHTML

Attribute values Can be written without Must be enclosed in double


quotes (e.g., <input or single quotes (e.g., <input
type=text>). type="text">).

Doctype Declaration Supports multiple versions Must use <!DOCTYPE>


(HTML4, HTML5). declaration to define it
properly.
Example
<!DOCTYPE html>
<html>
HTML Tags <head>
<title>My First Web Page</title>
HTML tags are the fundamental </head>
building blocks of any web page. <body>
They are used to structure <h1>Welcome to My Website</h1>
content, define elements, and tell <p>This is a paragraph of text.</p>
the browser how to display that <img src="myimage.jpg" alt="My Image">
content. <a href="www.example.com">Visit Example.com</a>
</body>
</html>
HTML Reference Tag

Document Structure Tag

Text Formatting Tag

List Tags

Link and Media Tags

Table Tags

Form Tags

Semantic Tag (HTML5)


Tag <!DOCTYPE html>

<!DOCTYPE> <html>

Document structure Tag <head>


<html>
<title>HTML</title>
<head>
A document structure tag is an HTML <meta name="viewport"
<title>
element that defines the structure and content="width=device-width,

organization of a web page. These tags <body> initial-scale=1.0">

help browsers understand the content <meta> <script></script>

layout. <style></style>
<script>
</head>
<style>
<body></body>

</html>
Tag Explanation Example

<h1>-<h6 Headings (h1 is the highest level, h6 is the <h1>Main Heading</h1>


> lowest).

Text Formatting Tags


<p> Defines a paragraph of text. <p>This is a paragraph.</p>

<br> Inserts a line break (self-closing). <p>Line 1<br>Line 2</p>

<hr> creates a horizontal line on the page. <hr>


Text formatting tags in HTML are
<strong> Indicates important text (bold by default). <strong>Important!</stron
elements used to change the g>

presentation and style of text. <em> Indicates emphasized text (italic by default). <em>Emphasized
text.</em>

These tags affect how the text <span> Inline container for styling or scripting. <span
style="color:red;">Red
appears on the webpage, such as text</span>

making it bold, italic, underlined, or <pre> Displays preformatted text (preserves spaces <pre>Hello World</pre>
and line breaks).

changing its size or alignment.


<code> Displays inline code snippets. <code>console.log("Hello");
</code>
Semantic Tags
Tag Explanation Example

<header> Defines the header section of a page <header><h1>Welcome</h1></header>


or section.

Semantic tags in HTML are


<footer> Defines the footer section of a page <footer><p>Copyright 2023</p></footer>
or section.
elements that clearly describe their
<nav> Defines a navigation section. <nav><a href="/">Home</a></nav>
meaning both to the browser and
<article> Defines independent, self-contained <article><h2>Blog Post</h2></article>
the developer. These tags provide a content.

more meaningful structure to the


<section> Defines a thematic grouping of <section><h2>Introduction</h2></section>
content.
webpage, making the content
<aside> Defines content aside from the main <aside><p>Related Links</p></aside>
easier to understand, more content (e.g., sidebar).

accessible, and better optimized for <main> Defines the main content of the <main><h1>Main Content</h1></main>
document.
search engines.
Tag Explanation Example

List Tags <ul> Defines an unordered


(bulleted) list.
<ul><li>Item 1</li><li>Item
2</li></ul>

<ol> Defines an ordered <ol><li>First</li><li>Second</li


List tags in HTML are used to (numbered) list. ></ol>

group and organize items in a <li> Defines a list item (used <li>List Item</li>
inside <ul> or <ol>).
list format.
<dl> Defines a description <dl><dt>Term</dt><dd>Definiti
list. on</dd></dl>

<dt> Defines a term in a <dt>HTML</dt>


description list.

<dd> Defines the description <dd>HyperText Markup


of a term in a Language</dd>
description list.
Link and Media Tag

Link and Media tags in HTML are used to reference external resources such as stylesheets,
images, videos, audio, and other media content.
Tag Explanation Example

<link> Defines a relationship <link rel="stylesheet" href="styles.css">


between the document
and an external
resource.

rel (attribute) Specifies the <link rel="icon" href="favicon.png"


relationship between type="image/png">
the current document
and the linked resource.

href (attribute) Specifies the URL of the <link rel="stylesheet" href="styles.css">


linked external resource.

type (attribute) Defines the MIME type <link rel="stylesheet" href="styles.css"


of the linked resource. type="text/css">

media (attribute) Specifies the media type <link rel="stylesheet" href="mobile.css"


or query for which the media="screen and (max-width: 767px)">
linked resource is
intended.
Tag Explanation Example

<video> Embeds a video file in <video controls width="500"><source


the webpage. src="video.mp4" type="video/mp4"></video>

<source> Specifies multiple <source src="video.mp4" type="video/mp4">


media sources for
<video> or
<audio>.

<track> Provides subtitles, <track src="subtitles.vtt" kind="subtitles"


captions, or metadata srclang="en" label="English">
for a video.

<audio> Embeds an audio file in <audio controls><source src="audio.mp3"


the webpage. type="audio/mpeg"></audio>
Tag Explanation Example

<table> Defines a table. <table><tr><th>Header</th></tr></


Table Tags table>

<tr> Defines a table row. <tr><td>Data</td></tr>

Table tags in HTML are used <td> Defines a table cell. <td>Cell Data</td>

to create tables for organizing <th> Defines a table header <th>Header</th>


cell.
and displaying data in a
structured way. <thead> Groups header <thead><tr><th>Header</th></tr><
content in a table. /thead>

<tbody> Groups body content <tbody><tr><td>Data</td></tr></tb


in a table. ody>

<tfoot> Groups footer content <tfoot><tr><td>Footer</td></tr></t


in a table. foot>
Tag Explanation Example

Form Tags <form> Defines a form for user


input.
<form action="/submit"
method="post"></form>

<input> Creates an input field (e.g., <input type="text" name="username">


Form tags in HTML are text, password, checkbox).

used to create <label> Defines a label for an input <label for="username">Username:</label>


element.
interactive forms that
<button> Creates a clickable button. <button type="submit">Submit</button>
allow users to submit
<select> Creates a dropdown list. <select><option>Option 1</option></select>
data to a server for
processing. <option> Defines an option in a <option value="1">Option 1</option>
dropdown list.

<textarea> Creates a multi-line text <textarea rows="4" cols="50"></textarea>


input field.
HTML Element
An HTML element is a fundamental building block of a webpage. It consists of a start tag, content,
and an end tag. Some elements do not require an end tag.
Elements define the structure and content of a webpage, allowing browsers to render text,
images, links, tables, forms, and interactive components. HTML elements are categorized into
different types based on their purpose.
For eg: <img/> <br/> <input/>.

Example: <p>I am inside a paragraph tag</p>


Structure: <tagname>Content</tagname>
HTML Element vs HTML Tag

HTML Element HTML Tag

An HTML Element includes everything from HTML Tags are the actual keywords
the opening tag, the content inside, and the enclosed in angle brackets (< >) that define
closing tag if required. the beginning and the end of the element.

It represents the complete structure of an Tags are used to create elements but do not
HTML component. include the content inside them
HTML Element vs HTML Tag

Defines the boundaries of an element. Represents the actual content or structure


on a webpage.

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

Structure of HTML Element: Structure of HTML Tag:


<tagname>content</tagname> <tagname></tagname>
Types of HTML Elements
Block Level Elements

These elements take up the full width of their parent container.


Examples:
<div>,
<p>,
<h1> to <h6>,
<section>,
<article>,
<header>,
<footer>
Types of HTML Elements
Inline Elements

These elements take up only the space required for their content.

Examples: <span>, <a>, <strong>, <em>


HTML Attributes
HTML attributes provide additional information about
elements and help modify their behavior or
appearance.
Attributes are written inside the opening tag of an
HTML element.
Syntax: <element attribute="value">

Note: All attributes must start from lowercase letters


Types of HTML Attributes

Assignment
Global Attributes Event Attributes Special Attributes

Attributes that can be applied to Attributes are used to handle Attributes that are specific to
any HTML element. events such as clicks, mouse particular HTML elements.
movements, and other user
actions.

Attributes that are specific to onclick, onmouseover, onfocus href, src, alt
particular HTML elements.

<div id=“menu”, <button onclick=“do <a href=“facebook.com”></a>,


class=“drawer-menu”> something”>Click me</button> <img src=“imagesource”/>
Global Attribute
Global attributes are HTML attributes that can be id Used for uniquely identifying element

applied to any HTML element, regardless of its class For adding and same element, add classes
for styling purposes
type. These attributes allow customization and
title To Provide additional information about
provide additional functionality like styling, the content inside the element

interactivity, or accessibility enhancements. style Adding different styling to the element


<div id=“attribute”class=“highlight” title=“Information
contentedi To create an editable content inside the
About Global Attribute” style=“text-transform:capitalize”
table element
contenteditable tabindex=“0”
data-publisheddate=“2018”> Global Attribute tabindex Used for focusing on the element,
Example</div> especially used for keyboard navigation
Event Attributes onclick Executes a function or action when the
user clicks the element.

Event attributes are HTML attributes that define


onmouseover Triggers a function when the mouse
JavaScript actions to be executed when a specific hovers over the element

event occurs on an element. These events can be


onmouseout Executes a function when the mouse
user interactions, such as clicking, hovering, leaves the element

typing, or focusing on an element. onfocus Executes when the element gains focus
<div id="eventExample" class="event-highlight"
onclick="alert('You clicked me!')" onblur Executes when the element loses focus

onmouseover="this.style.backgroundColor='yellow'"
onsubmit Executes when a form is submitted.
onmouseout="this.style.backgroundColor='white'">
Event Attribute Example </div>
src Specifies the source of an embedded resource

Special Attributes
like an image, video,

alt Provides alternative text for an image,


describing its content for accessibility or when
<img src="image.png"
unavailable.
alt="A descriptive text about the image"
width="300"
height, width Sets height and width of an image or video
height="200"/>
element
<a href="https://example.com" >
Example Website
href Links to an external resources/hyperlink
</a>
<input type=“password” placeholder=“Enter your
type Sets input type of the element
password”/>

placeholder Sets placeholder/hint for user input


List Tag
Ordered List

Ordered List are a list of items that are


numbered and have sequence of numbers,
alphabets or roman numerals in each list item
Types of Ordered List

Numerical ordered list Alphabetical ordered list Roman numeric ordered list

1. List number one A. Alphabetical list one i. Roman list one


2. List number two B. Alphabetical list two
ii. Roman list two
3. List number three C. Alphabetical list three
iii. Roman list three
Unordered List
<ul>
An unordered list is a list of items where the
<li>Apple</li>
order does not matter. It is represented using
the <ul> (unordered list) tag in HTML. The <li>Banana</li>

items in an unordered list are typically <li>Cherry</li>


displayed with bullet points (●) by default. </ul>
<dl>

<dt>HTML</dt>
Description List <dd>HyperText Markup Language - used to structure
web pages.</dd>
A description list in HTML is used to define a
list of terms with their corresponding <dt>CSS</dt>

descriptions. It is created using the <dl> <dd>Cascading Style Sheets - used to style web
(description list) tag, along with <dt> pages.</dd>
(description term) for the term and <dd>
<dt>JavaScript</dt>
(description definition) for its description.
<dd>A programming language used to create dynamic
content on websites.</dd>

</dl>
Definition List

A Definition List (<dl>) in HTML is used to define terms and their corresponding descriptions. It
consists of three main tags:

<dl> – Defines the definition list.

<dt> – Defines the term (word or phrase).

<dd> – Defines the description (explanation of the term).


Table Tag

The <table> tag in HTML is used to create tables for organizing and displaying data in a structured
format.
Classwork / Homework
Create a simple table having 3 rows and 3 columns using html.

Use of <thead> tag.

Describe html documents


White space

White space refers to spaces, tabs, and line breaks (newlines) that are used in the HTML code.
HTML ignores extra white spaces when rendering a webpage, meaning multiple spaces will be
treated as a single space.

<p>This is an example.</p>

Even though there are multiple spaces between words, the browser will display it as: This is an
example.

This happens because HTML collapses multiple spaces into one.


How to preserve white space?
If you want to display text exactly as written (with multiple spaces and line breaks), use the <pre>
tag:

<pre>

This is preserved.

Each line stays the same.

</pre>

The <pre> tag maintains white spaces and line breaks as they are.
Indentation
Indentation refers to using spaces or tabs to organize HTML code properly. It makes the code
easier to read and understand but does not affect how the webpage is displayed.

<div><h1>Title</h1><p>Paragraph</p></div> (Bad Indentation)

<div> (Proper Indentation)


<h1>Title</h1>
<p>Paragraph</p>
</div>
White space and Indentation

HTML Meaning

<br> Line Break

<p> </p> Paragraph, blank line

&nbsp; Special character for a space


Pre-formatted Paragraph

With the <pre> tag, the text renders in the browser exactly as you type it. The <pre> tag is short
for preformat.

So if you press the ENTER or RETURN key several times to create line breaks within a <pre> tag,
you can expect to see all those line breaks in a browser.

The <pre> tag usually displays text in a monospaced font (i.e., Courier).

The use of <pre> tag is useful for displaying programming code.


Table

Organizes the data into rows and columns.

All tags and texts that apply to table go inside the <table> .. </table> tags.
Table attribute - BORDER
Table attribute - ALIGN

Horizontal alignment also applies to tables

The align attribute specifies where the table will be positioned and how text will flow around it.
Table Attribute - WIDTH

The width attribute sets the width of the table

You specify either a number of pixels or a percentage of the screen width.

Width = N Where n is the width given in pixels

Width = N% Where n is the width given as a percentage of the available browser window width
Table Attribute - CELLPADDING

Defines the space between the data in a cell and the border of the cell in pixels
Table Attribute - CELLSPACING

Control the distance between cells in the table


Table Attribute - BGColor, Caption

BGCOLOR: Defines the background colour for cells in the table

<caption> .. </caption>

The text inside the <caption> … </caption> Tags is inserted directly above the table in the browser
window
Table Row Element

<tr> .. </tr>

is used for formatting cells of individual rows

ALL OF THE CELLS IN A ROW BELONG WITHIN THE <tr> .. </tr> TAGS OF THAT ROW.

The smallest area of the table is the data cell.

There are two types of data cells, located in the header (<th> .. </th>) or in the table body (</td> .. </td>)

Attributes that can be applied to the table row element (tr) are align and bgcolor
Table Row Element

<th> .. <th> - The table header elements are displayed in <strong> and provide a way of labeling rows and
columns.

<td> .. </td> - Applies only to a single cell.

Attributes that can be applied to the table header and table body are align, valign, width, colspan and
rowspan
Rowspan
Tells the browser that this data cell will span the area of two vertically adjacent cells

These cells will be joined vertically (and will thus span over two rows)
Colspan

To use multiple columns to display the cell


Images
Image Formats

GIF - Types

JPEG

PNG

TIFF, PCX, BMP, XBM, PS, PDF


GIF - Graphics Interchange Format
Created by CompuServe – Developed and owned by CompuServe.

Uses a 256-color palette – Limited to 256 colors, making it less suitable for complex images.

Best for specific image types – Ideal for screenshots, line drawings, and images with sharp edges.

Larger file size than JPEG – If space is an issue and the image has many colors, JPEG is a better
choice.

Lossless compression – Reduces file size without losing image quality.


Types of GIF

Plain GIF

Transparent GIF

Animated GIF
Plain GIF

A Plain GIF is a non-animated GIF that contains only a single image. It does not have multiple
frames like an animated GIF. It is also called as Static GIF

Uses only 256 colors – Limited color palette.

Lossless compression – Image quality stays the same.

Best for simple images – Used for icons, logos, and diagrams.
Examples ..

Source: Internet
Example of Transparent
and Animated GIF

Example of Plain GIF


i.e. Static GIF

This is not moving and it is image so is considered as plain GIF


Transparent GIF

A Transparent GIF is a GIF image with a see-through background instead of a solid color. This
allows the image to blend smoothly with any webpage or background color.

Supports transparency – One color in the image can be made fully transparent (but not
semi-transparent).

Uses a 256-color palette – Limited colors like a normal GIF.

Best for logos, icons, and web graphics – Helps images look clean on different backgrounds.
Examples..

Source: Internet
Animated GIF
An Animated GIF is a GIF file that contains multiple images (frames) played in a sequence to
create a motion effect, like a short video.

Works like a flipbook – Displays frames in order to create animation.

Supports 256 colors – Limited color palette.

Loops automatically – Can play continuously or stop after a few cycles.

Best for memes, stickers, and web animations – Used for fun or informative motion graphics.
Examples of Animated GIF
JPEG - Joint Photographic Experts Group

JPEG is a type of image format that uses a method of compression called "lossy
compression." This means it reduces the image size by removing some details, which can
make the image quality a little worse. However, this loss of quality is usually not noticeable
because our eyes can't easily tell the difference between very similar colors.
Features..
Compression: Uses lossy compression to reduce file size, making it ideal for web usage and
storage efficiency.

Quality: Compression can be adjusted to balance quality and file size.

File Extension: .jpg or .jpeg

Color Support: Supports 24-bit color depth (16.7 million colors).

Transparency: Does not support transparency (unlike PNG).


.jpg & .jpeg

There is no difference between .jpg and .jpeg in terms of functionality, quality, or compression.
Both are the same file format (JPEG - Joint Photographic Experts Group). The difference exists
only due to naming conventions in different operating systems.

Key Differences:

.jpeg: The original file extension for JPEG images.

.jpg: Used because older Windows versions (like Windows 95 and earlier) only allowed
three-letter file extensions.
PNG - Portable Network Graphics
PNG, pronounced as "PING," is a great alternative to both GIF and JPEG formats.

It offers lossless compression, which means no loss in image quality, and the file size is often smaller
than GIF without compromising quality.

PNG supports RGBA (Red, Green, Blue, Alpha), which means it can handle transparency in images,
allowing them to blend seamlessly with different backgrounds.

It's supported by modern programs like Paint Shop Pro, Netscape Navigator, and Internet Explorer.

PNG works with indexed color, grayscale, and true-color images, and also includes an optional alpha
channel for transparency. Additionally, it provides a patent-free replacement for GIF.
Features..
Compression: Uses lossless compression, meaning no image quality is lost when saving.

Quality: Maintains high-quality images, making it ideal for graphics, logos, and screenshots.

File Extension: .png

Color Support: Supports RGBA (Red, Green, Blue, Alpha)

Transparency: Supports transparent backgrounds, unlike JPEG, making it useful for logos and
layered images.
Using Anchor Tag
The <a> (anchor) tag creates a hyperlink, making the enclosed text clickable and typically
highlighted. It requires an opening and closing tag, with the linked text placed in between. The
href attribute specifies the URL, which defines the file type and location. When clicked, the
browser navigates to the specified page or file. The target attribute controls how the link opens,
such as in a new tab or the same window.

<a href="http://www.projectcool.com/helloworld.html">Hello World!</a> How Are You?

It displays like this in a web browser: Hello World! How Are You?
Anchor Tag Example

<a href="http://www.projectcool.com/helloworld.html">Hello World!</a> How Are You? It


displays like this in a web browser: Hello World! How Are You?

The highlighted color indicates a link.

When your readers click on the link they go to the file described by that link. Most browsers are,
by default, configured to underline links as well.
Anchor Attribute

The anchor tag has three attributes that you'll use for making a link:

• href

• target

• name
href (hypertext reference)

The href attribute in the <a> tag specifies the destination URL for the hyperlink. The URL
should be enclosed in quotes. For example, <a href="http://www.projectcool.com">Go to
Project Cool's Home Page.</a> links to a webpage, while <a
href="mailto:[email protected]">Send Me Mail!</a> creates an email link.
Target

The target attribute in the <a> tag controls where the linked file will open. It is especially useful
when working with frames, but if not using frames, it can open the link in a new window.

For example, <a href="http://projectcool.com/helloworld.html" target="new">Hello World!</a>


will open the linked page in a new window or tab. The target attribute can be set to various values
like _blank to open in a new window or tab.
Target values

_self (default): Opens in the same tab/window.

_blank: Opens in a new tab or window.

_parent: Opens in the parent frame (useful for iframes).

_top: Opens in the full browser window, breaking out of any frames.

"new": Attempts to open in a new window but is not widely supported.


name
The name attribute in the <a> tag creates an anchor mark, which allows you to identify a specific
location within a file. You can then use this anchor to link directly to that location from within the
same or another document. To create an anchor mark, place the cursor where you want to mark,
type <a name="anchorname">, and then close the tag. The name should be a single word without
spaces. The linked content can then be accessed using a URL with the href attribute pointing to
the anchor's name.
Cascading style sheet - CSS

Cascading Style Sheets (CSS) is a stylesheet language used to control the presentation and layout
of web pages. It works by defining styles (such as colors, fonts, spacing, and positioning) that are
applied to HTML elements.
Types of CSS

Inline CSS

Internal CSS

External CSS
Inline CSS

Inline CSS involves applying styles directly to individual HTML elements using the style attribute.

<p style="color:#009900;
font-size:50px;
font-style:italic;
text-align:center;">
Inline CSS
</p>
Internal CSS

Internal / Embedded CSS is defined within the HTML document’s <style> element. It applies
styles to specific HTML elements. The CSS rule set should be within the HTML file in the head
section i.e. the CSS is embedded within the <style> tag inside the head section of the HTML file.
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Internal CSS Example</title>
<style>
body {
background-color: lightblue;
font-family: Arial, sans-serif;
}
h1 {
color: darkblue;
text-align: center;
}
p {
color: darkgreen;
font-size: 18px;
}
</style>
</head>
External CSS

External CSS contains separate CSS files that contain only style properties with the help of tag
attributes (For example class, id, heading, … etc). CSS property is written in a separate file with a
.css extension and should be linked to the HTML document using a link tag. It means that, for
each element, style can be set only once and will be applied across web pages.
External CSS (style.css) body {
background-color: lightyellow;
font-family: Verdana, sans-serif;
}

h1 {
color: darkred;
text-align: center;
}

p {
color: navy;
font-size: 18px;
}
CSS Colors

Color

background-color

border-color
CSS allows you to style elements using different colors.

Color names (e.g., red, blue, green)

Hex codes (e.g., #ff0000)

RGB values (e.g., rgb(255, 0, 0))


Text color in CSS

The color property sets the text color of an element.

Example:

p {

color: blue;

}
Background color in CSS

The background-color property sets the background color of an element.

Example:

div {

background-color: red;

}
Border colors in CSS

The border-color property sets the color of the border around an element.

Example:

div {

border: 2px solid red;

border-color: red;

}
Combining color, background-color, and border-color

div {

color: white;

background-color: darkblue;

border: 3px solid yellow;

}
Introduction to CSS
CSS Properties
font-family
font-size
font-weight
font-style

Typography
color
line-height
text-align
text-decoration
letter-spacing
word-spacing
font-family

It defines the type of font used for text. If the first font
is not available, the browser uses the next one in the list.

Example:

font-family: Arial, sans-serif;

This sets the text to use Arial. If Arial is unavailable, a


similar sans-serif font will be used.
font-size

It controls how big or small the text appears.

Example:

font-size: 20px;

This makes the text 20 pixels tall.


font-weight

It determines how bold or light the text appears.

Example

font-weight: bold;

This makes the text bold.


font-style

It defines whether the text is normal, italic, or oblique.

Example

font-style: italic;

This makes the text italic.


Color

It changes the color of the text.

Example

color: red;

This makes the text red.


line-height

It controls the space between lines of text.

Example

line-height: 1.5;

This increases the space between lines to make the text


easier to read.
text-align

It sets the alignment of the text (left, center, right, or


justified).

Example

text-align: center;

This centers the text.


text-decoration

It adds decoration like underline, overline, or line-through


to the text.

Example

text-decoration: underline;

This underlines the text.


letter-spacing

It controls the space between letters.

Example

letter-spacing: 2px;

This increases the space between each letter by 2 pixels.


word-spacing

It controls the space between words.

Example

word-spacing: 5px;

This increases the space between words by 5 pixels.


HTML Code…
CSS Implementation..
width

height

margin

Box Model
padding

border

box-sizing
width

It defines how wide the element is.

Example

width: 200px;

This makes the box 200 pixels wide.


height

It defines how tall the element is.

Example

height: 100px;

This makes the box 100 pixels tall.


margin

It adds space outside the element (between elements).

Example

margin: 20px;

This adds 20 pixels of space around the box.


padding

It adds space inside the element (between content and


border).

Example
padding: 10px;

This adds 10 pixels of space inside the box.


border

It defines the outer edge of the box.

Example

border: 2px solid black;

This adds a 2px black solid border around the box.


box-sizing

It controls how width and height are calculated.

Example

box-sizing: border-box;

This ensures padding and border don’t increase the total


width & height.
background-color

background-image

background-position

background-repeat

Backgrounds & border-color

Borders border-style

border-width

border-radius

box-shadow
background-color

It sets the background color of an element.

Example

background-color: lightblue;

This makes the background light blue.


background-image

It sets an image as the background.

Example

background-image: url('background.jpg');

This adds background.jpg as the background.


background-position

It controls the position of the background image.

Example

background-position: center;

This places the image in the center.


background-repeat

It defines whether the background image repeats.

Example

background-repeat: no-repeat;

This prevents the image from repeating.


border-color

It sets the color of the border.

Example

border-color: red;

This makes the border red.


border-style

It defines the type of border (solid, dashed, dotted, etc.).

Example

border-style: dashed;

This creates a dashed border.


border-width

It controls the thickness of the border.

Example

border-width: 3px;

This makes the border 3px thick.


border-radius

It rounds the corners of the element.

Example

border-radius: 10px;

This makes the corners slightly rounded.


box-shadow

It adds a shadow effect around the element.

Example

box-shadow: 5px 5px 10px gray;

This adds a shadow 5px right, 5px down, and blurred by 10px.
color

Colors
background-color

border-color
color

It defines the text color of an element.

Example

color: red;

It makes text red.


background-color

It sets the background color of an element.

Example

background-color: blue;

It makes the background blue.


border-class

It specifies the color of an element's border.

Example

border: 2px solid green;

It sets a green border.


position

top

Positioning right

bottom

left

z-index
position

It defines how an element is placed on a webpage.

Example

position: absolute;

It places the element at a fixed position on the page.

Values: static (default), relative, absolute, fixed, sticky.


Top, right, bottom, left

It is used to move an element from its original position.

position: relative;

top: 20px;

left: 30px;

Moves the element 20 pixels down and 30 pixels to the right.


z-index

It decides which element appears on top when elements


overlap.

Example

z-index: 5;

An element with a higher z-index appears above elements with


a lower z-index.
display

position

float

clear

overflow

Layout
flexbox properties
(flex-direction, justify-content,
align-items, etc.)

grid properties
(grid-template-columns,
grid-template-rows, grid-gap,
etc.)
Animation & transition

Transitions
animation
transition

Used to create smooth changes when a property (like color or size) changes.

button {

background-color: blue;

transition: background-color 0.5s;

button:hover {

background-color: red;

When you hover over the button, it smoothly changes from blue to red in 0.5
seconds.
Animation
Allows more complex effects by changing styles over time.

@keyframes move {

from { left: 0px; }

to { left: 100px; }

div {

position: absolute;

animation: move 2s infinite alternate;

This moves a div back and forth from left 0px to left 100px in 2 seconds, repeating
forever
transform

Transforms
rotate

scale

translate

skew
Transforms allow element to be rotated, resized,
moved or skewed without affecting other element
transform

The transform property applies different transformations


like rotate, scale, translate, and skew.

Example

transform: rotate(45deg);

Rotates the element by 45 degrees.


rotate

Rotates an element clockwise or counterclockwise.

Example

transform: rotate(90deg);

Rotates the element 90 degrees.


scale

Increases or decreases the size of an element.

Example

transform: scale(1.5);

Makes the element 1.5 times bigger.


translate

Moves an element left, right, up, or down.

Example

transform: translate(50px, 20px);

Moves the element 50px right and 20px down.


skew

Tilts an element along the X or Y axis.

Example

transform: skew(20deg);

Tilts the element by 20 degrees.


Media Queries @media
Media queries help make
websites responsive
(adjusting for different

What is Media screen sizes). They allow

Queries?
CSS rules to apply only
when certain conditions
are met (like screen
width).
Changing background for small screen

body {
background-color: white;
}
/* When the screen width is 600px or less */
@media (max-width: 600px) {
body {
background-color: lightblue;
}
}
Lists
list-style-type

list-style-image

list-style-position
list-style-type

Changes the bullet style of a list.

Example

ul {

list-style-type: square;

Changes the default round bullet to a square.


list-style-image

Replaces bullets with an image.


Example
ul {
list-style-image: url('bullet.png');
}
Uses "bullet.png" as the bullet icon.
list-style-position

Defines whether bullets appear inside or outside the list


item.
Example
ul {
list-style-position: inside;
}
Moves the bullet inside the list item instead of the default outside position.
table-layout

Table border-collapse

border-spacing

caption-side
input styling (e.g.,
border, padding, width)
textarea styling (similar
to input)
button styling (similar to

Forms other elements, plus


cursor, transition, etc.)
form styling (e.g.,
margin, padding, display)
:hover, :focus, :active
states styling
cursor

opacity

Miscellaneous
visibility

outline

overflow

pointer-events

text-overflow
Unit - 4

Introduction to Javascript
Javascript is a programming language used to make
web pages interactive. It runs in the browser and
allows you to create dynamic content.
Introduction to Javascript

JavaScript is a versatile, lightweight scripting language


widely used in web development. It can be utilized for both
client-side and server-side development, making it essential
for modern web applications. Known as the scripting language
for web pages, JavaScript supports variables, data types,
operators, conditional statements, loops, functions, arrays,
and objects. With JavaScript, you can create dynamic,
interactive, and engaging websites.
Basic Syntax
Javascript Variables
Variables

Variables are Containers for Storing Data

JavaScript Variables can be declared in 4 ways:

● Automatically
● Using var
● Using let
● Using const
Var

● Function-scoped (accessible throughout the function).

● Not block-scoped (ignores {} blocks like loops and

conditionals).

● Can be redeclared and updated.

● Hoisted, but initialized as undefined.


Var Example

var name = "John";

var name = "Doe"; // ✅ Allowed (Redeclaration)

console.log(name); // Output: "Doe"

if (true) {

var age = 25;

console.log(age); // Output: 25 (Even though declared inside the block)


let

● Block-scoped (only accessible within {} where it is

declared).

● Cannot be redeclared in the same scope.

● Can be updated (reassigned).

● Hoisted, but not initialized (causes an error if accessed

before declaration).
let Example
let city = "New York";

city = "Los Angeles"; // ✅ Allowed (Reassignment)

console.log(city); // Output: "Los Angeles"

if (true) {

let country = "USA";

console.log(country); // Output: "USA"

console.log(country); // ❌ Error (Not accessible outside the block)

let x = 10;

let x = 20; // ❌ Error: Cannot redeclare the variable


const

● Block-scoped (same as let).

● Cannot be redeclared or reassigned after initialization.

● Must be initialized at the time of declaration.

● Objects and arrays declared with const can have their

properties modified, but not reassigned.


const Example

const PI = 3.1416;
PI = 3.14; // ❌ Error: Cannot reassign a constant

const person = { name: "Alice", age: 25 };


person.age = 26; // ✅ Allowed (Modifying properties)
console.log(person.age); // Output: 26

person = { name: "Bob" }; // ❌ Error: Cannot reassign the whole


object
Note

The var keyword was used in all JavaScript code from 1995 to
2015.

The let and const keywords were added to JavaScript in 2015.

The var keyword should only be used in code written for


older browsers.
When to use var, let or const?

1. Always declare variables

2. Always use const if the value should not be changed

3. Always use const if the type should not be changed


(Arrays and Objects)

4. Only use let if you can't use const

5. Only use var if you MUST support old browsers.


Javascript Comments
Javascript comments

JavaScript comments are used to add explanatory notes to the


code, making it easier to understand and maintain. Comments
are ignored by the JavaScript engine and do not affect the
execution of the code. JavaScript comments can be used to
explain JavaScript code, and to make it more readable.
Single line comment

Single line comments start with //.

Any text between // and the end of the line will be ignored
by JavaScript (will not be executed).
Multi-line comments

Multi-line comments start with /* and end with */.

Any text between /* and */ will be ignored by JavaScript.


Data Types in Javascript
Data Types in Javascript

In JavaScript, data types define the type of values that


variables can hold. JavaScript has two main categories of
data types: Primitive and Non-Primitive data types.
Types of Data Types in Javascript

Primitive Data Types Non-Primitive Data Types

- Number - Object
- String - Array
- Boolean - Function
- Undefined
- Null
- Bigint
Number

It represents both integers and floating-point numbers.

let age = 25;

let price = 99.99;


String

It represents a sequence of characters, enclosed in single


('), double ("), or backticks (`).

let name = "John Doe";

let greeting = `Hello, ${name}!`;


Boolean

It represents a logical value: true or false.

let isStudent = true;

let hasPassed = false;


Undefined

It represents a variable that has been declared but not


assigned a value.

let something;

console.log(something); // undefined
Null

It represents the intentional absence of any value.

let emptyValue = null;


Bigint

It represents large integers beyond Number.

let bigNumber = 123456789012345678901234567890n;


Operators in Javascript
Javascript operators are

used to perform different

Operators
types of mathematical and

logical computations.
Arithmetic Operators

Assignment Operators

Comparison Operators

String Operators
Types of Javascript Logical Operators

Operators Bitwise Operators

Ternary Operators

Type Operators
Javascript Arithmetic Operator

Arithmetic Operators are used to perform mathematical


calculations like addition, subtraction, multiplication, and
division.

let a = 3;

let x = (100 + 50) * a;


Example - Arithmetic Operator

let a = 10;
let b = 5;
console.log(a + b); // 15 (Addition)
console.log(a - b); // 5 (Subtraction)
console.log(a * b); // 50 (Multiplication)
console.log(a / b); // 2 (Division)
console.log(a % b); // 0 (Modulus - Remainder)
console.log(a ** 2); // 100 (Exponentiation - 10^2)
Operator Description

+ Addition

- Subtraction

* Multiplication

** Exponentiation (ES2016)

/ Division

% Modulus (Division Remainder)

++ Increment

-- Decrement
Assignment Operators

Assignment operators are used to Assign values to


variables, with options to add, subtract, multiply, or
divide within the assignment.

The Addition Assignment Operator (+=) adds a value to a


variable.

let x = 10;

x += 5;
Example - Assignment Operator

let x = 10;
x += 5; // Same as x = x + 5
console.log(x); // 15
x -= 3; // x = x - 3
console.log(x); // 12
x *= 2; // x = x * 2
console.log(x); // 24
x /= 4; // x = x / 4
console.log(x); // 6
Operator Example Same As

= x=y x=y

+= x += y x=x+y

-= x -= y x=x-y

*= x *= y x=x*y

/= x /= y x=x/y

%= x %= y x=x%y

**= x **= y x = x ** y
Comparison Operators

Comparison operators in javascript are used to Compare two


values and return true or false based on the comparison.
Example - Comparison Operators

console.log(5 == "5"); // true (checks value, not type)


console.log(5 === "5"); // false (checks value and type)
console.log(10 != 5); // true
console.log(10 !== "10"); // true
console.log(8 > 3); // true
console.log(4 < 7); // true
console.log(6 >= 6); // true
console.log(2 <= 3); // true
Operator Description

== equal to

=== equal value and equal type

!= not equal

!== not equal value or not equal type

> greater than

< less than

>= greater than or equal to

<= less than or equal to

? ternary operator
String Operators

String operators in Javascript are used to manipulate text,


such as joining (concatenating) strings together.
Example - String Operators

let firstName = "John";


let lastName = "Doe";
let fullName = firstName + " " + lastName; // Concatenation
console.log(fullName); // "John Doe"

let text = "Hello";


text += " World!"; // Same as text = text + " World!"
console.log(text); // "Hello World!"
Logical Operators

Logical operators in Javascript are used to combine multiple


conditions and return true or false based on logical
operations (AND, OR, NOT).
Example - Logical Operators

let age = 25;


let isStudent = true;

console.log(age > 18 && isStudent); // true (AND - both


must be true)
console.log(age > 30 || isStudent); // true (OR - at least
one is true)
console.log(!isStudent); // false (NOT - reverses value)
Operator Description

&& logical and

|| logical or

! logical not
Javascript Type Operators

Type operators in Javascript are used to check the type of a


variable (typeof) or test if an object is an instance of a
class (instanceof).
Example - Type Operator

console.log(typeof 42); // "number"

console.log(typeof "hello"); // "string"

console.log(typeof true); // "boolean"


Operator Description

typeof Returns the type of a variable


Bitwise Operators

Bitwise operators in Javascript are used to Perform


operations at the binary level (bit manipulation).
Rules for Bitwise Operators
1. Bitwise AND (&) → 1 & 1 → 1, otherwise 0.
2. Bitwise OR (|) → 0 | 0 → 0, otherwise 1.
3. Bitwise XOR (^) → 1 ^ 1 → 0, 0 ^ 0 → 0, otherwise 1.
4. Bitwise NOT (~) → Flips all bits (0 → 1, 1 → 0). Equivalent to -(x +
1).
5. Left Shift (<<) → Shifts bits left, filling right with 0 (x << n = x
* 2ⁿ).
6. Right Shift (>>) → Shifts bits right, discarding rightmost bits (x >>
n = ⌊x / 2ⁿ⌋).
7. Unsigned Right Shift (>>>) → Shifts bits right, filling left with 0
(for non-negative numbers).
Example - Bitwise Operator

console.log(5 & 1); // 1 (Bitwise AND)

console.log(5 | 1); // 5 (Bitwise OR)

console.log(5 ^ 1); // 4 (Bitwise XOR)

console.log(~5); // -6 (Bitwise NOT)

console.log(5 << 1); // 10 (Left shift)

console.log(5 >> 1); // 2 (Right shift)


Binary representation:

● 5 → 0101
● 1 → 0001

The & (AND) operator compares each bit and returns 1 only if
both bits are 1.
Final Binary Result → 0001
Decimal Equivalent → 1
Assignment - Bitwise Operators write and explain
Operator Description Example Same as Result Decimal

& AND 5&1 0101 & 0001 0001 1

| OR 5|1 0101 | 0001 0101 5

~ NOT ~5 ~0101 1010 10

^ XOR 5^1 0101 ^ 0001 0100 4

<< left shift 5 << 1 0101 << 1 1010 10

>> right shift 5 >> 1 0101 >> 1 0010 2

>>> unsigned right shift 5 >>> 1 0101 >>> 1 0010 2


Javascript Functions
function

A JavaScript function is a block of code designed to perform


a particular task.

A JavaScript function is executed when "something" invokes


it (calls it).
Why functions?

With functions you can reuse code

You can write code that can be used many times.

You can use the same code with different arguments, to


produce different results.
Example
<script>

<!DOCTYPE html> function myFunction(p1, p2) {

return p1 * p2;
<html>
}
<body>
let result = myFunction(4, 3);

<h1>JavaScript Functions</h1> document.getElementById("demo").innerHTM


L = result;
<p>Call a function which performs
</script>
a calculation and returns the
</body>
result:</p>
</html>
<p id="demo"></p>
Javascript Dialog Box
Alert Dialog (alert()) –
Displays a message with an
"OK" button.

Prompt Dialog (prompt()) –


Asks the user for input

Dialog Box and returns the value.

Confirm Dialog (confirm())


– Asks the user to confirm
an action (OK/Cancel).
Alert Dialog

It is used to display a message to the user.

The user must click "OK" to continue.

alert("Welcome to our website!");


Prompt Dialog

It is used to take input from the user and returns the user
input as a string.

let name = prompt("Enter your name:");

alert("Hello, " + name + "!");


Confirm Dialog
It asks for confirmation (OK/Cancel) and returns true if the user clicks
"OK" and false if "Cancel" is clicked.

let response = confirm("Do you want to proceed?");

if (response) {

alert("You clicked OK!");

} else {

alert("You clicked Cancel!");

}
Conditional statements in

Conditional JavaScript are used to

statements
make decisions in code
based on conditions.
if Statement

It executes a block of code only if a specified condition is


true.

let age = 18;

if (age >= 18) {

console.log("You are eligible to vote.");

}
if...else Statement

It executes one block if the condition is true, otherwise


executes another block.

let number = 10;

if (number % 2 === 0) {

console.log("Even number");

} else {

console.log("Odd number");

}
if...else if...else Statement
It checks multiple conditions, executing the first true block.

let score = 85;

if (score >= 90) {

console.log("Grade: A");

} else if (score >= 75) {

console.log("Grade: B");

} else {

console.log("Grade: C");

}
Switch Statement

It is used when there are multiple possible conditions for a


single variable.
let day = "Monday";
switch (day) {
case "Monday":
console.log("Start of the week!");
break;
case "Friday":
console.log("Weekend is near!");
break;
case "Sunday":
console.log("Relax, it's the weekend!");
break;
default:
console.log("It's a regular day.");
}
Ternary Operator

A shorthand for if...else.

let age1 = 20;

let message = age1 >= 18 ? "Adult" : "Minor";

console.log(message);
Nested if Statements
An if statement inside another if statement.

let num = 10;


if (num > 0) {
if (num % 2 === 0) {
console.log("Positive Even Number");
} else {
console.log("Positive Odd Number");
}
}
Arrays
Array

An array is a special type of object that allows storing


multiple values in a single variable. Arrays are used to
store ordered collections of data, such as a list of
numbers, strings, or objects.

An array is a special variable, which can hold more than one


value.

const cars = ["Saab", "Volvo", "BMW"];


Creating Array and accessing Elements

let fruits = ["Apple", "Banana", "Mango"];

console.log(fruits[0]); // Output: Apple

console.log(fruits[1]); // Output: Banana


Modifying Element

fruits[1] = "Orange";

console.log(fruits); // Output: ["Apple", "Orange", "Mango"]


Adding & Removing Element

fruits.push("Grapes"); // Adds "Grapes" at the end

console.log(fruits); // ["Apple", "Orange", "Mango",


"Grapes"]

fruits.pop(); // Removes last element

console.log(fruits); // ["Apple", "Orange", "Mango"]


Contd..

fruits.unshift("Strawberry"); // Adds at the beginning

console.log(fruits); // ["Strawberry", "Apple", "Orange",


"Mango"]

fruits.shift(); // Removes first element

console.log(fruits); // ["Apple", "Orange", "Mango"]


Type Description

Single-Dimensional A normal array with one


level of elements.

Multi-Dimensional An array containing other


arrays.

Sparse Array An array with missing


indexes.

Associative Array Not an array; it's actually


an object.

Typed Array Special arrays for handling


binary data.
1D Array

A single-dimensional array is a simple list of elements.

let fruits = ["Apple", "Banana", "Mango"];

console.log(fruits[0]); // Output: Apple


Multi-Dimensional Array

A multi-dimensional array is an array that contains other arrays inside


it.

let matrix = [

[1, 2, 3],

[4, 5, 6],

[7, 8, 9]

];

console.log(matrix[1][2]); // Output: 6
Sparse Array

A sparse array has empty (undefined) or missing indexes.

let sparse = [];


sparse[3] = "Hello";
console.log(sparse); // Output: [ <3 empty items>, 'Hello' ]
console.log(sparse.length); // Output: 4
Javascript Objects
Objects

In JavaScript, objects are collections of key-value pairs


where keys are strings (or Symbols) and values can be any
data type, including other objects, functions, and arrays.
They are fundamental in JavaScript and are used to store
structured data.
Creating JS Objects
// Create an Object:

<!DOCTYPE html> const person = {


firstName: "John",
<html>
lastName: "Doe",
<body>
age: 50,
<h1>Creating JavaScript eyeColor: "blue"
Objects</h1>
};
<h2>Using an Object Literal</h2> // Display Data from the Object:

<p id="demo"></p> document.getElementById("demo").innerHTML =


person.firstName + " is " + person.age + " years
<script> old.";
</script>
</body>
</html>
Document object model
The Document Object Model
(DOM) is a programming
interface for web
documents. It represents
an HTML or XML document as

DOM
a tree structure, where
each element is a node
that can be accessed,
modified, or deleted using
JavaScript.
When a web page is loaded, the browser creates a
Document Object Model of the page.
The HTML DOM Tree of Objects
Why is the DOM Important?

Modifies Content Dynamically – Change text, images, links,


etc.

Changes Styles in Real-Time – Modify CSS properties using


JavaScript.

Handles User Interactions – Respond to clicks, keyboard


input, mouse events, etc.

Manipulates Elements – Add, remove, or change HTML elements.


DOM Manipulation
Event Handling
Event handling

Event handling in JavaScript refers to the process of

responding to user interactions, such as clicks, key

presses, mouse movements, and form submissions. JavaScript

provides event listeners to detect and respond to these

events.
3 Ways to handle events

● Inline Event Handlers (Not Recommended)

● Using JavaScript (Recommended)

● Using addEventListener() (Best Practice)


Inline Event Handlers (Not Recommended)

Adding event handlers directly in HTML attributes.

<button onclick="alert('Button Clicked!')">Click Me</button>

Downside: It mixes JavaScript with HTML and is not


maintainable.
Using JavaScript

Adding an event using JavaScript.

<button id="myButton">Click Me</button>

<script>

document.getElementById("myButton").onclick = function() {

alert("Button Clicked!");

};

</script>
Using addEventListener()

Using addEventListener() allows multiple event listeners on the same element.

<button id="btn">Click Me</button>

<script>

document.getElementById("btn").addEventListener("click", function() {

alert("Button Clicked using addEventListener!");

});

</script>
onClick

The onClick event in JavaScript is used to execute a


function when an element is clicked. It is commonly used in
buttons, links, and other interactive elements.

<button onclick="alert('Button Clicked!')">Click Me</button>


onmouseover and onmouseout
These events are used to detect when a user hovers over or moves out of an
element.

The onmouseover event is triggered when the mouse pointer enters an element.

<p id="text" onmouseover="this.style.color='red'">Hover over me!</p>

The onmouseout event is triggered when the mouse pointer leaves an element.

<p id="text" onmouseover="this.style.color='red'"


onmouseout="this.style.color='black'">

Hover over me!

</p>
onSubmit

The onSubmit event is triggered when a form is submitted. It

is commonly used to validate form inputs or prevent form

submission before validation.


<form onsubmit="return validateForm()">
<input type="text" id="name" placeholder="Enter your name"
required>
<button type="submit">Submit</button>
</form>

<script>
function validateForm() {
let name = document.getElementById("name").value;
if (name === "") {
alert("Name cannot be empty!");
return false; // Prevents form submission
}
return true; // Allows form submission
}
</script>
onFocus and onBlur

These events are commonly used in form fields to improve

user experience, such as highlighting an input field when

selected (onFocus) and validating input when the user moves

away (onBlur).
onFocus and onBlur (Contd..)

The onFocus event triggers when an element (like an input


field) gains focus.

<input type="text" id="name" placeholder="Enter your name"


onfocus="this.style.backgroundColor='lightyellow'">

The onBlur event triggers when an element loses focus (i.e.,


the user clicks outside the input field).
<input type="text" id="name" placeholder="Enter your name"
onblur="validateInput()">
<p id="error" style="color: red;"></p>

<script>
function validateInput() {
let name = document.getElementById("name").value;
let error = document.getElementById("error");

if (name === "") {


error.textContent = "Name cannot be empty!";
} else {
error.textContent = "";
}
}
</script>
Event Description

click Fires when an element is clicked

dblclick Fires when an element is


double-clicked

mouseover Fires when the mouse hovers over


an element

mouseout Fires when the mouse leaves an


element

keydown Fires when a key is pressed

keyup Fires when a key is released

submit Fires when a form is submitted

change Fires when the value of an input


changes
Form Validation in JS
Form Validation

Form validation in JavaScript is the process of checking

user input in a web form before submitting it to the server.

It ensures that the data entered by the user meets the

required criteria, such as being in the correct format, not

being empty, and following specific rules (e.g., valid email

format, minimum password length).


JS Form Validation can be done using:

Client-side validation – Uses JavaScript to validate input

before submission, improving user experience.

Built-in HTML validation – Uses attributes like required,

pattern, and minlength.

Custom validation – Uses JavaScript to create specific rules

and provide custom error messages.


Hiding Javascript code from browsers that don’t support JS

If a browser does not support JavaScript, the JavaScript


code will be displayed as plain text unless it is properly
hidden. Here are a few ways to hide JavaScript code from
browsers that do not support JavaScript.

Browsers that do not support JavaScript will execute the


content inside <noscript>. You can use it to display a
message or alternative content.
Implementation..

<noscript>

<p>Your browser does not support JavaScript. Please

enable JavaScript or use a different browser.</p>

</noscript>

You might also like