0% found this document useful (0 votes)
8 views120 pages

Module 4 FOC

The document explains the process of accessing a website, detailing the roles of web browsers, web servers, and the request-response cycle. It covers key concepts such as HTTP and HTTPS protocols, DNS, URLs, and various types of web hosting. Additionally, it introduces HTML, its structure, and differences between HTML and XHTML.

Uploaded by

shilu000001
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)
8 views120 pages

Module 4 FOC

The document explains the process of accessing a website, detailing the roles of web browsers, web servers, and the request-response cycle. It covers key concepts such as HTTP and HTTPS protocols, DNS, URLs, and various types of web hosting. Additionally, it introduces HTML, its structure, and differences between HTML and XHTML.

Uploaded by

shilu000001
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/ 120

text

Your paragraph text yt fb in ln wp


Module-4
Imagine you want to visit a website like YouTube or Google. When you type the
web address URL and press Enter, your browser communicates with a web
server to fetch the webpage and display it for you.

Step 1: User Requests a Web Page


When you type a website address (e.g., www.google.com) in a web browser
Chrome, Firefox, Edge, etc.), the browser needs to find where that website is
stored.

It sends a request to a web server, which is a special computer that stores


and manages websites.

Example:

You enter www.example.com in your browser.

Your browser asks, "Where can I find this webpage?"


Your browser asks, "Where can I find this webpage?"

The request is sent to the correct web server that hosts the website.

Step 2: The Web Server Processes the Request


The web server receives the request and looks for the required website files.

Websites are made up of different files:

HTML HyperText Markup Language)  Defines the structure of the


webpage (like a skeleton).

CSS Cascading Style Sheets)  Adds design (colors, fonts, layout).

JavaScript  Makes the page interactive (buttons, animations, forms).

The web server sends these files back to the browser.

Step 3: The Browser Renders the Web Page


The browser takes the received files and starts building the webpage:

Module-4 1
 Reads the HTML  Adds headings, images, and text.

 Applies the CSS  Colors, layouts, and fonts are added.

 Runs JavaScript  Enables interactivity like buttons and animations.

Finally, the webpage appears on your screen, ready for you to use!

1. Web Server
A web server is a system that stores and delivers web pages when users request
them through a browser. It acts as an intermediary between the user and the
websiteʼs files. Hereʼs how it works:

When a user enters a website URL in a browser, the browser sends a request
to the web server.

The web server processes the request and retrieves the necessary files (such
as HTML, CSS, JavaScript, images, and videos).

It then sends these files back to the browser, which interprets and displays the
web page to the user.

Web servers also handle multiple requests from different users at the same
web page to the user.

Web servers also handle multiple requests from different users at the same
time, ensuring that websites remain accessible.

Some commonly used web servers include Apache, Nginx, Microsoft IIS, and
LiteSpeed.

2. Web Browser
A web browser is software that allows users to access and interact with websites.
It acts as a bridge between the user and the web server. The main functions of a
web browser include:

Sending HTTP/HTTPS requests to web servers to fetch website data.

Receiving and interpreting files such as HTML (for structure), CSS (for styling),
and JavaScript (for functionality).

Displaying web pages in a readable format for users.

Supporting user interaction with web applications, such as clicking buttons,


filling forms, and playing videos.

Module-4 2
Some popular web browsers include Google Chrome, Mozilla Firefox,
Microsoft Edge, and Safari.

3. HTTP (Hypertext Transfer Protocol)


HTTP is the protocol that allows communication between a web browser and a
web server. It defines how data is transferred over the web. Key points about
HTTP

It follows a request-response model, meaning the browser requests data and


the server responds with the requested content.

It enables the transfer of website elements like text, images, videos, and
interactive features.

HTTP is not secure, as it does not encrypt data. This means that if sensitive
information (like passwords or credit card details) is transmitted using HTTP,
hackers can intercept and read it.

Common HTTP request methods include:

GET  Requests data from the server (e.g., loading a webpage).


GET  Requests data from the server (e.g., loading a webpage).

POST  Sends data to the server (e.g., submitting a form).

4. HTTPS (Hypertext Transfer Protocol Secure)


HTTPS is a secure version of HTTP that encrypts data using SSL Secure Sockets
Layer) or TLS Transport Layer Security). This ensures that data exchanged
between the browser and the server is protected. Key features of HTTPS

Encryption Data is encrypted before transmission, preventing hackers from


intercepting sensitive information.

Authentication Ensures that the website being accessed is legitimate and not
a fake version created by attackers.

Data Integrity Ensures that data is not modified or tampered with during
transmission.

Websites using HTTPS have a padlock icon in the address bar, indicating a
secure connection.

Module-4 3
HTTPS is widely used for online banking, e-commerce, and login pages to
protect user information.

Websites without HTTPS are marked as "Not Secure" by modern browsers,


discouraging users from entering sensitive data.

Client-Server Architecture in Web Applications

Web applications follow a client-server architecture, meaning


two main components—client (front-end) and server (back-end)
—work together to provide users with web services. They
communicate using the request-response cycle over the
HTTP/HTTPS protocol.

1. Client (Front-End)
What is a Client?
The client is the userʼs web browser Chrome, Firefox, Edge, Safari, etc.).
The client is the userʼs web browser Chrome, Firefox, Edge, Safari, etc.).

It is responsible for requesting web pages and displaying them on the


screen.

It interprets and renders the content sent by the web server.

What Makes Up the Front-End?


A websiteʼs front-end is built using three core technologies:

 HTML Hypertext Markup Language)  Defines the structure of the webpage


(e.g., headings, paragraphs, images, buttons).

 CSS Cascading Style Sheets)  Adds styling like colors, fonts, and layouts.

 JavaScript  Enables interactivity (e.g., animations, form validation, and


dynamic content loading).

Example:
When you enter www.example.com in your browser, it sends a request to the
server to retrieve the webpage.

Module-4 4
The server responds with HTML, CSS, and JavaScript files, which the
browser processes and displays as a webpage.

2. Server (Back-End)
What is a Server?
The server is a powerful computer that stores and delivers website content.

It processes requests, retrieves necessary files or data, and sends responses


to the client.

Components of the Back-End:


 Web Server  Handles requests and delivers website files (e.g., Apache,
Nginx).

 Application Logic  The brain of the website that processes user actions,
manages sessions, and enforces business rules.

 Database  Stores and manages website data (user details, product


 Database  Stores and manages website data (user details, product
information, messages, etc.).

Example:
When you log into a website, your username and password are sent to the
server.

The server checks the credentials in the database and sends a response.

If correct, it sends a dashboard page; otherwise, it shows an error message.

3. Database
What is a Database?
A database is a system used to store and manage website data securely.

It contains structured information, such as user accounts, product details,


and messages.

Module-4 5
Types of Databases:
 SQL Databases Structured Query Language)

