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

HTML

Uploaded by

sujana
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)
10 views

HTML

Uploaded by

sujana
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/ 44

UNIT 1 : HTML: Introduction to web designing, difference between 4.

4. Coding Skills: While designers often use visual design tools,


web applications and desktop applications, introduction to HTML, understanding HTML, CSS, and sometimes JavaScript is crucial. This
HTML structure, elements, attributes, headings, paragraphs, styles, allows them to translate their designs into functional code that developers
colours, HTML formatting, Quotations, Comments, images, tables, can implement on the web.
lists, blocks and classes, HTML CSS, HTML frames, file paths, layout,
symbols, HTML responsive. 5. User Experience (UX) Design: UX design focuses on enhancing user
************************************************************* satisfaction by improving the usability, accessibility, and efficiency of the
Web designing: Web designing is a multifaceted discipline that involves website. It involves research, user testing, and iterative design to create a
creating the visual layout, user interface, and overall look and feel of site that meets users' needs and expectations.
websites. It combines elements of graphic design, user experience (UX)
design, and technical coding to produce aesthetically pleasing and 6. SEO Principles: Web designers should have a basic understanding of
functional websites. Search Engine Optimization (SEO) principles. This includes designing sites
with clean code, fast loading times, and structured content that search
Here are some key aspects of web designing: engines can easily crawl and index.

1. Graphic Design: Web designers use graphic design tools like Adobe 7. Collaboration: Web designers often work closely with developers,
Photoshop, Sketch, or Figma to create layouts and visual elements of the content creators, and stakeholders to ensure that the website meets both
website. This includes choosing colors, typography, and images that align design and functional requirements. Collaboration and communication
with the brand and purpose of the site. skills are essential for successful web design projects.

2. User Interface (UI) Design: UI design focuses on the interactive Comparison between web applications and desktop applications:
elements of the website. Designers create buttons, navigation menus, forms,
and other elements that users interact with. UI design ensures that the Feature Web Applications Desktop Applications
interface is intuitive, easy to use, and guides users to achieve their goals on Deployment Accessed via web browsers Installed directly on
the site. user's device
Access Requires internet Can work offline
3. Responsive Design: With the proliferation of various devices (desktops, connection
tablets, smartphones), web designers need to ensure that websites are Platform Platform-independent (runs Platform-specific
responsive. This means that the layout and content adapt smoothly to Dependency in browsers) (Windows, macOS,
different screen sizes and resolutions, providing a consistent user Linux versions)
experience across devices. User Interface Designed using web Uses platform-specific
technologies (HTML, CSS, UI frameworks (e.g.,
JS) WPF, Cocoa) Docs) network capabilities
Updates Centralized updates Users manage updates Cost Often subscription-based; One-time purchase or
managed by provider manually or via auto- can be cost-effective for subscription; cost varies
update users with features
Performance Depends on internet speed Typically faster, utilizes Accessibility Accessible from any device Requires installation on
and server responsiveness local resources with a web browser specific devices
Offline Can work offline with Designed to work fully Backup and Data backed up on remote Users responsible for
Capability limitations (via caching, offline Recovery servers local backup and
service workers) recovery
Security Vulnerable to web-based Lower risk of web- Examples Google Docs, Trello, Gmail Microsoft Office, Adobe
attacks (e.g., XSS, SQL based attacks, local Photoshop
injection) security concerns
Development Requires web development Requires platform- Introduction to HTML and HTML Structure
Skills skills specific development
skills HTML (HyperText Markup Language) is the standard markup language for
creating web pages. It provides the structure and format for content on the
Storage Data typically stored on Data stored locally on World Wide Web. Let’s dive into the basics:
remote servers (cloud) user's device
HTML History:
Integration Can easily integrate with May integrate with local
 HTML has evolved over time:
other web services and system services and
 1989: Tim Berners-Lee invented the World Wide Web.
APIs APIs
 1991: Tim Berners-Lee invented HTML.
Resource Usage Relies on server resources; Utilizes local resources
 Various versions followed, including HTML 4.01 and XHTML.
less local resource usage extensively (CPU,
 2008: WHATWG HTML5 draft.
RAM)
 2014: W3C Recommendation
