HTML
HTML
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.
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:
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.
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., © 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.
HTML
Responsive images:
Example:
HTML
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:
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
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
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
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
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
if...else statements: Execute code based on conditions. Unordered collections of key-value pairs.
JavaScript JavaScript
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: **=
JavaScript JavaScript
let x = true;
let y = false; const numbers = new Array(3, 1, 4, 1, 5, 9);
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.
for loop: There are two primary ways to define functions in 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.
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:
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 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.
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:
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.
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.
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.
Alternatives to Frames