Example: MySQL, PostgreSQL

Stores data in tables with predefined relationships.

Best for structured data like e-commerce products, orders, and users.

 NoSQL Databases

Example: MongoDB, Firebase

Stores data in flexible formats (e.g., JSON, key-value pairs).

Best for large-scale applications, real-time chat, and social media feeds.

Example:
When you search for a product on an e-commerce website, the database
retrieves matching items based on your query.

4. Request-Response Cycle
4. Request-Response Cycle
How Does the Client Communicate with the Server?
The client and server communicate using a process called the request-response
cycle over HTTP/HTTPS:

Steps of the Request-Response Cycle:


 Client Browser) Sends a Request

The user requests a webpage (e.g., typing www.example.com in a


browser).

If the user submits a form (e.g., login), the browser sends a request with
form data.

 Server Processes the Request

The web server checks if the requested file exists.

Module-4 6
If the request needs data (e.g., user login), the server queries the
database.

 Server Sends a Response

If successful, the server sends HTML, CSS, and JavaScript files or a


message (e.g., "Login successful").

If thereʼs an error, the server sends an error message (e.g., "Invalid


password").

 Client Displays the Response

The browser receives the response and renders the webpage or displays
a message.

Example: Logging into a Website


 You enter your username and password and click "Login."

 The browser sends a POST request with login credentials.

 The server checks the database to see if the credentials are correct.
 The server checks the database to see if the credentials are correct.

 If correct, the server sends a response with your account details.

 The browser displays the "Welcome, John!" message.

Introduction to DNS, URLs, and Web Hosting

1. DNS (Domain Name System)


DNS translates domain names (e.g., google.com) into IP addresses (e.g.,
142.250.190.14.

It acts as the internetʼs phonebook, making it easier for users to access


websites without memorizing numbers.

When a user enters a domain name, the DNS server finds the corresponding
IP address and directs the request to the correct web server.

DNS Process:

 User enters a domain name in the browser.

 The DNS server looks up the domainʼs IP address.

Module-4 7
 The browser connects to the correct web server and loads the website.

2. URL (Uniform Resource Locator)


A URL is the complete web address used to access a webpage.

It consists of different parts:

Structure of a URL

Protocol: Defines how the browser communicates with the server (e.g., http://,
https://).

Domain Name: Identifies the website (e.g., www.example.com).

Path: Specifies the exact resource or page (e.g., /contact).

Example URL Breakdown:

https://www.example.com/products/item123

https://  Secure protocol HTTPS.

www.example.com  Domain name.

/products/item123  Specific webpage location.


www.example.com  Domain name.

/products/item123  Specific webpage location.

3. Web Hosting
Web hosting is a service that stores website files and makes them accessible
online.

Websites are stored on web servers managed by hosting companies.

The hosting server delivers web pages to users when requested via a browser.

Types of Web Hosting:

 Shared Hosting

Multiple websites share a single server.

Low-cost and easy to use.

Performance may be affected if traffic increases.

Suitable for small websites and personal blogs.

Module-4 8
 VPS Virtual Private Server) Hosting

A single server is divided into multiple virtual machines.

Provides better performance and control than shared hosting.

More expensive but suitable for medium-sized businesses and growing


websites.

 Dedicated Hosting

A single website gets an entire server to itself.

Offers high performance, full control, and enhanced security.

Expensive and requires technical expertise.

Ideal for large businesses and high-traffic websites.

 Cloud Hosting

Uses multiple servers to handle website traffic dynamically.

Highly scalable and reliable.

Efficiently manages traffic spikes.


Highly scalable and reliable.

Efficiently manages traffic spikes.

Best suited for large-scale applications like Google and Netflix.

What is HTML? Basics of HTML Structure

1. What is HTML?
HTML HyperText Markup Language) is the standard language for creating
web pages.

It structures the content of a webpage using elements like headings,


paragraphs, images, and links.

HTML is not a programming language; it is a markup language used to define


the layout of a webpage.

2. Basic Features of HTML


Uses tags to structure content.

Module-4 9
Works alongside CSS Cascading Style Sheets) for styling and JavaScript for
interactivity.

Can include text, images, videos, tables, and forms.

HTML files have a .html extension.

3. Basic HTML Structure


An HTML document follows a specific structure with important elements:

!DOCTYPE html>
<html>
<head>
<title>My First Webpage</title>
</head>
<body>
<h1Welcome to My Website</h1
<p>This is a paragraph of text.</p>
<a href="https://www.example.com"Click Here</a>
</body>
<a href="https://www.example.com"Click Here</a>
</body>
</html>

Explanation of Structure:

!DOCTYPE html>  Declares the document as an HTML5 file.

<html>  The root element of an HTML document.

<head>  Contains metadata (title, styles, scripts).

<title>  Sets the title of the webpage (shown in the browser tab).

<body>  Contains the visible content of the webpage.

<h1  Defines the main heading of the page.

<p>  Represents a paragraph of text.

<a href="URL">  Creates a hyperlink to another webpage.

4. Common HTML Tags

Module-4 10
Headings: <h1 to <h6 for different heading sizes.

Paragraphs: <p> for text content.

Links: <a href="URL"> for clickable links.

Images: <img src="image.jpg" alt="Description"> for displaying images.

Lists: <ul> (unordered list), <ol> (ordered list), and <li> (list items).

Tables: <table> , <tr> (row), <td> (cell) for tabular data.

Forms: <form> , <input> , <button> for user inputs.

Difference Between HTML and XHTML


HTML HyperText Markup Language) and XHTML Extensible HyperText Markup
Language) are both markup languages used for structuring web pages. However,
XHTML is a stricter and more structured version of HTML.

1. Basic Differences
HTML HyperText Markup XHTML Extensible HyperText
Feature
Language) Markup Language)
HTML HyperText Markup XHTML Extensible HyperText
Feature
Language) Markup Language)

Standard language for A stricter version of HTML that


Definition
structuring web pages. follows XML rules.

More flexible, allows errors in


Syntax Must follow strict syntax rules.
code.

Some tags can remain All tags must be properly closed


Tag Closing
unclosed (e.g., <p> , <li> ). (e.g., <p></p> ).

Tags and attributes are case-


Tags and attributes must be in
Lowercase/Uppercase insensitive ( TITLE and
lowercase ( <title> only).
<title> work the same).

Attributes can be written Attributes must be enclosed in


Attribute Quotation
without quotes ( width=50 ). double quotes ( width="50" ).