Customization Limited customization Highly customizable UI
options for UI and and features tailored to
What is HTML?
functionality platform
Development Development environment Requires specific  HTML stands for Hyper Text Markup Language.
Environment is generally simpler (text development IDEs and  It describes the structure of a web page.
editors, browsers) tools  HTML consists of a series of elements that tell the browser
Collaboration Facilitates real-time Collaboration features how to display content.
collaboration (e.g., Google often depend on
 Elements label pieces of content, such as headings, o Browsers use HTML tags to determine how to display the
paragraphs, links, and more. content.

A Simple HTML Document Example: Elements:


<!DOCTYPE html>
<html> HTML elements are the building blocks of web pages. They define the
<head> structure and semantics of content that appears on a webpage. Each element
<title>Page Title</title> is enclosed by opening and closing tags, and can contain content or other
</head> nested elements. Some common HTML elements include:
<body>
<h1>My First Heading</h1> 1. `<html>`: The root element of an HTML page, encapsulating the entire
<p>My first paragraph.</p> document.
</body>
</html> 2. `<head>`: Contains meta-information about the HTML document, such
as `<title>`, `<meta>`, `<link>`, and `<script>` tags.
Explanation:
3. `<body>`: Encloses the content of the webpage that is displayed to the
 <!DOCTYPE html>: Declares this document as an user, such as text, images, links, forms, etc.
HTML5 document.
 <html>: The root element of an HTML page. 4. Headings: `<h1>` to `<h6>` tags define headings of different levels (from
 <head>: Contains meta information about the HTML most important `<h1>` to least important `<h6>`).
page.
5. Paragraphs: `<p>` tag defines a paragraph of text.
 <title>: Specifies a title for the page (shown in the
browser’s title bar or tab).
6. Links: `<a>` tag creates hyperlinks to other web pages or resources.
 <body>: Defines the document’s body, containing
visible content like headings and paragraphs. 7. Images: `<img>` tag embeds images into the webpage.
 <h1>: Represents a large heading.
 <p>: Represents a paragraph. 8. Lists: `<ul>` (unordered list), `<ol>` (ordered list), and `<li>` (list item)
tags create bulleted or numbered lists.
Web Browsers:
9. Forms: `<form>` tag is used to create interactive forms for user input,
o Browsers (like Chrome, Edge, Firefox, Safari) read HTML containing input fields like `<input>`, `<textarea>`, `<select>`, `<button>`,
documents and display them correctly. etc.
10. Tables: `<table>`, `<tr>` (table row), `<th>` (table header), `<td>` (table 7. `style`: Applies inline CSS styles to an element.
data) tags create structured data tables.
<p style="color: red; font-size: 16px;">Styled Paragraph</p>
11. Semantic Elements: HTML5 introduced semantic elements like
`<header>`, `<nav>`, `<section>`, `<article>`, `<aside>`, `<footer>`, etc., to 8. `type`: Specifies the type of an `<input>` element (e.g., text, password,
better define the structure and meaning of content. submit).

Attributes: <input type="text" name="username">

HTML attributes provide additional information about HTML elements. 9. `value`: Sets the initial value of an `<input>` element.
They are always specified in the opening tag and come in name/value pairs,
separated by an equals sign (`=`). Some common attributes include: <input type="text" name="username" value="John Doe">
1. `id`: Uniquely identifies an element within a document.
<div id="main-content">...</div> 10. `placeholder`: Provides a hint or example text for an input field.
2. `class`: Specifies one or more classes for an element (used for styling
<input type="email" name="email" placeholder="Enter
with CSS or JavaScript).
your email">
<p class="intro">...</p>
3. `src`: Specifies the URL of an external resource, such as an image or
HTML, headings: HTML, headings are created using the <h1> to <h6>
script.
tags. These tags define different levels of headings, with <h1> being the
<img src="image.jpg" alt="Description">
most important and <h6> the least important. Let’s look at a simple
example program:
4. `href`: Specifies the URL of the linked resource in `<a>` (anchor) tags.
<!DOCTYPE html>
<a href="https://example.com">Link Text</a>
<html>
<head>
5. `alt`: Provides alternative text for images when they cannot be displayed.
<title>HTML Headings</title>
<img src="image.jpg" alt="Description">
</head>
6. `title`: Provides additional information about an element, typically shown <body>
as a tooltip. <h1>Main Heading</h1>
<p>This is some content under the main heading.</p>
<a href="https://example.com" title="Visit Example">Link <h2>Subheading</h2>
Text</a> <p>More content under the subheading.</p>
</body>
</html>
In this example:  <h1 style="font-family: verdana;">This is a
heading</h1>
 <h1> represents the main heading.  <p style="font-family: courier;">This is a
 <h2> represents a subheading. paragraph.</p>
 The content under each heading is displayed accordingly.  Text Size:
 Adjust the text size with the font-size
Certainly! In HTML, you can style your content using various techniques. property:
Let’s explore how to create paragraphs, apply styles, and use colors:  <h1 style="font-size: 300%;">This is a
heading</h1>
1. Paragraphs:  <p style="font-size: 160%;">This is a
o To create paragraphs, use the <p> tag. For example:
paragraph.</p>
o <p>This is a paragraph.</p>
 Text Alignment:
2. Styles:  Control horizontal text alignment using the
o You can apply styles directly to HTML elements using the
text-align property:
style attribute. It allows you to set properties like color, font,  <h1 style="text-align: center;">Centered
and alignment. Heading</h1>
o Here are some examples:
 <p style="text-align: center;">Centered
 Background Color:
paragraph.</p>
 Use the background-color property to define
3. Colors:
the background color for an element: o You can specify colors using names or hexadecimal values.
 <body style="background-color:
For example:
powderblue;"> o <p style="color: tomato;">This text is tomato-colored.</p>
 <h1>This is a heading</h1>
 <p>This is a paragraph.</p> In HTML, you can create paragraphs using the <p> element. Each
 </body> paragraph starts on a new line and is usually a block of text. Here’s a simple
 Text Color: example program with three paragraphs:
 Set the text color using the color property: HTML
 <h1 style="color: blue;">This is a <!DOCTYPE html>
heading</h1>
<html>
 <p style="color: red;">This is a paragraph.</p>
<head>
 Fonts:
 Specify the font using the font-family <title>Paragraph Example</title>
property: </head>
<body> HTML
<p>This is a first paragraph. You can add any kind of text here.</p>
<h1 style="color: blue;">This is a heading</h1>
<p>This is a second paragraph. This is some sample text.</p>
<p style="color: red;">This is a paragraph.</p>
<p>This is another paragraph.</p>
Here, the heading text is blue, and the paragraph text is red 1.
</body>
</html> 3. Fonts: To specify the font family, use the font-family property within
the style attribute:
Output:
HTML
This is a first paragraph. You can add any kind of text here.
This is a second paragraph. This is some sample text. <h1 style="font-family: verdana;">This is a heading</h1>
This is another paragraph <p style="font-family: courier;">This is a paragraph.</p>
The heading uses the “verdana” font, and the paragraph uses the “courier”
In HTML, you can apply inline styles directly to individual elements using
font 1.
the style attribute. These styles define how an element should appear. Let’s look at
some examples: 4. Text Size: Adjust the text size using the font-size property:

1. Background Color: To set the background color for an HTML HTML


element, use the background-color property within the style attribute.
For instance: <h1 style="font-size: 300%;">This is a heading</h1>
<p style="font-size: 160%;">This is a paragraph.</p>
HTML The heading is 300% of the default size, and the paragraph is 160% 1.
5. Text Alignment: Control horizontal text alignment with the text-
<body style="background-color: powderblue;">
align property:
<h1>This is a heading</h1>
<p>This is a paragraph.</p> HTML
</body>
<h1 style="text-align: center;">Centered Heading</h1>
This example sets the background color of the entire page to
“powderblue” 1. <p style="text-align: center;">Centered paragraph.</p>.
2. Text Color: To define the text color, use the color property within Both the heading and paragraph are centered 1.
the style attribute. For example:
In HTML, you can specify colors using color names, RGB values, or <p>This is a quoted text. Lorem ipsum dolor sit amet...</p>
hexadecimal (HEX) codes. Let’s explore some examples: <cite>— John Doe</cite>
 Color Names: You can use predefined color names like “Tomato,” </blockquote>
“DodgerBlue,” or “MediumSeaGreen.” Here’s how to set the
Replace the placeholder text with your actual quote and citation.
background color and text color using color names:

HTML  Nested Blockquotes: You can nest blockquotes within each other for
multiple levels of quoting:
<h1 style="background-color: DodgerBlue;">Hello World</h1>
HTML
<p style="color: Tomato;">Lorem ipsum...</p>
 RGB Values: RGB values allow you to define colors using red, green, <blockquote>
and blue intensity levels (0 to 255). For instance: <p>This is the outer quote.</p>
<blockquote>
HTML
<p>This is a nested quote.</p>
<h1 style="background-color: rgb(255, 99, 71);">...</h1> </blockquote>
 HEX Codes: HEX codes represent colors as six-character combinations </blockquote>
(e.g., #FF6347 for Tomato). Use them like this:

HTML Comments: In HTML, you can add comments using the <!-- ... --> syntax.
Comments are not displayed by browsers but can help document your HTML
<h1 style="background-color: #FF6347;">...</h1> source code. Here’s a simple example:

HTML
In HTML, you can use the <blockquote> element to create block-level <!-- This is a comment -->
quotations. Here’s how you can format quotations: <p>This is a paragraph.</p>
<!-- End of paragraph -->
 Blockquote: To create a blockquote, wrap the quoted text within
the <blockquote> tags. You can also include a citation using
the <cite> element: <img> Tag:

HTML In HTML, you can use the <img> tag to embed images in your web pages.
Here’s a simple example of how to use it:
<blockquote>
HTML <td>Germany</td>
<img src="image.jpg" alt="A beautiful sunset"> </tr>
In this example: <tr>
<td>Centro comercial Moctezuma</td>
 The src attribute specifies the path to the image file (in this case, <td>Francisco Chang</td>
“image.jpg”).
<td>Mexico</td>
 The alt attribute provides an alternate text for the image, which is
displayed if the image cannot be shown. </tr>
</table>
In HTML, tables allow web developers to organize data into rows and AI-generated code. Review and use carefully. More info on FAQ.
columns. Let’s break down the essential tags:
 <table>: Defines a table. It serves as the container for all table-related In this example:
elements.
 <tr>: Represents a row within the table. Each row starts with <tr> and ends  The first row contains header cells (Company, Contact, Country).
with </tr>.  The subsequent rows contain data cells (company names, contacts, and
 <th>: Stands for “table header.” It defines header cells (usually the first countries).
row) that describe the content in the columns. Header cells are typically
bold and centered. List & Types:
 <td>: Stands for “table data.” It defines regular data cells within the rows.
These cells contain the actual content of the table. In HTML, lists allow you to organize content in a structured manner. Let’s
explore the different types of lists:
Here’s a simple example program:
1. Ordered Lists (OL):
HTML An ordered list starts with the <ol> tag and contains list items defined by <li> tags.
<table>
<tr> By default, ordered lists use numbers (1, 2, 3, …).

<th>Company</th>
You can customize the numbering type using the type attribute:
<th>Contact</th>
<th>Country</th>  type="1": Numbers (default)
</tr>  type="A": Uppercase letters (A, B, C, …)
 type="a": Lowercase letters (a, b, c, …)
<tr>
 type="I": Uppercase Roman numerals (I, II, III, …)
<td>Alfreds Futterkiste</td>
 type="i": Lowercase Roman numerals (i, ii, iii, …)
<td>Maria Anders</td>
Example: You can control the bullet style using CSS:
 .disc: Filled circle
HTML  .circle: Hollow circle
 .square: Square
<ol type="A">
Example:
<li>Coffee</li>
<li>Tea</li> HTML
<li>Milk</li>
<style>
</ol>
.disc { list-style-type: disc; }
AI-generated code. Review and use carefully. More info on FAQ. .circle { list-style-type: circle; }
.square { list-style-type: square; }
2. Unordered Lists (UL):
</style>
 An unordered list starts with the <ul> tag and contains list
items defined by <li> tags. <ul class="disc">
 Unordered lists use bullet points (disc, circle, or square) by <li>This is a list with disc markers.</li>
default. <li>Items don't need to be in order.</li>
 You can customize the bullet style using CSS (see below).
</ul>
Example:
<ul class="circle">
HTML <li>This is a list with circle markers.</li>
<li>Items don't need to be in order.</li>
<ul>
</ul>
<li>Apples</li>
<li>Bananas</li> AI-generated code. Review and use carefully. More info on FAQ.
<li>Oranges</li>
</ul> 4. Definition Lists (DL):
o A definition list (<dl>) groups terms with their corresponding definitions.

Use <dt> for terms and <dd> for descriptions.


3. .Custom Bullet Styles (UL):
Example:  <span>: Used to mark up a part of text or a
document.
HTML  <a>: Hyperlinks.
 <strong>: Strong emphasis.
<dl>  <em>: Emphasized text.
<dt>HTML</dt>
<dd>HyperText Markup Language</dd> 3. Classes:
<dt>CSS</dt>
The class attribute in HTML is used to specify a class for an element.
<dd>Cascading Style Sheets</dd> Multiple HTML elements can share the same class, allowing you to apply
</dl> consistent styling or behavior to them1.

Let’s dive into HTML blocks and classes: Frame:


1. Block-level Elements:
These elements structure the main content of a webpage. They typically start on a In HTML, frames were used in the past to divide a webpage into separate
new line and take up the full width of their container. sections. However, they are no longer recommended due to various issues.
Instead, consider using <iframe> tags to embed content from other
Examples of block-level elements include:
documents within your current HTML page1.
 <div>: Used as a container for other HTML Here’s an example of how you might have used frames in the past:
elements. HTML
 <p>: Defines a paragraph. <html>
 <h1> to <h6>: Headings.
<head></head>
 <ul>: Unordered lists.
<frameset border="0" frameborder="0" framespacing="0" rows="20%,*">
2. Inline Elements: <frame src="title.html">
<frameset border="0" frameborder="0" framespacing="0" cols="30%,*">
These elements are used within block-level elements to style or format <frame src="menu.html">
specific parts of the content.Inline elements do not start on a new line
<frame src="content.html">
and only take up as much width as necessary.
</frameset>
Examples of inline elements include: </frameset>
</html>
1. File Paths in HTML: Responsive text size:

A file path describes the location of a file within a website’s folder Set text size using the “vw” unit (viewport width).
structure.
Example:
Examples:
HTML
 <img src="picture.jpg">: The “picture.jpg” file is in the same
folder as the current page. <h1 style="font-size: 10vw;">Hello World</h1>
 <img src="images/picture.jpg">: The file is in the “images” folder
within the current folder. Media queries allow different styles for different screen sizes2.
 <img src="/images/picture.jpg">: The file is in the “images”
folder at the root of the website. 3. Symbols and Layout:
1. HTML doesn’t directly include symbols, but you can use character entities
 <img src="../picture.jpg">: The file is in a folder one level up
(e.g., &copy; for ©).
from the current folder1.
2. For layout, use HTML elements like <div> and CSS for styling.
3. Explore CSS frameworks like W3.CSS and Bootstrap for efficient layout
2. Responsive Web Design (HTML): design.

Responsive design ensures web pages look good on all devices.Use


the <meta> tag to set the viewport:

HTML

<meta name="viewport" content="width=device-width, initial-scale=1.0">

Responsive images:

Use width: 100% or max-width: 100% to make images responsive.

Example:

HTML

<img src="img_girl.jpg" style="max-width: 100%; height: auto;">


Unit – II HTML Input Types

HTML forms: HTML form elements, input types, input attributes, HTML supports various input types, each suited for different kinds of user
HTML5, HTML graphics, HTML media – video, audio, plug INS, you input. Some common input types include:
tube.
HTML API’S: Geo location, Drag/drop, local storage, HTML SSE.  Text Input (<input type="text">): Used for single-line text input.
CSS: CSS home, introduction, syntax, colours, back ground, borders,  Password Input (<input type="password">): Conceals user input
margins, padding, height/width, text, fonts, icons, tables, lists, position, over for passwords.
flow, float, CSS combinators, pseudo class, pseudo elements, opacity, tool  Checkbox (<input type="checkbox">): Allows selecting multiple
tips, image gallery, CSS forms, CSS counters, CSS responsive.HTML options from a list.
forms are essential for gathering user input on web pages. Here's an  Radio (<input type="radio">): Allows selecting a single option
overview of HTML form elements, input types, and input attributes from a list.
commonly used:  Number (<input type="number">): For inputting numeric values.
*********************************************************  Date (<input type="date">): For selecting dates.
 File (<input type="file">): Allows users to upload files.
HTML Form Structure  Submit (<input type="submit">): Submits the form data to the
server.
A basic HTML form is defined using the <form> element. It typically
encloses various input elements and a submit button. Here's a simple HTML Input Attributes
example:
Each input type can have additional attributes that modify its behavior or
<form action="/submit-form" method="post"> appearance:
<!-- Form inputs go here -->
<input type="text" name="username" placeholder="Enter your  name: Specifies the name of the input, used when submitting the
username"><br> form.
<input type="password" name="password" placeholder="Enter your  value: Specifies the initial value of the input.
password"><br>  placeholder: Provides a hint to the user about what to enter.
<input type="submit" value="Submit">  required: Makes the input mandatory.
</form>  disabled: Disables the input so it cannot be edited.
 readonly: Makes the input read-only (cannot be edited).
<form>: Defines the start of a form.  maxlength: Specifies the maximum number of characters allowed
for text inputs.
o action: Specifies where to send the form data when
submitted. Example Usage
o method: Specifies the HTTP method (get or post) for sending
form data. <form action="/submit-form" method="post">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required><br> HTML5 introduces new semantic elements that provide clearer meanings to
different parts of a web page, making it easier for developers to structure
<label for="password">Password:</label> content:
<input type="password" id="password" name="password" required><br>
 <header>: Represents introductory content at the beginning of a
<label for="remember">Remember me:</label> section or page.
<input type="checkbox" id="remember" name="remember"><br>  <footer>: Represents a footer for its nearest section or article.
 <nav>: Defines a section with navigation links.
<input type="submit" value="Login">  <section>: Defines sections in a document, such as chapters,
</form> headers, footers, or any other sections of the document.
 <article>: Represents self-contained content that could be
In this example: distributed and reused independently.
 <aside>: Represents content aside from the content it is placed in.
 type="text" and type="password" define text and password inputs.
 required ensures both fields must be filled out before the form can Multimedia Support
be submitted.
 type="checkbox" allows the user to select whether to be HTML5 includes native support for embedding multimedia content without
remembered. plugins:
 type="submit" creates a submit button to send the form data to the
server.  <audio>: Embeds audio content in a web page.
 <video>: Embeds video content in a web page.
Conclusion  <source>: Specifies multiple media resources for <audio> and
<video> elements, allowing the browser to choose the most suitable
HTML forms and their elements are fundamental for user interaction on the one.
web. Understanding how to structure forms, use different input types, and
apply input attributes effectively is crucial for building functional and user- Form Enhancements
friendly web applications
HTML5 provides new input types and attributes for forms, improving user
HTML5, the latest version of HTML (Hypertext Markup Language), experience and validation:
introduces several new features, elements, and attributes that enhance the
capabilities of web pages and applications. Here are some key aspects of  New Input Types: Such as email, url, tel, number, date, time, color,
HTML5: etc., providing more specific input controls and enabling better user
input validation.
Semantic Elements  Attributes: Like autocomplete, autofocus, placeholder, and required
provide additional control and usability enhancements for form
elements.
Improved Accessibility Conclusion

HTML5 incorporates features that enhance accessibility for users with HTML5 significantly advances the capabilities of web development by
disabilities: introducing new elements, APIs, and features that enhance multimedia
support, improve semantic structure, provide better form handling, and
 <figure> and <figcaption>: Used to mark up illustrations, increase accessibility and performance. Embracing HTML5 allows
diagrams, photos, code listings, etc., with an optional caption. developers to create richer, more interactive, and more accessible web
 aria-* attributes: Allows developers to add ARIA (Accessible Rich experiences.
Internet Applications) roles, states, and properties to HTML
elements, enhancing accessibility for assistive technologies. HTML graphics

Local Storage HTML provides several ways to incorporate graphics into web pages,
primarily through the use of <img>, <canvas>, and SVG (<svg>) elements.
 localStorage and sessionStorage: APIs introduced in HTML5 that Each method serves different purposes and offers distinct advantages:
allow web applications to store data locally within the user's
browser. localStorage persists data indefinitely, while 1. <img> Element
sessionStorage persists data for the duration of the page session.
The <img> element is the most straightforward way to embed graphics in
Canvas and SVG HTML. It is used for displaying static images that are linked from external
sources:
 <canvas>: Provides a space on the page for dynamically rendering
graphics, animations, or other visual images via scripting <img src="image.jpg" alt="Description of the image">
(JavaScript).
 <svg>: Defines vector-based graphics for the web, allowing for  src attribute: Specifies the URL of the image file.
scalable and interactive graphics and animations.  alt attribute: Provides a text description of the image, used for
accessibility and in cases where the image cannot be displayed.
Geolocation API
2. <canvas> Element
 Geolocation: Allows web applications to request the geographical
location of the user's device. This enables location-aware browsing The <canvas> element is used for drawing graphics dynamically using
experiences and services. JavaScript. It provides a drawing surface that can be manipulated through
scripting to create animations, games, charts, and other visualizations:
Web Workers
<canvas id="myCanvas" width="400" height="200"></canvas>
 Web Workers: Enable running scripts in background threads,
allowing for multitasking and improving responsiveness in web  JavaScript: You use JavaScript to draw on the <canvas> using its
applications. 2D or 3D context APIs (getContext('2d') or getContext('webgl')).
 Attributes: width and height attributes determine the size of the the specific requirements of your project regarding interactivity, scalability,
canvas. and dynamic content generation.

3. SVG (<svg>) Element HTML provides various ways to integrate media content like video and
audio into web pages, including support for plugins and embedding services
SVG (Scalable Vector Graphics) is a markup language for describing two- like YouTube. Here’s a detailed overview:
dimensional graphics in XML format. It allows for scalable and interactive
graphics that can be styled and manipulated using CSS and JavaScript: 1. Video and Audio Elements

<svg width="100" height="100"> HTML5 introduced native support for embedding video and audio content
<circle cx="50" cy="50" r="40" stroke="black" stroke-width="2" using the <video> and <audio> elements. These elements allow developers
fill="red" /> to embed media directly into web pages without relying on third-party
</svg> plugins.

 Elements: SVG uses various elements like <circle>, <rect>, <line>, <video> Element
<path>, etc., to create shapes and graphics.
 Advantages: SVG graphics are resolution-independent and can be The <video> element is used to embed video content on a web page. Here's
scaled without losing quality, making them ideal for icons, logos, a basic example:
and interactive graphics.
<video width="640" height="360" controls>
Choosing the Right Approach <source src="video.mp4" type="video/mp4">
Your browser does not support the video tag.
 Static Images (<img>): Use when displaying simple, non- </video>
interactive images fetched from a URL.
 Dynamic Graphics (<canvas>): Ideal for animations, games, and  Attributes:
complex visualizations where you need programmatic control over o src: Specifies the URL of the video file.
drawing. o type: Specifies the MIME type of the video file (optional but
 Scalable and Interactive Graphics (SVG): Best for scalable recommended).
vector-based graphics that require interaction and animation o width and height: Sets the dimensions of the video player.
capabilities. o controls: Adds playback controls (play, pause, volume, etc.)
to the video player.
Conclusion
<audio> Element
HTML provides multiple ways to integrate graphics into web pages,
catering to different needs from simple static images to complex interactive The <audio> element is used to embed audio content on a web page. Here’s
visualizations. Choosing between <img>, <canvas>, and SVG depends on a simple example:
<audio controls>  Fallback Content: Provide alternative content or messages inside
<source src="audio.mp3" type="audio/mpeg"> <video> and <audio> elements for browsers that do not support
Your browser does not support the audio tag. them or cannot play the specified media types.
</audio>  Accessibility: Use appropriate captions and transcripts for videos
and audio content to ensure accessibility for all users.
 Attributes:  Responsive Design: Ensure that embedded media elements are
o src: Specifies the URL of the audio file. responsive by setting appropriate width and height attributes or
o type: Specifies the MIME type of the audio file (optional but using CSS.
recommended).
o controls: Adds playback controls (play, pause, volume, etc.) Conclusion
to the audio player.
HTML provides robust support for embedding and integrating media
2. Plugins content such as video and audio directly into web pages using native
elements like <video> and <audio>. Additionally, services like YouTube
Historically, plugins like Adobe Flash and Java Applets were used to embed can be easily integrated using <iframe> elements. Embracing HTML5
multimedia content and interactive applications into web pages. However, standards ensures compatibility, accessibility, and performance for
due to security concerns and the adoption of HTML5 standards, browser multimedia content on the web
support for plugins has significantly decreased. It's now recommended to
use native HTML5 elements (like <video> and <audio>) or other modern HTML5 introduced several APIs that greatly enhance the capabilities of
web technologies for multimedia content. web applications, enabling features like geolocation, drag and drop
functionality, local storage, and Server-Sent Events (SSE). Here’s an
3. Embedding YouTube Videos overview of each API:

To embed a YouTube video into a web page, you can use an <iframe> Geolocation API
element with the video's embed URL:
 Purpose: Determines the geographical location of a user.
<iframe width="560" height="315"  Usage: Location-based services, mapping, weather apps, etc.
src="https://www.youtube.com/embed/VIDEO_ID" frameborder="0"  Key methods:
allowfullscreen></iframe> o navigator.geolocation.getCurrentPosition(): Gets the current
position.
 Replace VIDEO_ID with the actual ID of the YouTube video you o navigator.geolocation.watchPosition(): Continuously tracks
want to embed. the position.
 Example:
Best Practices
JavaScript

function success(position) {
const latitude = position.coords.latitude;  Purpose: Stores data locally on the user's browser.
const longitude = position.coords.longitude;  Usage: Saving user preferences, shopping cart items, game progress,
console.log(`Latitude: ${latitude}, Longitude: ${longitude}`); etc.
}  Key methods:
o localStorage.setItem(key, value): Stores data.
function error() { o localStorage.getItem(key): Retrieves data.
console.error("Unable to retrieve geolocation"); o localStorage.removeItem(key): Removes data.
}  Example:

navigator.geolocation.getCurrentPosition(success, error); JavaScript

Drag and Drop API localStorage.setItem("username", "johnDoe");


const username = localStorage.getItem("username");
 Purpose: Allows users to drag and drop elements within a webpage console.log(username);
or between different windows.
 Usage: File uploads, reordering elements, interactive games, etc. Server-Sent Events (SSE)
 Key events:
o dragstart: Initiates a drag operation.  Purpose: Enables servers to push data to clients in real-time.
o drag: Occurs during a drag operation.  Usage: Live updates, notifications, chat applications, etc.
o drop: Occurs when an element is dropped.  Key elements:
 Example: o Server-side: Uses EventSource object to send events.
o Client-side: Uses EventSource object to listen for events.
JavaScript  Example:

element.addEventListener("dragstart", (event) => { JavaScript


event.dataTransfer.setData("text/plain", element.id);
}); const source = new EventSource('/sse-endpoint');
source.addEventListener('message', (event) => {
dropZone.addEventListener("drop", (event) => { console.log(event.data);
event.preventDefault(); });
const data = event.dataTransfer.getData("text/plain");
const draggedElement = document.getElementById(data); Note: While these APIs are primarily associated with HTML5, they are
dropZone.appendChild(draggedElement); widely supported by modern browsers.
});

Local Storage API


What is CSS? HTML

CSS stands for Cascading Style Sheets. It's a language used to style <head>
HTML elements, defining how they appear on web pages. Think of it as the <style>
makeup for your website. It controls the layout, colors, fonts, and overall h1 {
presentation of your content. color: blue;
}
Key functions of CSS: </style>
</head>
 Controls the look and feel: Determines the visual style of web
pages.  Pros: Applies styles to multiple elements within the same page.
 Improves efficiency: Applies styles consistently across multiple  Cons: Not suitable for large-scale projects, styles are limited to one
pages. page.
 Separates content from presentation: Keeps HTML focused on
content, making it easier to maintain. 3. External CSS
 Enhances user experience: Creates visually appealing and user-
friendly websites.  Styles are defined in a separate .css file and linked to the HTML
document using the <link> tag.
Types of CSS  Syntax: <link rel="stylesheet" href="styles.css">
 Pros: Best practice for large projects, reusability, maintainability,
There are three main types of CSS: separation of concerns.
 Cons: Requires an additional file.
1. Inline CSS
External CSS is generally the preferred method for most web
 Styles are applied directly to individual HTML elements using the development projects.
style attribute.
 Syntax: <element style="property: value;"> Beyond these basic types, CSS also offers a vast array of features and
 Example: <h1 style="color: red;">This is a red heading</h1> properties for advanced styling:
 Pros: Quick styling for specific elements.
 Cons: Poor readability, difficult to maintain for multiple elements.  Selectors: Target specific HTML elements for styling.
 Properties and values: Define the style characteristics of elements.
2. Internal (Embedded) CSS  Units: Specify measurements for properties like font size, width,
and height.
 Styles are defined within the <head> section of the HTML  Media queries: Create responsive designs that adapt to different
document using the <style> tag. screen sizes.
 Syntax: <style> selector { property: value; }</style>  Layout methods: Control the arrangement of elements on the page
 Example: (e.g., flexbox, grid).
By effectively using CSS, you can create visually stunning and engaging  background-color: Sets the background color of an element.
websites that enhance the user experience.  background-image: Adds an image as the background.
 background-repeat: Controls how the background image is repeated.
CSS Syntax  background-position: Positions the background image.
 background-attachment: Specifies whether the background image is
 Selector: Specifies the HTML element(s) to be styled. fixed or scrolls with the page.
 Property: The style attribute you want to apply.
 Value: The desired value for the property. Borders

Basic syntax:  border-width: Sets the width of the border.


 border-style: Sets the style of the border (solid, dotted, dashed, etc.).
CSS  border-color: Sets the color of the border.
 Shorthand: border: width style color;
selector {
property: value; Margins
}
 Create space outside an element.
Example:  margin-top, margin-right, margin-bottom, margin-left.
 Shorthand: margin: top right bottom left;
CSS
Padding
h1 {
color: red;  Create space inside an element.
font-size: 36px;  padding-top, padding-right, padding-bottom, padding-left.
}  Shorthand: padding: top right bottom left;

Colors Height/Width
CSS offers various ways to specify colors:  Sets the height and width of an element.
 height and width properties.
 Color names: red, blue, green, etc.
 Hexadecimal values: #FF0000, #00FF00, #0000FF, etc. Text
 RGB values: rgb(255, 0, 0), rgb(0, 255, 0), rgb(0, 0, 255), etc.
 HSL values: hsl(0, 100%, 50%), hsl(120, 100%, 50%), hsl(240,  color: Sets the text color.
100%, 50%), etc.  font-size: Sets the font size.
 font-family: Specifies the font to be used.
Background
 text-align: Aligns the text within an element (left, right, center,  sticky: Positions an element relative to its parent until it reaches a
justify). specified offset, then it becomes fixed.
 text-decoration: Adds decorations like underline, overline, line-
through. Overflow

Fonts  overflow: Specifies what happens if content overflows an element's


box.
 font-family: Specifies the font to be used. o visible: Content is not clipped.
 font-size: Sets the font size. o hidden: Content is clipped.
 font-weight: Sets the font weight (bold, normal). o scroll: Adds scrollbars to the element.
 font-style: Sets the font style (italic, normal). o auto: Adds scrollbars if content overflows.

Icons Float

 Typically used with image formats (PNG, SVG) or font icons.  Makes an element float to the left or right of its container.
 background-image property can be used to display icons as  float: left or float: right.
background images.
 Font icons provide a scalable and flexible way to use icons. CSS Combinators

Tables  Combine multiple selectors to target specific elements.


 descendant selector: Space between selectors (e.g., div p).
 Use <table>, <tr>, <td> elements for table structure.  child combinator: > (e.g., div > p).
 CSS can be used to style table elements, borders, cell spacing, etc.  adjacent sibling combinator: + (e.g., p + div).
 general sibling combinator: ~ (e.g., p ~ div).
Lists
Pseudo-classes and Pseudo-elements
 Use <ul> for unordered lists and <ol> for ordered lists.
 list-style-type property controls the list marker style. These are powerful tools for styling elements based on their state or to style
specific parts of an element.
Position
Pseudo-classes represent the state of an element, like hover, focus, or
 static: Default, no positioning. visited.
 relative: Positions an element relative to its normal position.
 absolute: Positions an element relative to its nearest positioned  Examples:
ancestor. o :hover: Styles an element when the mouse hovers over it.
 fixed: Positions an element relative to the viewport. o :active: Styles an element while it's being clicked or
activated.
o :focus: Styles an element when it has focus (usually for Style HTML form elements like input fields, buttons, and select boxes.
keyboard navigation).
 Properties: color, font-family, border, padding, background-color,
Pseudo-elements represent parts of an element, like the first letter or etc.
before/after content.  Pseudo-classes: :focus, :hover, :disabled, etc.

 Examples: CSS Counters


o ::before: Inserts content before the element's content.
o ::after: Inserts content after the element's content. Generate sequential numbers for elements, like numbering list items or
o ::first-letter: Styles the first letter of an element. creating custom counters.

Opacity  Properties: counter-reset, counter-increment, content.

Controls the transparency of an element. CSS Responsive Design

 Syntax: opacity: value; Create websites that adapt to different screen sizes and devices.
 Value: A number between 0 (fully transparent) and 1 (fully opaque).
 Media Queries: Detect the screen size and apply different styles
Tooltips based on it.
 Flexible layouts: Use units like em and rem for relative sizing.
Small pop-up boxes that provide extra information when hovering over an  Grid and Flexbox: Create responsive layouts efficiently.
element.
Would you like to explore any of these topics in more detail? I can
 Usually created using a combination of HTML, CSS, and provide examples, code snippets, or explanations based on your specific
JavaScript. needs.
 CSS is used to style the tooltip itself and to position it correctly.

Image Gallery

A collection of images displayed in a structured way.

 CSS is used for layout, spacing, transitions, and effects.


 Often combined with JavaScript for image swapping, lightboxes,
and navigation.

CSS Forms
Unit – III (10 hours)  Event Handling: Responding to user interactions like button clicks,
form submissions, and input changes.
Client side Validation: Introduction to JavaScript - What is DHTML,  Regular Expressions: Pattern matching for complex validation
JavaScript, basics, variables, string manipulations, mathematical functions, rules (e.g., email, phone number).
statements, operators, arrays, functions. Objects in JavaScript - Data and  Data Types: Understanding different data types (strings, numbers,
objects in JavaScript, regular expressions, exception handling. DHTML booleans) for appropriate validation.
with JavaScript - Data validation, opening a new window, messages and
confirmations, the status bar, different frames, rollover buttons, moving Common Validation Scenarios
images.
Here are some typical validation checks:
*********************************************************
 Required Fields: Ensuring that mandatory fields are filled.
Client-Side Validation with JavaScript: An Introduction  Data Formats: Verifying correct input formats (e.g., email, phone
number, date).
Understanding Client-Side Validation  Data Ranges: Checking values within specified limits (e.g., age,
quantity).
Client-side validation is the process of checking user input for accuracy and  Custom Validation: Applying specific rules based on application
completeness before submitting it to a server. This is primarily done using logic.
JavaScript to examine form data within the user's browser.
Basic Validation Example
Why is it important?
Let's validate a simple form with name and email fields:
 Improved User Experience: Provides immediate feedback to users,
preventing incorrect submissions and frustrating error messages HTML
from the server.
 Reduced Server Load: Prevents unnecessary server requests by <form id="myForm">
filtering out invalid data upfront. <label for="name">Name:</label>
 Enhanced Data Integrity: Ensures data consistency and accuracy <input type="text" id="name" name="name" required>
before it reaches the server. <br>
<label for="email">Email:</label>
Basic JavaScript Concepts for Validation <input type="email" id="email" name="email" required>
<br>
Before diving into validation, let's review essential JavaScript concepts: <button type="submit">Submit</button>
</form>
 DOM Manipulation: Accessing and manipulating HTML elements
using JavaScript.
JavaScript What is DHTML

const form = document.getElementById('myForm'); DHTML: A Blend of Technologies for Dynamic Web Pages
form.addEventListener('submit', (event) => {
event.preventDefault(); // Prevent form submission DHTML stands for Dynamic HyperText Markup Language. It's not a
language itself but rather a term used to describe the combination of
const name = document.getElementById('name').value; technologies that create interactive and dynamic web pages.
const email = document.getElementById('email').value;
Core Components of DHTML
// Basic validation (replace with more robust checks)
if (name === '') {  HTML: Structures the content of the web page.
alert('Please enter your name');  CSS: Styles the appearance of the page.
return;  JavaScript: Provides interactivity and dynamic behavior.
}  DOM (Document Object Model): Represents the page's structure
as objects, allowing JavaScript to manipulate it.
// Basic email validation (improve using regular expressions)
if (!email.includes('@')) { How DHTML Works
alert('Please enter a valid email address');
return; By working together, these technologies enable:
}
 Interactive elements: Buttons, menus, forms that respond to user
// Form is valid, submit it (or perform other actions) actions.
console.log('Form submitted:', { name, email });  Animations: Moving and changing elements on the page without
// form.submit(); // Uncomment to submit the form reloading.
});  Dynamic content: Updating parts of a page without loading a new
one.
Key Points to Remember  Rich user experiences: Creating engaging and immersive web
applications.
 Client-side validation is not a replacement for server-side
validation. Always validate data on the server for security and Example: A Simple DHTML Dropdown Menu
robustness.
 Use clear and informative error messages to guide users. HTML
 Consider using HTML5 form validation attributes for basic checks.
 Leverage regular expressions for complex pattern matching. <ul id="myMenu">
 Test your validation thoroughly with different input scenarios. <li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>  JavaScript code is typically embedded within <script> tags in an
Use code with caution. HTML file:

CSS HTML
#myMenu { <script>
display: none; // Your JavaScript code here
} </script>
JavaScript

const menu = document.getElementById('myMenu');  JavaScript is case-sensitive.


const button = document.createElement('button');
button.textContent = 'Show Menu'; 2. Variables:
button.addEventListener('click', () => {
menu.style.display = menu.style.display === 'none' ? 'block' : 'none';  Used to store data.
});  Declared using let or const:
document.body.appendChild(button);
JavaScript
This code creates a simple dropdown menu using HTML, CSS, and
JavaScript. The button toggles the display of the menu when clicked. let age = 30; // Variable using let (can be reassigned)
const name = "Alice"; // Constant using const (cannot be reassigned)
DHTML vs. Traditional HTML
3. Data Types:
While HTML creates static web pages, DHTML brings them to life with
interactivity and dynamic features. It's the foundation for modern web  Numbers: Integers and floating-point numbers.
development and has been superseded by more advanced frameworks and  Strings: Textual data enclosed in quotes (single or double).
libraries, but understanding DHTML is essential for grasping the  Booleans: True or false values.
fundamentals of web development.  Null: Represents no value.
 Undefined: Represents a variable that has been declared but not
What is JavaScript? assigned a value.
 Objects: Collections of key-value pairs.
JavaScript is a programming language that adds interactivity to your  Arrays: Ordered collections of values.
website. It's used to create dynamic and engaging web experiences. Think
of it as the magic that brings your website to life! 4. Operators:

Getting Started  Arithmetic operators: +, -, *, /, %.


 Comparison operators: ==, !=, <, >, <=, >=.
1. Basic Syntax:  Logical operators: && (and), || (or), ! (not).
5. Control Flow: 8. Objects:

 if...else statements: Execute code based on conditions.  Unordered collections of key-value pairs.

JavaScript JavaScript

if (age >= 18) { const person = {


console.log("You are an adult"); name: "John Doe",
} else { age: 30,
console.log("You are a minor"); city: "New York"
} };

 switch statements: Efficiently handle multiple conditions. Example: A Simple Calculator


 Loops: Repeat code execution.
o for loop: Repeats a block of code a specific number of times. JavaScript
o while loop: Repeats a block of code as long as a condition is
true. function calculate(operator, num1, num2) {
o do...while loop: Similar to while but executes the code block switch (operator) {
at least once. case '+':
return num1 + num2;
6. Functions: case '-':
return num1 - num2;
 Reusable blocks of code. case '*':
return num1 * num2;
JavaScript case '/':
return num1 / num2;
function greet(name) { default:
console.log("Hello, " + name + "!"); return "Invalid operator";
} }
}
7. Arrays:
const result = calculate('+', 5, 3);
 Ordered collections of data. console.log(result); // Output: 8

JavaScript Next Steps

 DOM Manipulation: Interacting with HTML elements.


const fruits = ["apple", "banana", "orange"];
 Events: Responding to user actions. Searching and Extracting Substrings
 Asynchronous JavaScript: Handling non-blocking operations.
 Object-Oriented Programming (OOP) concepts: Classes,  indexOf(searchValue, fromIndex): Returns the index of the first
inheritance, etc. occurrence of a specified value, or -1 if not found.
 lastIndexOf(searchValue, fromIndex): Returns the index of the
JavaScript String Manipulation last occurrence of a specified value, or -1 if not found.
 substring(startIndex, endIndex): Extracts characters from a string,
JavaScript offers a rich set of methods for manipulating strings, making between two specified indices.
them versatile for various tasks. Let's explore some common operations:  slice(startIndex, endIndex): Extracts a part of a string and returns a
new string.
Basic String Operations  substr(startIndex, length): Extracts characters from a string,
starting at a specified index and returning a specified number of
 Accessing Characters: characters.
o charAt(index): Returns the character at the specified index.
o charCodeAt(index): Returns the Unicode value of the JavaScript
character at the specified index. let text = "The quick brown fox jumps over the lazy dog";
 String Length:
o length: Returns the length of the string. console.log(text.indexOf("fox")); // 16
 Concatenation: console.log(text.lastIndexOf("the")); // 32
o + operator: Combines two or more strings. console.log(text.substring(4, 9)); // quick
o concat() method: Combines two or more strings. console.log(text.slice(-4)); // dog
 Template Literals: console.log(text.substr(10, 5)); // brown
o Use backticks () to embed expressions within strings.
Modifying Strings
JavaScript
let str = "Hello, world!";  toUpperCase(): Converts a string to uppercase.
 toLowerCase(): Converts a string to lowercase.
console.log(str.charAt(7)); // o  trim(): Removes whitespace from both ends of a string.
console.log(str.charCodeAt(0)); // 72  replace(searchValue, newValue): Replaces a specified value with
console.log(str.length); // 13 another value.
 split(separator): Splits a string into an array of substrings based on
let newStr = str + " How are you?"; a separator.
console.log(newStr); // Hello, world! How are you?  join(separator): Joins elements of an array into a string.

let name = "Alice"; JavaScript


let greeting = `Hello, ${name}!`; let str = " Hello, World! ";
console.log(greeting); // Hello, Alice!
console.log(str.toUpperCase()); // HELLO, WORLD!  Math.max(x, y, ...): Returns the largest of the given numbers.
console.log(str.trim()); // Hello, World!  Math.min(x, y, ...): Returns the smallest of the given numbers.
 Math.pow(base, exponent): Returns base raised to the power of
let replacedStr = str.replace("World", "Everyone"); exponent.
console.log(replacedStr); // Hello, Everyone!  Math.sqrt(x): Returns the square root of x.

let words = str.split(" "); Trigonometric Functions


console.log(words); // [ "", "Hello,", "World!", "" ]
 Math.sin(x): Returns the sine of x (in radians).
let joinedStr = words.join("-");  Math.cos(x): Returns the cosine of x (in radians).
console.log(joinedStr); // -Hello,-World!-  Math.tan(x): Returns the tangent of x (in radians).
 Math.asin(x): Returns the arcsine of x (in radians).
Regular Expressions  Math.acos(x): Returns the arccosine of x (in radians).
 Math.atan(x): Returns the arctangent of x (in radians).
JavaScript supports regular expressions for complex pattern matching and  Math.atan2(y, x): Returns the arctangent of y/x (in radians).
replacement.
Exponential and Logarithmic Functions
JavaScript
 Math.exp(x): Returns e raised to the power of x.
let email = "[email protected]";  Math.log(x): Returns the natural logarithm of x.
let emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;  Math.log2(x): Returns the base-2 logarithm of x.
console.log(emailRegex.test(email)); // true  Math.log10(x): Returns the base-10 logarithm of x.

Other Useful Functions


JavaScript Math Functions
 Math.random(): Returns a random number between 0 (inclusive)
JavaScript provides a built-in Math object that offers a wide range of and 1 (exclusive).
mathematical functions and constants. These functions are static, meaning  Math.PI: Returns the value of Pi.
you access them directly through the Math object without creating a Math  Math.E: Returns the value of Euler's number (e).
instance.
Example
Basic Arithmetic Functions
JavaScript
 Math.abs(x): Returns the absolute value of x.
 Math.ceil(x): Returns the smallest integer greater than or equal to x. let number = 4.6;
 Math.floor(x): Returns the largest integer less than or equal to x.
 Math.round(x): Returns the nearest integer to x. console.log(Math.abs(-5)); // Output: 5
console.log(Math.ceil(number)); // Output: 5 JavaScript
console.log(Math.floor(number)); // Output: 4
console.log(Math.round(number)); // Output: 5 let x = 10;
console.log(Math.max(2, 8, 3)); // Output: 8 x += 5;
console.log(Math.min(2, 8, 3)); // Output: 2
console.log(Math.pow(2, 3)); // Output: 8  Function calls:
console.log(Math.sqrt(16)); // Output: 4
console.log(Math.random()); // Output: a random number between 0 and 1 JavaScript
console.log(Math.PI); // Output: 3.141592653589793

JavaScript Statements console.log("Hello, world!");


Math.sqrt(16);
Statements are the fundamental building blocks of JavaScript code. They
 Object creation:
represent actions or commands that the JavaScript engine executes.
JavaScript
Types of Statements

Declaration Statements let person = { name: "John", age: 30 };

Control Flow Statements


 Variable declaration:
 Conditional statements:
JavaScript o if, else if, else
o switch
let age = 30;  Loop statements:
const name = "Alice"; o for
o while
 Function declaration: o do...while
o for...in
JavaScript o for...of

function greet(name) { Other Statements


console.log("Hello, " + name + "!");
}  Empty statement:
Expression Statements JavaScript
 Assignment: ; // Does nothing
 Return statement: }