Some attributes can be


All attributes must have a value
Attribute Values written without values
( checked="checked" ).
( checked ).

Browsers can tolerate minor Browsers require well-formed


Parsing Rules
errors in HTML. code without errors.

Module-4 11
Requires a strict DOCTYPE
Doctype Declaration !DOCTYPE html> (in HTML5 declaration, such as !DOCTYPE
XHTML 1.0 Strict> .

Can use empty tags without


Must use self-closing syntax for
Use of Empty Tags self-closing (e.g., <br> ,
empty tags ( <br /> , <img /> ).
<img> ).

2. Example Code Comparison


HTML Example:

!DOCTYPE html>
<html>
<head>
<title>HTML Example</title>
</head>
<body>
<h1Welcome</h1
<p>This is an HTML page.</p>
<img src="image.jpg">
<p>This is an HTML page.</p>
<img src="image.jpg">
</body>
</html>

XHTML Example:

!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w


3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>XHTML Example</title>
</head>
<body>
<h1Welcome</h1
<p>This is an XHTML page.</p>
<img src="image.jpg" alt="Image" />

Module-4 12
</body>
</html>

HTML Elements Overview


HTML elements define the structure and content of a webpage. Below are the
most commonly used HTML elements:

1. Headings ( <h1> to <h6> )


Headings are used to define titles and subtitles.

<h1 is the largest and <h6 is the smallest.

Headings help structure content and improve SEO.

Example:

<h1Main Title</h1
<h2Subheading</h2
<h3Section Title</h3
<h2Subheading</h2
<h3Section Title</h3

2. Paragraphs ( <p> )
The <p> tag is used for defining paragraphs.

Browsers automatically add space before and after a paragraph.

Example:

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

3. Lists
There are two main types of lists in HTML

a) Ordered List ( <ol> )


Displays items in a numbered sequence.

Module-4 13
Example:

<ol>
<li>Item 1/li>
<li>Item 2/li>
<li>Item 3/li>
</ol>

b) Unordered List ( <ul> )


Displays items with bullet points.

Example:

<ul>
<li>Apple</li>
<li>Banana</li>
<li>Cherry</li>
</ul>
</ul>

4. Links ( <a> )
Links allow navigation between pages.

The href attribute specifies the destination URL.

Example:

<a href="https://www.example.com"Visit Example</a>

5. Tables ( <table> )
Tables organize data in rows and columns.
Example:

<table border="1">
<tr>

Module-4 14
<th>Name</th>
<th>Age</th>
</tr>
<tr>
<td>John</td>
<td>25/td>
</tr>
<tr>
<td>Jane</td>
<td>22/td>
</tr>
</table>

<table> defines a table.

<tr> defines a row.

<th> defines a table header.

<td> defines a table cell.


<td> defines a table cell.

6. Forms ( <form> )
Forms collect user input and send it to a server.

Example:

<form action="submit.php" method="POST">


<label for="name"Name:</label>
<input type="text" id="name" name="name" required>

<label for="email"Email:</label>
<input type="email" id="email" name="email" required>

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


</form>

<input> defines input fields (text, email, password, etc.).

Module-4 15
<label> associates text with form elements.

<submit> button sends data to the server.

7. Images ( <img> )
The <img> tag displays images.

The src attribute specifies the image location.

The alt attribute provides alternative text for accessibility.

Example:

<img src="image.jpg" alt="Description of image">

8. Div and Span ( <div> , <span> )


<div> groups block elements together.

<span> is used for styling small parts of text.


<span> is used for styling small parts of text.

Example:

<div>
<h2Section Title</h2
<p>This is a paragraph inside a div.</p>
</div>

<p>This is a <span style="color: red;">highlighted</span> word.</p>

9. Buttons ( <button> )
The <button> tag creates clickable buttons.
Example:

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

Module-4 16
10. Horizontal Line ( <hr> ) & Line Break ( <br> )
<hr> adds a horizontal line.

<br> adds a line break.

Example:

<p>First line.<br>Second line.</p>


<hr>

Attributes, Semantic HTML, and Accessibility in HTML

1. HTML Attributes
Attributes provide additional information about HTML elements. They are added
inside the opening tag and usually follow the attribute="value" format.

Common HTML Attributes:


id  Assigns a unique identifier to an element.
Common HTML Attributes:
id  Assigns a unique identifier to an element.

class  Groups elements for styling with CSS.

href  Specifies a linkʼs destination in <a> tags.

src  Defines the source URL for images and media.

alt  Provides alternative text for images (important for accessibility).

title  Displays additional information when hovering over an element.

style  Adds inline CSS styling.

Example:

<a href="https://www.example.com" title="Go to Example"Visit Example</a


>
<img src="image.jpg" alt="A beautiful sunset">
<p id="intro" class="text-bold"This is a paragraph.</p>

Module-4 17
2. Semantic HTML
Semantic HTML refers to using HTML elements that convey meaning about their
content. It improves accessibility, SEO, and code readability.

Examples of Semantic Tags:


<header>  Defines the page header.

<nav>  Represents a navigation menu.

<section>  Groups related content.

<article>  Represents self-contained content.

<aside>  Contains sidebar content.

<footer>  Defines the page footer.

Example:

<header>
<h1Website Title</h1
<header>
<h1Website Title</h1
</header>
<nav>
<ul>
<li><a href="home.html"Home</a></li>
<li><a href="about.html"About</a></li>
</ul>
</nav>
<section>
<article>
<h2Blog Post Title</h2
<p>This is an example of a blog post.</p>
</article>
</section>
<footer>
<p>© 2025 My Website</p>
</footer>

Module-4 18
3. Web Accessibility (A11Y)
Web accessibility ensures that websites are usable by everyone, including people
with disabilities.

Best Practices for Accessibility:


✅ Use alt attributes for images ( ).
alt="description"

 Ensure high contrast between text and background.


 Provide keyboard navigation support.
 Use semantic HTML to improve screen reader support.
 Add ARIA Accessible Rich Internet Applications) attributes for better
interaction.

 Use elements for form inputs.


label

Example (Accessible Form):

<form>
<label for="name"Name:</label>
<form>
<label for="name"Name:</label>
<input type="text" id="name" name="name" aria-required="true">

<button type="submit"Submit</button>
</form>

Forms and Input Fields in HTML


Forms are essential for collecting user input on a website. They allow users to
enter data, which can be sent to a server for processing.

1. Form Structure ( <form> )


The <form> element defines an HTML form for user input.

The action attribute specifies where to send form data.

The method attribute defines how data is sent ( GET or POST ).

Module-4 19
Example:

<form action="submit.php" method="POST">


! Input fields go here ⟶
</form>

2. Input Fields ( <input> )


The <input> tag is used for various types of input fields.

a) Text Input
Used for short text input like names or usernames.

<label for="name"Name:</label>
<input type="text" id="name" name="name" required>

b) Email Input
Accepts email addresses with built-in validation.
b) Email Input
Accepts email addresses with built-in validation.

<label for="email"Email:</label>
<input type="email" id="email" name="email" required>

c) Password Input
Masks characters for secure password entry.

<label for="password"Password:</label>
<input type="password" id="password" name="password" required>

d) Number Input
Allows numeric values only.

<label for="age"Age:</label>

Module-4 20
<input type="number" id="age" name="age" min="1" max="100">

e) Radio Buttons
Used for selecting one option from multiple choices.

<label>Gender:</label>
<input type="radio" id="male" name="gender" value="male">
<label for="male"Male</label>

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


<label for="female"Female</label>

f) Checkboxes
Used for selecting multiple options.

<label>Hobbies:</label>
<input type="checkbox" id="sports" name="hobby" value="sports">
<label>Hobbies:</label>
<input type="checkbox" id="sports" name="hobby" value="sports">
<label for="sports"Sports</label>

<input type="checkbox" id="music" name="hobby" value="music">


<label for="music"Music</label>

g) Dropdown (Select Menu)


Allows users to pick one option from a dropdown list.

<label for="country"Country:</label>
<select id="country" name="country">
<option value="usa"USA/option>
<option value="uk"UK/option>
<option value="india"India</option>
</select>

h) Textarea

Module-4 21
Used for multi-line text input.

<label for="message"Message:</label>
<textarea id="message" name="message" rows="4" cols="30"></textarea>

i) File Upload
Allows users to upload files.

<label for="file"Upload File:</label>


<input type="file" id="file" name="file">

j) Date Picker
Allows users to select a date.

<label for="dob"Date of Birth:</label>


<input type="date" id="dob" name="dob">
<input type="date" id="dob" name="dob">

k) Submit Button
Sends form data to the server.

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

l) Reset Button
Clears all input fields.

<input type="reset" value="Reset">

3. Advanced Form Elements

a) Placeholder
Displays hint text inside an input field.

Module-4 22
<input type="text" placeholder="Enter your name">

b) Disabled Input
Prevents users from editing the input field.

<input type="text" value="Read-only text" disabled>

c) Readonly Input
Displays text that cannot be modified but can be selected.

<input type="text" value="Fixed Value" readonly>

d) Required Attribute
Ensures the field must be filled before submitting the form.

<input type="text" required>


<input type="text" required>

4. Form Example (Complete Form with Input Fields)

<form action="submit.php" method="POST">


<label for="name"Name:</label>
<input type="text" id="name" name="name" required><br><br>

<label for="email"Email:</label>
<input type="email" id="email" name="email" required><br><br>

<label for="password"Password:</label>
<input type="password" id="password" name="password" required><br>
<br>

<label>Gender:</label>

Module-4 23
<input type="radio" id="male" name="gender" value="male">
<label for="male"Male</label>

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


<label for="female"Female</label><br><br>

<label for="country"Country:</label>
<select id="country" name="country">
<option value="usa"USA/option>
<option value="uk"UK/option>
<option value="india"India</option>
</select><br><br>

<label for="message"Message:</label>
<textarea id="message" name="message" rows="4"></textarea><br><br>

<label for="dob"Date of Birth:</label>


<input type="date" id="dob" name="dob"><br><br>
<input type="date" id="dob" name="dob"><br><br>

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


<input type="reset" value="Reset">
</form>

Introduction to CSS and Its Role in Web Design


CSS Cascading Style Sheets) is a stylesheet language used to control the
presentation and layout of web pages. It allows developers to separate the
content HTML from the design, ensuring consistency and flexibility in web
design.

1. What is CSS?
CSS defines how HTML elements should be displayed on a webpage. It controls
aspects like:

Colors

Module-4 24
Fonts

Layouts

Spacing

Animations

Example:

!DOCTYPE html>
<html>
<head>
<style>
h1 
color: blue;
font-size: 24px;
}
</style>
</head>
<body>
</head>
<body>
<h1Hello, CSS!/h1
</body>
</html>

In this example, the <h1 element is styled with blue color and a font size of 24px.

2. Role of CSS in Web Design


CSS plays a crucial role in web design by:

✅ Enhancing Visual Appearance  Makes websites attractive with colors, fonts,


and animations.

 Improving User Experience UX  Ensures readability, responsiveness, and


accessibility.

 Providing Consistency  Allows consistent styling across multiple pages.


 Enabling Responsive Design  Adapts web pages to different screen sizes
(mobile, tablet, desktop).

Module-4 25
✅ Reducing Code Duplication  Centralized stylesheets apply styles to multiple
elements, reducing redundancy.

3. Types of CSS

a) Inline CSS
Applied directly inside an HTML element using the style attribute.

<p style="color: red;"This is a red paragraph.</p>

' Pros Quick to apply.


' Cons Difficult to manage for large projects.
b) Internal CSS
Defined inside the <style> tag within the HTML <head> .

<head>
<style>
<head>
<style>
p{
color: green;
font-size: 16px;
}
</style>
</head>

' Pros Useful for single-page styling.


' Cons Not reusable across multiple pages.
c) External CSS
Stored in a separate .css file and linked to HTML using <link> .

<head>
<link rel="stylesheet" href="styles.css">

Module-4 26
</head>

' Pros Best for large projects; reusable and scalable.


' Cons Requires an external file.
4. Basic CSS Syntax
CSS rules consist of a selector and declaration block.

selector {
property: value;
}

Example:

h1 
color: blue;
font-size: 24px;
}
font-size: 24px;
}

5. Common CSS Properties


Property Description Example
color Changes text color color: red;

background-color Sets background color background-color: yellow;

font-size Controls text size font-size: 20px;

text-align Aligns text text-align: center;

margin Adds space outside an element margin: 10px;

padding Adds space inside an element padding: 5px;

border Adds a border border: 2px solid black;

6. CSS in Responsive Design

Module-4 27
CSS makes websites responsive using media queries, allowing layouts to adjust
for different devices.

@media (max-width: 600px) {


body {
background-color: lightblue;
}
}

º This changes the background color when the screen width is less than
600px.

Types of CSS: Inline, Internal, and External


CSS Cascading Style Sheets) can be applied in three ways: Inline CSS, Internal
CSS, and External CSS. Each method has its advantages and use cases.

1. Inline CSS
1. Inline CSS
✅ Applied directly within an HTML element using the style attribute.

 Used for quick, one-time styling of a specific element.