JavaScript  Throw statement:

function add(x, y) { JavaScript


return x + y;
} throw new Error("Something went wrong");

 Break statement:  Debugger statement:

JavaScript JavaScript

for (let i = 0; i < 10; i++) { debugger; // Pauses execution for debugging
if (i === 5) {
break; Statement Terminators
}
} In JavaScript, statements are typically terminated by a semicolon (;).
However, it's optional in many cases.
 Continue statement:
Code Blocks
JavaScript
Multiple statements can be grouped together within curly braces {} to form
for (let i = 0; i < 10; i++) { a code block. This is often used with control flow statements and functions.
if (i % 2 === 0) {
continue; Example:
}
console.log(i); JavaScript
}
if (age >= 18) {
 Try...catch statement: console.log("You are an adult");
// More statements here
JavaScript }

try {
// Code that might throw an error
} catch (error) {
// Handle the error
JavaScript Operators  Equal: =
 Addition assignment: +=
Operators are special symbols that perform specific operations on one or  Subtraction assignment: -=
more operands. They are essential for manipulating data and performing  Multiplication assignment: *=
calculations in JavaScript.  Division assignment: /=
 Modulus assignment: %=
Types of Operators  Exponentiation assignment: **=

Arithmetic Operators JavaScript


let x = 10;
Used for basic mathematical operations: x += 5; // Equivalent to x = x + 5
console.log(x); // Output: 15
 Addition: +
Comparison Operators
 Subtraction: -
 Multiplication: *
 Division: / Used to compare values:
 Modulus (remainder): %
 Exponentiation: **  Equal to: ==
 Increment: ++  Not equal to: !=
 Decrement: --  Strict equal to: === (checks both value and type)
 Strict not equal to: !==
JavaScript  Greater than: >
 Less than: <
let x = 10;
 Greater than or equal to: >=
let y = 5;
 Less than or equal to: <=
console.log(x + y); // Output: 15
JavaScript
console.log(x - y); // Output: 5
console.log(x * y); // Output: 50 let x = 10;
console.log(x / y); // Output: 2 let y = "10";
console.log(x % y); // Output: 0
console.log(x ** 2); // Output: 100 console.log(x == y); // Output: true (value comparison)
x++; // Increment x by 1 console.log(x === y); // Output: false (value and type comparison)
y--; // Decrement y by 1
Logical Operators
Assignment Operators
Used to combine boolean expressions:
Used to assign values to variables:
 Logical AND: && Use code with caution.
 Logical OR: ||
 Logical NOT: ! 2. Array constructor:

JavaScript JavaScript
let x = true;
let y = false; const numbers = new Array(3, 1, 4, 1, 5, 9);

console.log(x && y); // Output: false Accessing Array Elements


console.log(x || y); // Output: true
console.log(!x); // Output: false Array elements are accessed by their index, which starts from 0.
Other Operators
JavaScript
 Ternary operator: condition ? expression1 : expression2 const fruits = ["apple", "banana", "orange"];
 Typeof operator: typeof console.log(fruits[0]); // Output: apple
 Instanceof operator: instanceof console.log(fruits[2]); // Output: orange
 Comma operator: ,
Modifying Array Elements

You can change the value of an element by assigning a new value to its
JavaScript Arrays index.

Arrays in JavaScript are used to store multiple values in a single variable. JavaScript
They can hold different data types, including numbers, strings, objects, and
even other arrays. fruits[1] = "grape";
console.log(fruits); // Output: ["apple", "grape", "orange"]
Creating Arrays
Array Length
There are two primary ways to create arrays:
The length property of an array indicates the number of elements in it.
1. Array literal:
JavaScript
JavaScript
console.log(fruits.length); // Output: 3
const fruits = ["apple", "banana", "orange"];
Adding and Removing Elements
 push(): Adds elements to the end of an array.  splice(): Removes or replaces elements at specific positions.
 pop(): Removes the last element from an array.  sort(): Sorts the elements of an array.
 unshift(): Adds elements to the beginning of an array.  reverse(): Reverses the order of elements in an array.
 shift(): Removes the first element from an array.  filter(): Creates a new array with elements that pass a test.
 splice(): Removes or replaces elements at specific positions.  map(): Creates a new array by transforming each element.
 reduce(): Reduces an array to a single value.
JavaScript
fruits.push("mango"); // Adds "mango" to the end JavaScript Functions
console.log(fruits); // Output: ["apple", "grape", "orange", "mango"]
Functions are reusable blocks of code designed to perform a specific task.
fruits.splice(1, 1); // Removes the element at index 1 They are essential for organizing and structuring your JavaScript code,
console.log(fruits); // Output: ["apple", "orange", "mango"] improving readability, and promoting code reusability.

Iterating Over Arrays Defining Functions

 for loop: There are two primary ways to define functions in JavaScript:

JavaScript Function Declaration


JavaScript
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]); function greet(name) {
} console.log("Hello, " + name + "!");
}
 forEach():