Example:

<p style="color: red; font-size: 18px;"This is a red paragraph.</p>

Advantages:
✔ Quick and easy for small changes.
˜ Does not require a separate CSS file.
Disadvantages:

✖ Not reusable for multiple elements.


™ Makes the HTML code messy and difficult to maintain.
2. Internal CSS

Module-4 28
✅ Defined inside a tag within the
<style> <head> section of an HTML document.

 Useful for applying styles to a single webpage.


Example:

!DOCTYPE html>
<html>
<head>
<style>
h1 
color: blue;
text-align: center;
}
p{
font-size: 16px;
color: green;
}
</style>
</head>
</style>
</head>
<body>
<h1Welcome to CSS/h1
<p>This paragraph is styled using internal CSS.</p>
</body>
</html>

Advantages:

✔ Keeps styles separate from content for better readability.


˜ Useful when designing a single-page website.
Disadvantages:

✖ Styles are not reusable across multiple pages.


™ Larger files can make the HTML document look cluttered.
3. External CSS

Module-4 29
✅ Stored in a separate file and linked to the HTML file using the tag.
.css <link>

 Ideal for large websites as it keeps the design consistent across multiple
pages.

Example:
HTML File ( index.html )

!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1Welcome to External CSS/h1
<p>This paragraph is styled using an external CSS file.</p>
</body>
</html>

CSS File ( styles.css )


CSS File ( styles.css )

h1 
color: blue;
text-align: center;
}

p{
font-size: 18px;
color: green;
}

Advantages:

✔ Keeps HTML and CSS separate, making code cleaner and easier to maintain.
˜ Allows for consistent styling across multiple pages.
˜ Improves website performance as styles are cached by the browser.

Module-4 30
Disadvantages:

✖ Requires an additional HTTP request to fetch the CSS file.


™ If the CSS file is missing or incorrect, the webpage may not display properly.
Comparison Table
Type of CSS Definition Use Case Advantages Disadvantages

Applied directly Hard to


Quick fixes &
Inline CSS within an HTML Easy to apply maintain, not
small styling
element reusable

Defined inside Keeps styles Not reusable


Single-page
Internal CSS <style> in separate from across multiple
websites
<head> content pages

Stored in a
Reusable, keeps Requires an
External CSS separate .css Large websites
HTML clean additional file
file
Selectors, Properties, and Values in CSS
CSS Cascading Style Sheets) is used to style HTML elements by selecting them
and applying properties with specific values.

1. Selectors
A CSS Selector is used to target HTML elements that need to be styled.

Types of Selectors:
Å Element Selector  Selects HTML elements by tag name.
p{
color: blue;
}

Styles all <p> elements with blue text.)

Module-4 31
Æ Class Selector  Selects elements with a specific class ( . ).

.highlight {
background-color: yellow;
}

Styles all elements with class="highlight" .)

Ç ID Selector  Selects an element with a specific ID  # ).

#header {
font-size: 24px;
}

Styles the element with id="header" .)

È Group Selector  Selects multiple elements at once ( , ).

h1, h2, p {
text-align: center;
h1, h2, p {
text-align: center;
}

Styles all <h1 , <h2 , and <p> elements.)

É Descendant Selector  Selects elements inside another element (space).


div p {
color: red;
}

Styles only <p> elements inside a <div> .)


Ê Pseudo-Class Selector  Styles elements in a specific state ( : ).

a:hover {
color: green;
}

Module-4 32
Changes link color to green when hovered.)

2. Properties
A CSS Property defines what aspect of an element to style.

Examples:

color  Text color

font-size  Size of the text

background-color  Background color

margin  Space outside an element

padding  Space inside an element

border  Border around an element

3. Values
A CSS Value is assigned to a property to specify its effect.
3. Values
A CSS Value is assigned to a property to specify its effect.

Examples:

p{
color: blue; /* Property: color, Value: blue */
font-size: 20px; /* Property: font-size, Value: 20px */
background-color: yellow; /* Property: background-color, Value: yellow */
}

Example: Combining Selectors, Properties, and Values


CSS File ( style.css )

/* Applying styles to elements */


h1 
color: darkblue;

Module-4 33
font-size: 28px;
}

/* Styling elements with a class */


.highlight {
background-color: lightgray;
padding: 10px;
}

/* Styling an element with an ID */


#main-content {
width: 80%;
margin: auto;
}

HTML File ( index.html )

!DOCTYPE html>
!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1Welcome to CSS/h1
<p id="main-content"This is a paragraph inside the main content area.</p
>
<p class="highlight"This is a highlighted paragraph.</p>
</body>
</html>

Box Model, Flexbox, and Grid Layout in CSS


CSS provides different ways to structure and style elements on a webpage. The
Box Model, Flexbox, and Grid Layout are essential concepts for layout design.

Module-4 34
1. CSS Box Model
The Box Model represents how every HTML element is structured in terms of
spacing and dimensions. It consists of:

' Content  The actual text or image inside the element.


' Padding  Space between content and border.
' Border  The boundary around the element.
' Margin  Space outside the border, separating the element from others.
Example: Box Model in CSS

.box {
width: 200px;
height: 100px;
padding: 10px;
border: 5px solid black;
margin: 20px;
}
margin: 20px;
}

Ë This defines an element with:


✔ Content size  200px  100px
˜ Padding  10px (increases total size)
˜ Border  5px thick
˜ Margin  20px space outside
2. CSS Flexbox (Flexible Box Layout)
Flexbox is used to align and distribute space within a container efficiently, even
when elements have different sizes.

Key Concepts of Flexbox:


' display: flex;  Enables Flexbox on a container.

' flex-direction:  Defines the direction (row or column).

Module-4 35
' justify-content:  Aligns items horizontally (left, center, space-between, etc.).

' align-items:  Aligns items vertically.

' flex-wrap:  Allows items to wrap to the next line if needed.

Example: Flexbox Layout

.container {
display: flex;
flex-direction: row;
justify-content: space-around;
align-items: center;
}

.box {
width: 100px;
height: 100px;
background-color: lightblue;
text-align: center;
background-color: lightblue;
text-align: center;
}

HTML:

<div class="container">
<div class="box"1/div>
<div class="box"2/div>
<div class="box"3/div>
</div>

Ë This creates a row of boxes aligned horizontally with equal spacing.


3. CSS Grid Layout
Grid Layout is a powerful system for designing 2D layouts with rows and columns.

Key Concepts of Grid:

Module-4 36
' display: grid;  Enables Grid on a container.

' grid-template-columns:  Defines column structure.

' grid-template-rows:  Defines row structure.

' gap:  Sets spacing between grid items.


' align-items:  Aligns items within cells.

Example: Grid Layout

.grid-container {
display: grid;
grid-template-columns: 1fr 1fr 1fr; /* 3 equal columns */
grid-gap: 10px;
}

.grid-item {
background-color: lightcoral;
text-align: center;
padding: 20px;
text-align: center;
padding: 20px;
}

HTML:

<div class="grid-container">
<div class="grid-item"1/div>
<div class="grid-item"2/div>
<div class="grid-item"3/div>
<div class="grid-item"4/div>
<div class="grid-item"5/div>
<div class="grid-item"6/div>
</div>

Ë This creates a grid with 3 columns and multiple rows.

Module-4 37
Responsive Design and Media Queries in CSS
Responsive design ensures that web pages look good on all devices, from
desktops to smartphones. Media Queries help apply different styles based on
screen size, resolution, or device type.

1. What is Responsive Design?


Responsive design allows a webpage to adapt to different screen sizes without
breaking the layout. It improves usability and user experience on various devices.

Techniques for Responsive Design:


' Fluid Layouts  Use percentages instead of fixed pixel widths.
' Flexible Images  Use to make images shrink as needed.
max-width: 100%;

' Media Queries  Apply different styles based on screen size.


' Viewport Meta Tag  Ensures proper scaling on mobile devices.
Example: Viewport Meta Tag
Example: Viewport Meta Tag

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

Ë This makes the page scale correctly on all devices.


2. Media Queries in CSS
Media queries allow us to apply different styles depending on the deviceʼs screen
width.

Syntax of a Media Query

@media (condition) {
/* CSS rules */
}

Example: Media Query for Different Screen Sizes

Module-4 38
/* Default styles for larger screens */
.container {
width: 80%;
margin: auto;
}

/* Styles for tablets (screen width up to 768px) */


@media (max-width: 768px) {
.container {
width: 95%;
}
}

/* Styles for mobile phones (screen width up to 480px) */


@media (max-width: 480px) {
.container {
width: 100%;
font-size: 14px;
width: 100%;
font-size: 14px;
}
}

Ë This adjusts the containerʼs width and font size based on screen size.
3. Common Breakpoints for Responsive Design
Breakpoints define at what screen width the design should change. Here are some
standard breakpoints:
✔ Large Screens Desktops, Laptops) → min-width: 1024px

˜ Tablets Portrait Mode) → max-width: 768px

˜ Mobile Devices → max-width: 480px

Example: Responsive Navigation Menu

Module-4 39
/* Default menu for larger screens */
.navbar {
display: flex;
justify-content: space-between;
}

/* Mobile-friendly navigation */
@media (max-width: 600px) {
.navbar {
flex-direction: column;
text-align: center;
}
}

Ë On smaller screens, the menu switches to a column layout.


4. Responsive Images and Typography
4. Responsive Images and Typography
' Use max-width: 100%; to make images scale properly.

' Use rem or em for font sizes instead of px for better scalability.

Example: Responsive Image

img {
max-width: 100%;
height: auto;
}

Ë This ensures images resize without distortion.


5. Flexbox and Grid for Responsive Layouts
' Flexbox  Adjusts layout dynamically based on available space.
' CSS Grid  Creates structured, adaptive grid-based layouts.

Module-4 40
Example: Responsive Grid

.grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 10px;
}

Ë This creates a flexible grid layout that adjusts based on screen width.
Introduction to JavaScript and Its Importance in Web
Development
What is JavaScript?
JavaScript JS is a high-level, interpreted programming language used to make
web pages interactive and dynamic. It runs in the browser and allows developers
to add functionality beyond static HTML and CSS.
to add functionality beyond static HTML and CSS.

1. Why is JavaScript Important?


JavaScript plays a crucial role in modern web development because it enables:

✔ Interactivity  Enables dynamic elements like dropdown menus, sliders, and


animations.

˜ Client-Side Functionality  Runs in the browser, reducing the need for server
requests.
˜ Event Handling  Responds to user actions (clicks, form submissions,
keyboard inputs).

˜ Manipulation of HTML & CSS  Changes web page content and styles
dynamically.
˜ Asynchronous Operations  Supports AJAX and Fetch API for real-time
updates without reloading the page.

Module-4 41
2. Where is JavaScript Used?
' Front-End Development  Adds interactivity (e.g., form validation, animations,
responsive menus).

' Back-End Development  With Node.js, JavaScript can handle server-side


operations.
' Web Applications  Used in frameworks like React, Angular, and Vue.js.
' Mobile App Development  Frameworks like React Native use JavaScript for
mobile apps.

' Game Development  HTML5 Canvas  JavaScript is used for creating


browser-based games.

3. Basic JavaScript Syntax


JavaScript code is written inside <script> tags in an HTML document or in external
.js files.

Example: Adding JavaScript to an HTML Page


Example: Adding JavaScript to an HTML Page

!DOCTYPE html>
<html lang="en">
<head>
<title>JavaScript Example</title>
</head>
<body>
<h1 id="message"Hello, World!/h1
<button onclick="changeText()"Click Me</button>

<script>
function changeText() {
document.getElementById("message").innerHTML  "Hello, JavaScrip
t!";
}
</script>

Module-4 42
</body>
</html>

Ë When the button is clicked, the text changes dynamically using JavaScript.
4. JavaScript Features
✔ Lightweight & Fast  Runs directly in the browser without additional setup.
˜ Cross-Platform  Works on all modern web browsers.
˜ Object-Oriented  Uses objects and prototypes for flexibility.
˜ Asynchronous Programming  Supports promises and async/await for non-
blocking execution.

˜ Wide Community Support  Large ecosystem with libraries and frameworks.


5. JavaScript vs Other Web Technologies
Feature JavaScript HTML CSS
Feature JavaScript HTML CSS

Adds interactivity & Defines webpage Styles the


Purpose
functionality structure webpage

Browser & Server


Runs On Browser Browser
Node.js)

Form validation,
Example Headings, paragraphs Colors, layouts
animations

6. How JavaScript Works in Web Development


' HTML  Provides structure (e.g., buttons, text, forms).
' CSS  Styles the elements (e.g., colors, fonts, layouts).
' JavaScript  Adds functionality (e.g., event handling, animations, form
validation).

7. JavaScript Libraries and Frameworks

Module-4 43
JavaScript has many libraries and frameworks that simplify development:

✔ Front-End Frameworks  React.js, Vue.js, Angular.js


˜ Back-End Runtime  Node.js (server-side JavaScript)
˜ UI Libraries → jQuery, Bootstrap
Variables, Data Types, and Operators in JavaScript
JavaScript is a dynamically typed language, meaning variables do not have a
fixed type and can hold different types of data.