Function Expression
JavaScript JavaScript

const greet = function(name) {


fruits.forEach(fruit => console.log(fruit)); console.log("Hello, " + name + "!");
};
Other Useful Array Methods
Function Parameters and Arguments
 concat(): Combines two or more arrays.
 join(): Converts an array to a string.  Parameters are placeholders for values that will be passed to the
 indexOf(): Returns the index of the first occurrence of an element. function when it's called.
 lastIndexOf(): Returns the index of the last occurrence of an  Arguments are the actual values passed to the function when it's
element. invoked.
 slice(): Returns a shallow copy of a portion of an array.
JavaScript
function add(num1, num2) { // num1 and num2 are parameters myFunction();
return num1 + num2; console.log(localVariable); // Error: localVariable is not defined
}
Arrow Functions
const result = add(3, 4); // 3 and 4 are arguments
console.log(result); // Output: 7 A concise syntax for writing functions:

Return Values JavaScript

A function can return a value using the return keyword. If no return const greet = (name) => {
statement is present, the function implicitly returns undefined. console.log("Hello, " + name + "!");
};
JavaScript
Function Hoisting
function multiply(x, y) {
return x * y; Function declarations are hoisted, meaning they can be used before they are
} defined. Function expressions are not hoisted.

const product = multiply(5, 2); Function Expressions as Values