1. Variables in JavaScript
A variable is a container used to store data values.

Declaring Variables
JavaScript provides three ways to declare variables:
˜ var  Global or function-scoped (older method, avoid using).
˜ var  Global or function-scoped (older method, avoid using).

˜ let  Block-scoped (preferred for most cases).


˜ const  Block-scoped and cannot be reassigned (used for constants).

Example

var name = "Alice"; // Old way (avoid)


let age  25; // Preferred for changing values
const PI  3.14; // Constant (cannot be changed)

2. Data Types in JavaScript


JavaScript has two types of data: Primitive and Non-Primitive.

Primitive Data Types (Stores a single value)


˜ Number  Stores integers and floating-point numbers
˜ String  Text values inside quotes ( or )
"Hello" 'World'

Module-4 44
✔ Boolean → ortrue false

˜ Undefined  Variable declared but not assigned a value


˜ Null  Represents an empty or unknown value
˜ BigInt  Large integers beyond limits
Number

˜ Symbol  Unique identifier (used for object properties)


Example

let x  10; // Number


let y = "JavaScript"; // String
let isCodingFun = true; // Boolean
let z; // Undefined
let emptyValue = null; // Null

Non-Primitive (Reference) Data Types (Stores collections of


values)
˜ Object  Collection of key-value pairs
values)
˜ Object  Collection of key-value pairs
˜ Array  Ordered list of values
˜ Function  A block of reusable code
Example

let person = { name: "Alice", age: 25 ; // Object


let numbers = 1, 2, 3, 4, 5; // Array
function greet() { return "Hello!"; } // Function

3. Operators in JavaScript
Operators perform operations on variables and values.

Arithmetic Operators (Perform mathematical calculations)


Operator Description Example ( a  10, b  5 ) Result

Module-4 45
+ Addition a+b 15

- Subtraction a-b 5

* Multiplication a*b 50

/ Division a/b 2

% Modulus Remainder) a%b 0

** Exponentiation a ** 2 100

Example

let sum  10  5; // 15
let product  10  5; // 50

Comparison Operators (Compare two values and return true or


false )

Example ( a  10, b =
Operator Description Result
5)
Example ( a  10, b =
Operator Description Result
5)

== Equal to a == b false

Strictly equal (checks type


=== a === "10" false
too)
! Not equal a ! b true

! Strictly not equal a ! "10" true

> Greater than a>b true

< Less than a<b false

>= Greater than or equal to a >= b true

<= Less than or equal to a <= b false

Example

console.log(10  "10"); // true (loose equality)


console.log(10  "10"); // false (strict equality)
console.log(10  5; // true

Module-4 46
Logical Operators (Combine multiple conditions)

Operator Description Example ( a = true, b = false ) Result


&& AND a && b false

` ` OR
! NOT !a false

Example

let isAdult = true;


let hasID  false;
console.log(isAdult && hasID; // false
console.log(isAdult || hasID; // true
console.log(!isAdult); // false

Assignment Operators (Assign values to variables)


Assignment Operators (Assign values to variables)
Operator Example Equivalent To
= x5 x5

+= x  5 x=x5

-= x  5 x=x5

*= x * 5 x=x*5

/= x / 5 x=x/5

Example

let num  10;


num  5; // num = num  5  15
num * 2; // num = num * 2  30

Ternary Operator (Shorthand for if-else)


The ternary operator ? provides a shorter way to write if-else statements.

Module-4 47
Syntax

condition ? "True Output" : "False Output";

Example

let age  18;


let result = (age  18 ? "Adult" : "Minor";
console.log(result); // Output: Adult

Functions and Events in JavaScript


JavaScript functions allow us to execute reusable blocks of code, while events
enable interaction between users and web elements.

1. Functions in JavaScript
A function is a reusable block of code designed to perform a specific task.
1. Functions in JavaScript
A function is a reusable block of code designed to perform a specific task.
Functions help reduce code duplication and improve readability.

Declaring a Function

Syntax

function functionName(parameters) {
// Code to execute
return value; // Optional
}

Example: Basic Function

function greet(name) {
return "Hello, " + name + "!";

Module-4 48
}
console.log(greet("Alice")); // Output: Hello, Alice!

Types of Functions
Å Function with Parameters and Return Value
function add(a, b) {
return a + b;
}
console.log(add(5, 3)); // Output: 8

Æ Function Without Parameters


function showMessage() {
console.log("Welcome to JavaScript!");
}
showMessage(); // Output: Welcome to JavaScript!
showMessage(); // Output: Welcome to JavaScript!

Ç Anonymous Function Function Without a Name)


let multiply = function(a, b) {
return a * b;
};
console.log(multiply(4, 5)); // Output: 20

È Arrow Function Shorter Syntax for Anonymous Functions)


const square = (num) ⇒ num * num;
console.log(square(6)); // Output: 36

É Immediately Invoked Function Expression IIFE


Executed as soon as defined.

Module-4 49
(function() {
console.log("This function runs immediately!");
})();

2. JavaScript Events
An event is an action or occurrence triggered by a user (e.g., clicking, typing) or
the browser (e.g., page load, error).

Common Events in JavaScript


Event Description
click When an element is clicked
mouseover When the mouse hovers over an element
mouseout When the mouse leaves an element
keydown When a key is pressed
keyup When a key is released
keydown When a key is pressed
keyup When a key is released
change When the value of an input element changes
submit When a form is submitted
load When the page finishes loading

Handling Events in JavaScript


Å Using HTML Event Attributes Not Recommended)
<button onclick="alert('Button Clicked!')"Click Me</button>

Æ Using JavaScript Event Listeners Recommended Approach)


document.getElementById("myButton").addEventListener("click", function() {
alert("Button Clicked!");
});

Module-4 50
Ç Example: Changing Text on Button Click
<button id="changeText"Click Me</button>
<p id="text"Hello!/p>

<script>
document.getElementById("changeText").addEventListener("click", function()
{
document.getElementById("text").innerHTML  "Text Changed!";
});
</script>

Example: Mouseover and Mouseout Events

<p id="hoverText"Hover over me!/p>

<script>
let text = document.getElementById("hoverText");
<script>
let text = document.getElementById("hoverText");

text.addEventListener("mouseover", function() {
text.style.color = "red";
});

text.addEventListener("mouseout", function() {
text.style.color = "black";
});
</script>

Example: Form Validation Using Events

<input type="text" id="username" placeholder="Enter username">


<p id="error"></p>

<script>