console.log(product); // Output: 10
Functions can be assigned to variables, passed as arguments, and returned
Function Scope from other functions.

 Global scope: Variables declared outside of functions are accessible Default Parameters
anywhere in the code.
 Local scope: Variables declared within a function are only You can specify default values for function parameters:
accessible within that function.
JavaScript
JavaScript
let globalVariable = "I'm global"; function greet(name = "World") {
console.log("Hello, " + name + "!");
function myFunction() { }
let localVariable = "I'm local";
console.log(globalVariable); // Accessible Rest Parameters
console.log(localVariable); // Accessible
} Collect multiple arguments into an array:
JavaScript age: 30,
city: "New York"
function sum(...numbers) { };
return numbers.reduce((total, num) => total + num, 0);
} 2. Constructor Function:

Recursive Functions JavaScript

Functions that call themselves directly or indirectly: function Person(firstName, lastName, age, city) {
this.firstName = firstName;
JavaScript this.lastName = lastName;
this.age = age;
function factorial(n) { this.city = city;
if (n === 0 || n === 1) { }
return 1;
} else { const person = new Person("Jane", "Smith", 25, "Los Angeles");
return n * factorial(n - 1);
} Accessing Object Properties
}
You can access object properties using dot notation or bracket notation:
Objects in JavaScript: A Comprehensive Overview
JavaScript
Objects are the fundamental building blocks of JavaScript. They are
collections of key-value pairs, where keys are strings or symbols, and console.log(person.firstName); // Output: John
values can be any data type, including other objects. This structure allows console.log(person["lastName"]); // Output: Doe
for flexible and complex data modeling.
Modifying Object Properties
Creating Objects
You can change the value of an object property:
There are two primary ways to create objects:
JavaScript
1. Object Literal:
person.age = 31;
JavaScript console.log(person.age); // Output: 31

const person = { Adding and Removing Properties


firstName: "John",
lastName: "Doe", You can add new properties to an object:
JavaScript
console.log(person.fullName()); // Output: John Doe
person.occupation = "Developer";
this Keyword
You can remove properties using the delete operator:
The this keyword refers to the object that the function is a method of.
JavaScript
Prototypes
delete person.city;
JavaScript objects inherit properties and methods from a prototype object.
Nested Objects You can modify the prototype to add shared properties and methods to all
instances of a constructor function.
Objects can contain other objects:
Important Notes
JavaScript
 Objects are reference types, meaning assigning one object to another
const address = { creates a reference to the same object in memory.
street: "123 Main St",  Object properties can be accessed and modified dynamically.
city: "New York",
state: "NY",
Regular Expressions in JavaScript
zipCode: "10001"
};
Regular expressions (often shortened to regex) are patterns used to match
person.address = address; character combinations in text. They are incredibly powerful for tasks like
searching, replacing, validating, and extracting information from strings.
Methods
Creating Regular Expressions
Object properties can hold functions, which are called methods.
There are two ways to create regular expressions in JavaScript:
JavaScript
1. Literal notation:
const person = {
firstName: "John", JavaScript
lastName: "Doe",
fullName: function() { const regex = /pattern/;
return this.firstName + " " + this.lastName;
} 2. Constructor:
};
JavaScript Using Regular Expressions

const regex = new RegExp('pattern');  test() method: Returns true if the pattern matches the entire string,
otherwise false.
Basic Syntax
JavaScript
 Characters: Match literal characters.
const regex = /cat/;
JavaScript console.log(regex.test("I have a cat")); // Output: true

/cat/ // Matches "cat"  match() method: Returns an array containing the matches, or null if
no match is found.
 Metacharacters: Have special meanings.
o . Matches any character except newline. JavaScript
o ^ Matches the beginning of the string.
o $ Matches the end of the string. const regex = /\d+/g;
o * Matches zero or more occurrences of the preceding const str = "I have 3 cats.";
character. console.log(str.match(regex)); // Output: ["3"]
o + Matches one or more occurrences of the preceding
character.  replace() method: Replaces matched text with a new string.
o ? Matches zero or one occurrence of the preceding character.
o \: Escapes special characters. JavaScript
 Character classes: Match a set of characters.
o [abc] Matches a, b, or c. const regex = /cat/g;
o [^abc] Matches any character except a, b, or c. const str = "I have a cat and a dog.";
o \d Matches a digit. console.log(str.replace(regex, "dog")); // Output: I have a dog and a
o \w Matches a word character (alphanumeric and underscore). dog.
o \s Matches a whitespace character.
 Quantifiers: Specify the number of occurrences. Example: Validating an Email Address
o {n} Matches exactly n occurrences.
o {n,} Matches at least n occurrences. JavaScript
o {n,m} Matches between n and m occurrences.
 Alternation: Matches one of several expressions. const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
o a|b Matches either a or b. const email = "[email protected]";
 Grouping: Groups subexpressions. console.log(emailRegex.test(email)); // Output: true
o (abc) Groups the characters abc.
Exception Handling in JavaScript 1. The try block contains the code that might potentially throw an
error.
Exception handling is a mechanism to manage errors or unexpected 2. If an error occurs, the catch block is executed. The error object
conditions that occur during program execution. It helps prevent program contains information about the error.
crashes and provides a way to gracefully handle these situations. 3. The finally block always executes, regardless of whether an error
occurred or not.
Key Components
Common Error Types
 try block: Encloses code that might throw an exception.
 catch block: Handles the exception if it occurs.  SyntaxError: Invalid syntax.
 finally block: Optional, executes code regardless of whether an  ReferenceError: Attempt to access an undefined variable.
exception is thrown or caught.  TypeError: Type mismatch.
 throw statement: Manually throws an exception.  RangeError: Number is outside the valid range.

Example Custom Exceptions

JavaScript You can create custom exceptions by throwing objects:

function divide(numerator, denominator) { JavaScript


try {
if (denominator === 0) { function validateAge(age) {
throw new Error("Division by zero"); if (age < 0) {
} throw new Error("Age cannot be negative");
return numerator / denominator; }
} catch (error) { // ...
console.error("An error occurred:", error.message); }
return NaN; // Or handle the error differently
} finally { DHTML with JavaScript: Data Validation
console.log("Division operation complete");
} DHTML (Dynamic HyperText Markup Language), a combination of
} HTML, CSS, and JavaScript, empowers you to create interactive and
dynamic web pages. A crucial aspect of this dynamism is ensuring data
console.log(divide(10, 2)); // Output: 5 integrity through robust data validation.
console.log(divide(10, 0)); // Output: An error occurred: Division by zero
Why Data Validation is Essential
Explanation
 Enhanced User Experience: Provides immediate feedback to users, JavaScript
preventing incorrect submissions and frustrating error messages
from the server. function validateAge(age) {
 Reduced Server Load: Prevents unnecessary server requests by if (age < 0 || age > 120) {
filtering out invalid data upfront. alert("Invalid age");
 Data Integrity: Ensures data consistency and accuracy before it return false;
reaches the server. }
return true;
Core Validation Techniques }

Basic Checks  Custom Validation: Apply specific rules based on application


logic.
 Required Fields: Ensure mandatory fields are filled.
Advanced Techniques
JavaScript
 Asynchronous Validation: Fetch data from the server for real-time
function validateRequired(field) { validation (e.g., checking username availability).
if (field.value.trim() === "") {  Regular Expressions: Use complex patterns for sophisticated
alert("Please fill in the " + field.name + " field"); validation (e.g., strong password checks).
return false;  HTML5 Form Validation: Leverage built-in HTML5 attributes for
} basic validation (e.g., required, pattern).
return true;
} Example: Validating a Registration Form

 Data Types: Verify correct input formats (e.g., email, phone HTML
number, date).
<form id="registrationForm">
JavaScript <label for="name">Name:</label>
<input type="text" id="name" name="name" required>
function validateEmail(email) { <br>
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; <label for="email">Email:</label>
return emailRegex.test(email); <input type="email" id="email" name="email" required>
} <br>
<button type="submit">Submit</button>
 Data Ranges: Check values within specified limits (e.g., age, </form>
quantity).
JavaScript Example:

const form = document.getElementById("registrationForm"); JavaScript


form.addEventListener("submit", (event) => {
event.preventDefault(); function openNewWindow() {
const newWindow = window.open("https://www.example.com", "_blank",
const name = document.getElementById("name").value; "width=400,height=300");
const email = document.getElementById("email").value; if (newWindow) {
newWindow.focus();
if (!validateRequired(name) || !validateRequired(email) || }
!validateEmail(email)) { }
// Handle validation errors
return; This code opens a new window with the URL https://www.example.com,
} with a width of 400 pixels and a height of 300 pixels. The _blank target
ensures it opens in a new tab or window.
// Form is valid, submit it or perform other actions
console.log("Form submitted successfully"); Window Features
});
You can customize the appearance of the new window using the features
parameter. Common features include:
Opening a New Window in JavaScript
 width=px: Sets the width of the window in pixels.
Using the window.open() Method  height=px: Sets the height of the window in pixels.
 left=px: Sets the left position of the window in pixels.
JavaScript provides the window.open() method to create new browser  top=px: Sets the top position of the window in pixels.
windows or tabs.  toolbar=yes/no: Shows or hides the toolbar.
 location=yes/no: Shows or hides the address bar.
Syntax:  menubar=yes/no: Shows or hides the menu bar.
 status=yes/no: Shows or hides the status bar.
JavaScript  resizable=yes/no: Allows or prevents resizing the window.

window.open(url, name, features); Example:

 url: The URL of the page to be loaded in the new window. JavaScript
 name: The name of the new window. If omitted or an empty string,
a new tab is opened. window.open("https://www.example.com", "_blank",
 features: A string specifying window features like size, position, "width=600,height=400,toolbar=no,menubar=no,location=no");
toolbars, etc.
Messages and Confirmations in JavaScript console.log("Username:", username);
} else {
JavaScript provides built-in functions to display various types of messages console.log("User canceled the prompt");
and confirmations to the user. These functions are primarily used for simple }
interactions and alerts.
Important Considerations
Alert Messages
 Browser Compatibility: The appearance and behavior of these