Module-4 51
document.getElementById("username").addEventListener("keyup", function()
{
let input = this.value;
let errorMsg = document.getElementById("error");

if (input.length  3 
errorMsg.innerHTML  "Username must be at least 3 characters!";
errorMsg.style.color = "red";
} else {
errorMsg.innerHTML  "";
}
});
</script>

DOM Manipulation in JavaScript


The Document Object Model DOM represents the structure of a web page as a
tree of objects, allowing JavaScript to dynamically change content, structure, and
The Document Object Model DOM represents the structure of a web page as a
tree of objects, allowing JavaScript to dynamically change content, structure, and
styling.

1. Selecting Elements in the DOM


JavaScript provides several methods to select elements:

Å getElementById() – Select by ID
Finds a single element using its id .

let heading = document.getElementById("title");


heading.style.color = "blue";

<h1 id="title"Hello, World!/h1

Æ getElementsByClassName() – Select by Class

Module-4 52
Returns a collection (array-like list) of elements with the specified class.

let items = document.getElementsByClassName("item");


items[0].style.color = "red"; // Changes the first item's color

<p class="item"Item 1/p>


<p class="item"Item 2/p>

Ç getElementsByTagName() – Select by Tag


Returns a collection of elements with a specified tag name.

let paragraphs = document.getElementsByTagName("p");


paragraphs[1].style.fontWeight = "bold"; // Changes second paragraph

<p>Paragraph 1/p>
<p>Paragraph 2/p>
<p>Paragraph 1/p>
<p>Paragraph 2/p>

È querySelector() – Select First Matching Element


Finds the first element matching a CSS selector.

let firstItem = document.querySelector(".item");


firstItem.style.backgroundColor = "yellow";

<p class="item"Item 1/p>


<p class="item"Item 2/p>

É querySelectorAll() – Select All Matching Elements


Returns a NodeList of all elements matching the CSS selector.

Module-4 53
let allItems = document.querySelectorAll(".item");
allItems.forEach(item ⇒ item.style.color = "green");

2. Modifying Elements in the DOM


Å Changing Inner Text ( innerText , textContent )

document.getElementById("demo").innerText = "New Text!";

<p id="demo"Old Text</p>

Æ Changing HTML Content ( innerHTML )

document.getElementById("content").innerHTML  "<strong>Bold Text</stro


ng>";
ng>";

<p id="content"Original Text</p>

Ç Changing Attributes ( setAttribute , .src , .href )

document.getElementById("image").setAttribute("src", "new-image.jpg");

<img id="image" src="old-image.jpg">

3. Modifying Styles in the DOM


Å Using .style Property

document.getElementById("box").style.backgroundColor = "lightblue";

Module-4 54
document.getElementById("box").style.fontSize = "20px";

<div id="box"Change My Style</div>

Æ Adding and Removing CSS Classes ( classList )

document.getElementById("box").classList.add("new-class");
document.getElementById("box").classList.remove("old-class");

4. Creating and Removing Elements


Å Creating New Elements ( createElement )

let newPara = document.createElement("p");


newPara.innerText = "This is a new paragraph!";
document.body.appendChild(newPara);
newPara.innerText = "This is a new paragraph!";
document.body.appendChild(newPara);

Æ Removing Elements ( remove() )

document.getElementById("demo").remove();

5. Handling Events with DOM Manipulation


Å Adding an Event Listener
document.getElementById("btn").addEventListener("click", function() {
alert("Button Clicked!");
});

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

Module-4 55
Æ Changing Content on Click
document.getElementById("changeText").addEventListener("click", function()
{
document.getElementById("text").innerText = "Text Changed!";
});

<button id="changeText"Click Me</button>


<p id="text"Original Text</p>

Basics of JavaScript in Form Validation


Form validation ensures that user inputs meet the required criteria before
submission. JavaScript helps perform both client-side validation (faster, reduces
server load) and real-time validation (as the user types).
1. Why Use JavaScript for Form Validation?
✔ Prevents invalid or incomplete form submissions
˜ Improves user experience with instant feedback
˜ Reduces server-side processing and database errors
2. Basic Form Validation Example
' HTML Form
<form id="myForm">
<label for="name"Name:</label>
<input type="text" id="name">
<small id="nameError" style="color: red;"></small>

<label for="email"Email:</label>
<input type="email" id="email">

Module-4 56
<small id="emailError" style="color: red;"></small>

<button type="submit"Submit</button>
</form>

' JavaScript for Validation


document.getElementById("myForm").addEventListener("submit", function(ev
ent) {
let isValid = true;

let name = document.getElementById("name").value;


let email = document.getElementById("email").value;

// Validate Name Should not be empty)


if (name.trim() === "") {
document.getElementById("nameError").innerText = "Name is required!";
isValid = false;
document.getElementById("nameError").innerText = "Name is required!";
isValid = false;
} else {
document.getElementById("nameError").innerText = "";
}

// Validate Email Basic pattern check)


let emailPattern = /^[a-zAZ09._%+@[a-zAZ09.-]+\.[a-zAZ2,$/;
if !emailPattern.test(email)) {
document.getElementById("emailError").innerText = "Enter a valid emai
l!";
isValid = false;
} else {
document.getElementById("emailError").innerText = "";
}

// Prevent form submission if validation fails


if !isValid) {
event.preventDefault();

Module-4 57
}
});

3. Common Types of Validation


' Required Field Validation
Ensures the input is not left empty.

if (input.trim() === "") {


alert("This field is required!");
}

' Length Validation


Checks if input meets the required length.

if (password.length  6 
alert("Password must be at least 6 characters long!");
if (password.length  6 
alert("Password must be at least 6 characters long!");
}

' Number Validation


Ensures input is a valid number.

if (isNaN(age) || age  0 
alert("Enter a valid number!");
}

' Regular Expressions (Regex)


Used for pattern matching (e.g., email, phone number).

let phonePattern = /^0910$/;


if !phonePattern.test(phone)) {

Module-4 58
alert("Enter a 10-digit phone number!");
}

4. Real-Time Validation (On Input Event)


Instantly checks and displays errors as the user types.

document.getElementById("name").addEventListener("input", function() {
if (this.value.trim() === "") {
document.getElementById("nameError").innerText = "Name cannot be e
mpty!";
} else {
document.getElementById("nameError").innerText = "";
}
});

5. Preventing Form Submission on Invalid Input


5. Preventing Form Submission on Invalid Input
Even if JavaScript is enabled, users might bypass validation using Inspect
Element. Always validate data server-side as well.

document.getElementById("myForm").addEventListener("submit", function(ev
ent) {
if !isValid) {
event.preventDefault(); // Stops form from submitting
}
});

Module-4 59
text

You might also like