The alert() function displays a simple popup message with an "OK" button. message boxes can vary across browsers.
 User Experience: Overuse of these functions can be annoying to
JavaScript users. Use them judiciously.
 Alternatives: For more complex interactions, consider using custom
alert("This is an alert message"); dialogs or modal windows built with HTML, CSS, and JavaScript.

Confirmation Messages Example: Confirming Form Submission

The confirm() function displays a popup message with "OK" and "Cancel" HTML
buttons. It returns a boolean value indicating whether the user clicked "OK"
or "Cancel". <form id="myForm">
<button type="submit">Submit</button>
JavaScript </form>
JavaScript
let confirmed = confirm("Are you sure you want to proceed?");
if (confirmed) { const form = document.getElementById('myForm');
// User clicked OK form.addEventListener('submit', (event) => {
} else { event.preventDefault();
// User clicked Cancel const confirmed = confirm("Are you sure you want to submit the form?");
} if (confirmed) {
// Submit the form
Prompt Messages form.submit();
}
The prompt() function displays a popup message with an input field, });
allowing the user to enter text. It returns the user's input as a string.
The Status Bar: A Brief Overview
JavaScript
A status bar is a graphical control element typically found at the
let username = prompt("Enter your username:"); bottom of a window. It serves as an information area, displaying details
if (username) { about the current state of the window or application.
Common Uses  Responsiveness: Update the status bar in real-time to reflect
changes in the application state.
 Displaying application or system status: For example, battery  Accessibility: Ensure the information is accessible to users with
level, time, network connectivity, or loading progress. disabilities.
 Providing contextual information: Such as file path, selected item
details, or cursor position. Rollover Buttons in DHTML
 Indicating user actions: Showing progress bars, confirmation
messages, or error notifications. Rollover buttons are interactive elements that change appearance when the
 Offering additional controls: Like zoom levels, page numbers, or mouse cursor hovers over them. They are a classic example of DHTML
application settings. (Dynamic HTML) using JavaScript to enhance user experience.

Examples of Status Bars Basic Implementation

 Web browsers: Displaying URL, loading progress, and connection Here's a simple example using image swapping:
status.
 Word processors: Showing page number, word count, and HTML:
document statistics.
 Image editors: Indicating image dimensions, color information, and HTML
zoom level.
 Operating systems: Displaying time, date, battery level, network <img src="button_normal.png" id="myButton" alt="Button"
connectivity, and system notifications. onmouseover="this.src='button_hover.png'"
onmouseout="this.src='button_normal.png'">
Components of a Status Bar
Explanation:
 Text labels: Display static or dynamic information.
 Progress bars: Indicate the progress of tasks.  Two images are used: button_normal.png for the normal state and
 Icons: Represent specific states or actions. button_hover.png for the hover state.
 Clickable areas: Trigger additional actions or display more  The onmouseover and onmouseout attributes trigger JavaScript
information. functions when the mouse enters and leaves the image, respectively.
 The functions change the src attribute of the image to display the
Design Considerations appropriate image.

 Clarity and conciseness: Display essential information without Using CSS for Styling
cluttering the space.
 Consistency: Maintain a consistent appearance and behavior across For more control over the appearance, you can use CSS to define different
different parts of the application. styles for the normal and hover states:
HTML:  JavaScript Libraries: Use frameworks like jQuery for simplified
event handling and animations.
HTML  Accessibility: Ensure buttons are accessible to users with
disabilities (e.g., using keyboard navigation).
<button id="myButton">Hover Me</button>
Example with CSS Transitions
CSS:
HTML
#myButton {
background-color: #f0f0f0; <button id="myButton">Hover Me</button>
border: 1px solid #ccc;
padding: 10px 20px;
cursor: pointer; CSS
}
#myButton {
#myButton:hover { background-color: #f0f0f0;
background-color: #e0e0e0; border: 1px solid #ccc;
} padding: 10px 20px;
cursor: pointer;
JavaScript: transition: background-color 0.3s ease;
}
JavaScript
#myButton:hover {
// No JavaScript required in this case background-color: #e0e0e0;
}
Explanation:
Moving Images with JavaScript
 The button element is styled with CSS for its normal appearance.
 The :hover pseudo-class is used to define the style when the mouse Understanding the Basics
hovers over the button.
To move an image using JavaScript, we typically manipulate its CSS left
Advanced Techniques and top properties. These properties determine the image's position relative
to its parent element.
 Image Sprites: Combine multiple images into a single image to
improve performance. Basic Example
 CSS Transitions: Create smooth visual transitions between states
using CSS transitions. HTML
<img id="myImage" src="image.jpg" style="position: absolute;">  Animation: For smoother movement, consider using CSS
JavaScript transitions or animations.
 Performance: Be mindful of performance when moving many
function moveImage() { elements or creating complex animations.
const image = document.getElementById('myImage');
let left = parseInt(image.style.left) || 0; Advanced Techniques
left += 10; // Adjust the movement distance as needed
image.style.left = left + 'px';  CSS Transitions and Animations: Create smoother and more
} complex movements.
 RequestAnimationFrame: For better performance in animations.
// Call the function to start moving the image  Event Listeners: Allow user interaction to control the movement
setInterval(moveImage, 10); // Adjust the interval time as needed (e.g., keyboard, mouse).
 Collision Detection: Implement logic to detect collisions with other
Explanation: elements.
 Game Development Libraries: Use specialized libraries for
1. HTML: We create an image element with an ID for easy reference creating complex game-like animations.
and set its position to absolute to allow precise positioning.
2. JavaScript: Example using CSS Transitions:
o We get a reference to the image element using
getElementById. CSS
o We parse the current left position as an integer (or set it to 0
if not set). #myImage {
o We increment the left position by 10 pixels. position: absolute;
o We update the image's left style property with the new transition: left 1s ease;
position. }
o The setInterval function repeatedly calls the moveImage JavaScript
function every 10 milliseconds, creating the illusion of
movement. function moveImage() {
const image = document.getElementById('myImage');
Key Points: let left = parseInt(image.style.left) || 0;
left += 10;
 Position: Ensure the image has position: absolute or position: image.style.left = left + 'px';
relative for accurate positioning. }
 Increment: Adjust the increment value to control the movement
speed. By using CSS transitions, the image will smoothly move to its new position
 Boundaries: Implement checks to prevent the image from moving without abrupt jumps.
outside the viewport.
Frames in JavaScript: A Historical Perspective HTML

While the concept of frames still exists in JavaScript, their usage is <iframe src="content.html" width="300" height="200"></iframe>
highly discouraged due to several drawbacks.
This code embeds the content of content.html within an <iframe> element,
What are Frames? providing more control over its dimensions and styling.

Frames were a way to divide a web page into multiple sections, each
displaying a different document. They were created using the <frameset>
and <frame> tags in HTML.

Why Frames are Deprecated

 Poor User Experience: Frames can cause navigation and usability


issues, as users often struggle to understand which content belongs
to which frame.
 SEO Issues: Search engines have difficulty indexing content within
frames, negatively impacting website visibility.
 Compatibility Issues: Different browsers handle frames differently,
leading to inconsistent rendering.
 Maintenance Difficulties: Managing multiple frames can become
complex and error-prone.

Alternatives to Frames

Modern web development practices strongly recommend using alternative


approaches:

 HTML5 <iframe>: Offers more control and flexibility than


traditional frames.
 CSS Grid or Flexbox: Create complex layouts without relying on
frames.
 JavaScript Libraries and Frameworks: Provide tools for building
dynamic and interactive web applications.

Example: Using <iframe> instead of Frames

You might also like