FSD Digital Notes
FSD Digital Notes
2024-25
FULL STACK DEVELOPMENT
(R22A0513)
LECTURE NOTES
Vision
Mission
o Apache: One of the most widely used web servers, known for its flexibility and wide
support.
o Nginx: A highly efficient and performant web server, often used as a reverse proxy or
load balancer in high-traffic environments.
o LiteSpeed: Known for performance and security features.
o Node.js: A runtime environment that also includes web server capabilities, typically
using frameworks like Express.js.
o IIS (Internet Information Services): A web server from Microsoft, commonly used for
Windows-based applications.
4. Static vs Dynamic Content
Static Content: Includes fixed resources like images, CSS files, and pre-rendered HTML pages.
Web servers simply retrieve these files and send them to the browser.
Dynamic Content: Involves processing logic, such as querying a database, running server-side
scripts, or processing user inputs. Web servers may pass the request to a back-end application
(e.g., Node.js, Django, Flask) to generate dynamic content, which is then returned to the client.
5. Security and Configuration
Web servers help secure applications by managing configurations like SSL/TLS encryption (for
HTTPS), setting up firewalls, controlling access permissions, and handling authentication (e.g.,
basic auth, OAuth).
They also provide performance optimizations, like caching, compression (e.g., gzip), and load
balancing to handle high traffic efficiently.
6. Web Server vs Web Application Server
A web server primarily handles HTTP requests and serves static content, while a web
application server is responsible for running application code, interacting with databases, and
generating dynamic content. Some servers, like Node.js, combine the functionalities of both.
7. Examples of Using Web Servers in Development
Local Development: During development, you can set up a web server locally (e.g., using
XAMPP, WAMP, or directly with Node.js) to test your website or application.
Deployment: For live environments, web servers host the website or application, with
configurations optimized for production, such as SSL/TLS for security, caching strategies, and
load balancing.
8. Popular Web Servers in Web Development
Apache HTTP Server: A highly configurable, open-source server, often used with PHP-based
websites.
Nginx: A lightweight, high-performance web server, often used for serving static files and as a
reverse proxy for handling dynamic content.
Express.js (Node.js): When building applications using JavaScript on the server side, Express is
a popular framework to handle HTTP requests and responses.
Backend services
The web server is a crucial component in the web development process, responsible for receiving,
processing, and responding to client requests. It ensures that static files are served correctly and dynamic
content is generated and delivered to users based on their interactions with the site or application.
In web development, backend services refer to the part of the application that runs on the server-side,
behind the scenes, to manage and process data, user authentication, interactions with databases, and more.
These services are responsible for handling the logic, database communication, and server-side processes
that power the functionality of a website or application.
Key Components of Backend Services
1. Web Server:
o A web server (e.g., Apache, Nginx) serves as the intermediary between the client
(browser) and the backend services, handling incoming HTTP/HTTPS requests and
forwarding them to appropriate backend processes.
2. Application Logic:
o This is the core functionality of the backend. It includes the business logic of your
application, like processing data, interacting with other services, and applying rules for
how the application should behave.
o Common backend technologies/frameworks for handling application logic include:
Node.js (JavaScript runtime, often with Express.js or other frameworks)
Ruby on Rails (Ruby)
Django (Python)
Flask (Python)
Laravel (PHP)
Spring Boot (Java)
3. Database Management:
o Backend services often interact with databases to store, retrieve, and manipulate data.
Databases can be either:
Relational Databases (SQL): Use structured tables to store data. Examples
include MySQL, PostgreSQL, SQLite.
Non-Relational Databases (NoSQL): Store unstructured or semi-structured data,
often in document, key-value, graph, or column-based models. Examples include
MongoDB, Cassandra, Firebase.
4. APIs (Application Programming Interfaces):
o Backend services often expose APIs to enable communication between the server and
client. These APIs allow the frontend (client-side) to request data and services from the
backend.
RESTful APIs: These follow standard HTTP methods like GET, POST, PUT,
and DELETE for CRUD (Create, Read, Update, Delete) operations.
GraphQL APIs: A newer, more flexible alternative to REST, allowing clients to
request only the data they need in a single query.
SOAP (Simple Object Access Protocol): An older protocol for exchanging
structured information, typically used in enterprise systems.
5. Authentication and Authorization:
o Backend services handle user authentication (verifying identity) and authorization
(determining access rights).
JWT (JSON Web Tokens): Used for securing API endpoints by encoding
claims about the user and their permissions.
OAuth: An open standard for access delegation, often used for allowing third-
party applications to access user data securely.
Session-based Authentication: Using server-side sessions to track authenticated
users.
6. Middleware:
o Middleware consists of code that lies between the web server and the backend
application, performing tasks like:
Authentication
Logging requests
Error handling
Request/response transformation (e.g., parsing JSON)
Caching
o Examples: Express middleware, Django middleware
7. Caching:
o To improve performance, backend services often use caching mechanisms to store
frequently requested data in memory for quick access, reducing the load on the database.
Redis: A fast, in-memory key-value store often used for caching and session
management.
Memcached: Another memory caching system often used for performance
improvements.
8. File Storage:
o Backend services also handle the uploading, storing, and retrieval of files such as images,
videos, and documents. Storage can either be local or cloud-based:
Cloud Storage: Services like Amazon S3, Google Cloud Storage, and Azure
Blob Storage provide scalable, secure storage.
File Servers: Can store files on a dedicated server or a distributed file system.
9. Background Jobs and Task Queues:
o Some tasks, like sending emails, processing large files, or generating reports, can be
offloaded to background services to avoid blocking user-facing interactions.
o These tasks are often handled using task queues or message brokers.
RabbitMQ: A popular message broker that helps manage and process tasks
asynchronously.
Celery (with Django/Flask): A distributed task queue system for background
processing.
AWS Lambda: Serverless functions that can process tasks in the background.
10. Real-time Communication:
o For real-time features like live chat, notifications, or collaborative editing, backend
services might use WebSockets, long polling, or server-sent events.
o Socket.IO: A library for real-time communication using WebSockets, often used with
Node.js.
o Firebase: A backend-as-a-service (BaaS) platform that provides real-time data
synchronization for applications.
11. Security:
o Backend services handle the security of an application, including protection against
threats like SQL injection, cross-site scripting (XSS), cross-site request forgery (CSRF),
and others.
o Implementing SSL/TLS encryption for secure data transmission (HTTPS).
o Implementing input validation and sanitation to prevent malicious code from being
executed on the server.
Key Technologies for Backend Services
1. Node.js:
o A JavaScript runtime that allows you to build server-side applications using JavaScript. It
is popular for building fast, scalable network applications, especially for APIs and real-
time applications.
o Common frameworks: Express.js, Koa.js
2. Django (Python):
o A high-level Python web framework that simplifies the development of secure and
maintainable websites. It includes features like authentication, database ORM (Object-
Relational Mapping), and an admin interface out of the box.
3. Ruby on Rails (Ruby):
o A popular web application framework written in Ruby, known for its convention over
configuration principles, speed of development, and large community.
4. Laravel (PHP):
o A robust PHP framework for web application development, offering tools for routing,
authentication, and database management.
5. Spring Boot (Java):
o A Java-based framework that simplifies the creation of production-ready, stand-alone
applications with minimal configuration.
6. Go (Golang):
o A statically typed, compiled programming language known for performance and
efficiency in backend services, especially for building scalable systems.
7. Serverless Platforms:
o Services like AWS Lambda, Google Cloud Functions, and Azure Functions provide
serverless architectures where you only focus on writing the backend logic, while the
platform takes care of scaling and infrastructure management.
Why Backend Services Matter
Data Management: Backend services are essential for managing large datasets, handling
requests, and ensuring the correct business logic is applied.
User Management: They handle critical functionalities like user authentication and
authorization, ensuring that only authorized users can access specific resources.
Performance: By offloading computationally expensive tasks, background services, and caching,
the backend ensures that the web application performs efficiently under high traffic conditions.
Security: They are responsible for securing the application, implementing proper data encryption,
preventing unauthorized access, and safeguarding sensitive data.
HTML Basics
In HTML, headings are used to define the structure and organization of content on a webpage. They help
users and search engines understand the hierarchy and importance of the content. HTML offers six levels
of headings, ranging from <h1> (the highest or most important level) to <h6> (the least important level).
Headings in HTML: Overview
Here’s how each heading tag works in HTML:
1. <h1> - The Most Important Heading
o Represents the most important heading, often used for the main title of a page or a
section.
o There should typically be only one <h1> tag per page for SEO purposes.
Example:
<h1>Welcome to My Website</h1>
2. <h2> - Subheadings of <h1>
o Used for secondary headings or sections within a page. These provide further structure
beneath the <h1> heading.
Example:
<h2>About Us</h2>
3. <h3> - Subheadings of <h2>
o Used for subsections under <h2> headings.
Example:
<h3>Our Mission</h3>
4. <h4> - Subheadings of <h3>
o These are used for even more specific subsections within <h3>.
Example:
<h4>Our Goals</h4>
5. <h5> - Subheadings of <h4>
o Used for even deeper sections, providing further breakdown of content under <h4>.
Example:
<h5>Short-Term Goals</h5>
6. <h6> - The Least Important Heading
o Represents the least important heading and is typically used for fine-grained sections or
items under <h5>.
Example:
<h6>Action Items</h6>
Usage and Best Practices
1. Hierarchical Structure: Headings should be used in a logical order. <h1> is the most important,
and the subsequent headings (<h2>, <h3>, etc.) should represent a nested structure. Don’t skip
heading levels (e.g., jumping from <h1> directly to <h4>).
2. SEO Considerations: Search engines often prioritize content that uses headings effectively. The
<h1> tag is especially important for SEO because it tells search engines the main topic of the
page. Use headings to structure content and improve the accessibility and relevance of your
webpage.
3. Accessibility: Headings help screen readers and other assistive technologies understand the
layout and structure of a webpage, making it more navigable for users with disabilities.
4. Styling Headings: By default, headings are displayed with a larger font size and bold text. You
can style them with CSS to adjust the font size, color, spacing, etc.
Example:
<style>
h1 {
color: darkblue;
font-size: 36px;
}
h2 {
color: darkgreen;
font-size: 30px;
}
</style>
Example of Using Headings in HTML
Here’s a simple example to illustrate how headings can be used in HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sample Webpage</title>
</head>
<body>
<h1>Welcome to Our Website</h1>
<h2>Our Services</h2>
<h3>Web Development</h3>
<p>We offer custom web development solutions.</p>
<h2>Contact Us</h2>
<h3>Support</h3>
<p>If you have any questions, feel free to contact our support team.</p>
<h3>Sales</h3>
<p>For sales inquiries, reach out to our sales department.</p>
</body>
</html>
Summary of HTML Headings
<h1>: Most important heading (typically used for page titles).
Paragraphs
In HTML, paragraphs are used to define blocks of text. The <p> tag is the HTML element used to create
paragraphs. Paragraphs are essential for structuring content and making text readable and organized.
The <p> Tag in HTML
The <p> tag is used to encapsulate a paragraph of text. By default, paragraphs are displayed with some
space before and after them to separate them from other elements.
Basic Syntax for a Paragraph
<p>This is a paragraph of text.</p>
Example of Multiple Paragraphs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Paragraphs in HTML</title>
</head>
<body>
<p>This is the first paragraph of text.</p>
<p>This is the second paragraph. It is separated from the first one with space.</p>
<p>This is the third paragraph. It has its own space and is distinct from the others.</p>
</body>
</html>
Key Points about Paragraphs in HTML
1. Text Wrapping:
o The <p> tag automatically wraps the text inside it. You don't need to manually break
lines with <br> for each new line in the paragraph.
o However, the browser automatically ignores extra spaces and line breaks within a
paragraph.
2. Paragraph Spacing:
o Paragraphs have default margins applied by browsers. Typically, there’s some space
before and after each <p> tag. You can adjust this spacing using CSS if needed.
3. Nested Elements:
o You can include other inline elements like <a>, <strong>, <em>, and others inside a
paragraph.
o Example:
o <p>This is a <strong>bold</strong> word in the paragraph.</p>
4. No Nested Paragraphs:
o It is not valid to place a <p> tag inside another <p> tag. If you do, the browser will
automatically close the first <p> and open a new one.
Example of incorrect usage:
<p>This is the first paragraph <p>This is a nested paragraph.</p></p> <!-- Incorrect -->
Styling Paragraphs with CSS
You can apply CSS styles to paragraphs to adjust things like font size, line height, margins, text
alignment, etc.
Example of CSS Styling for Paragraphs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Styled Paragraphs</title>
<style>
p{
font-size: 16px;
line-height: 1.6;
color: #333;
margin-bottom: 20px;
text-align: justify;
}
</style>
</head>
<body>
<p>This is a styled paragraph. The font size is set to 16px, with a line height of 1.6 to improve
readability. The text is justified and has a margin at the bottom.</p>
<p>Another styled paragraph. Notice the consistent styling applied across all paragraphs in the
document.</p>
</body>
</html>
Paragraphs and Accessibility
Semantic Meaning: The <p> tag provides semantic meaning to the text, which helps both search
engines and screen readers understand the content structure.
Spacing for Readability: Proper paragraph spacing enhances readability, especially for users
with visual impairments or cognitive difficulties.
Screen Readers: When paragraphs are properly defined, screen readers can more easily read the
content aloud, respecting the logical flow of text.
Conclusion
The <p> tag is fundamental in HTML for structuring textual content into readable paragraphs. It is simple
to use, and its styling can be customized with CSS to improve the appearance of text. Proper use of
paragraphs enhances both the user experience and SEO of a webpage.
links
In HTML, links are used to navigate between different web pages or resources. Links are created using
the <a> (anchor) tag, which stands for "anchor" because it anchors the user to a new location, whether it's
on the same page, a different page, or even an external site.
Basic Syntax for Links
The basic syntax for creating a link in HTML is:
<a href="URL">Link Text</a>
href: This attribute specifies the URL (Uniform Resource Locator) that the link points to. It can
be a relative path (for links within the same site) or an absolute URL (for external websites).
Link Text: This is the clickable text that users will see and click on.
Example of a Link
<a href="https://www.example.com">Visit Example Website</a>
In this example, the link text "Visit Example Website" is clickable, and when clicked, it will take the user
to https://www.example.com.
Types of Links
1. External Links:
o These links point to a different website or domain.
2. <a href="https://www.example.com">Go to Example.com</a>
3. Internal Links:
o These links point to another page or resource within the same website. This can be done
using a relative path.
4. <a href="/about.html">About Us</a>
5. Anchor Links (Same Page Links):
o These links point to a specific section or element within the same page. You create
anchor links using id attributes on elements.
6. <a href="#section2">Go to Section 2</a>
7. <!-- Later in the page -->
8. <h2 id="section2">Section 2</h2>
9. Mailto Links:
o These links open the user's email client with a predefined recipient's email address.
10. <a href="mailto:[email protected]">Send an Email</a>
11. Phone Links:
o These links allow users to click and dial a phone number (mainly on mobile devices).
12. <a href="tel:+1234567890">Call Us</a>
Opening Links in a New Tab
To open a link in a new tab (or window), you use the target="_blank" attribute:
<a href="https://www.example.com" target="_blank">Visit Example Website</a>
This ensures that when the user clicks the link, it opens in a new browser tab.
Linking to a Specific Part of a Page (Anchor Links)
To create links that navigate to a specific part of the same page, you need to use the id attribute on the
target element and then refer to that id in the href.
1. Set the id on the target element:
2. <h2 id="section1">Section 1</h2>
3. Create a link that points to the id:
4. <a href="#section1">Go to Section 1</a>
This way, when the link is clicked, the browser will scroll to the <h2> element with the id="section1".
Styling Links with CSS
Links can be styled using CSS to change their appearance, such as color, text decoration, and hover
effects.
Example of styling links:
<style>
a{
color: blue;
text-decoration: none;
}
a:hover {
color: red;
text-decoration: underline;
}
a:visited {
color: purple;
}
</style>
<h1>Welcome to My Website</h1>
<ul>
<li><a href="https://www.example.com" target="_blank">Visit Example Website</a></li>
<li><a href="/about.html">About Us</a></li>
<li><a href="#contact">Go to Contact Section</a></li>
<li><a href="mailto:[email protected]">Send an Email</a></li>
<li><a href="tel:+1234567890">Call Us</a></li>
</ul>
</body>
</html>
Summary
The <a> tag is used to create hyperlinks in HTML.
The href attribute specifies the destination URL.
Links can point to external websites, internal pages, sections within the same page, email
addresses, or phone numbers.
The target="_blank" attribute opens links in a new tab.
CSS can be used to style links and create effects like color changes and underlines.
Using links effectively improves navigation and accessibility on your website, enhancing the overall user
experience.
IMAGES
In HTML, images are used to display graphical content such as pictures, icons, and other visual elements.
The <img> tag is used to embed images in a webpage.
Basic Syntax for the <img> Tag
The basic syntax for embedding an image in HTML is:
<img src="image-url" alt="description" />
src (source): This attribute specifies the path to the image file. It can be a relative path (for
images stored locally in the same directory or project) or an absolute URL (for images hosted on
external websites).
alt (alternative text): This attribute provides a textual description of the image. This description is
important for accessibility, especially for users who rely on screen readers, and it is displayed if
the image fails to load.
The <img> tag is self-closing, meaning it does not have an end tag.
Example of an Image in HTML
<img src="https://www.example.com/images/logo.png" alt="Company Logo" />
In this example:
src="https://www.example.com/images/logo.png": This is the URL of the image.
alt="Company Logo": This is the description of the image, useful for screen readers and when
the image fails to load.
Image Attributes
The <img> tag has several useful attributes you can use to control how images are displayed:
1. src: Specifies the path to the image file.
2. alt: Describes the image for accessibility purposes.
3. width: Specifies the width of the image (in pixels or percentage).
4. height: Specifies the height of the image (in pixels or percentage).
5. title: Displays additional information when the user hovers over the image.
6. loading: Determines how the image is loaded (either "lazy" or "eager").
o lazy: The image is loaded only when it’s about to appear on the screen (helps improve
page load time).
o eager: The image is loaded immediately.
Example with Attributes
<img src="logo.png" alt="Logo of My Website" width="300" height="200" title="Click to visit
homepage" loading="lazy" />
Displaying Images from Different Sources
1. Local Images: If the image is stored locally in the same directory as the HTML file (or in a
folder within the directory), you can specify a relative path.
Example:
<img src="images/photo.jpg" alt="A local image" />
2. External Images: You can also display images from external websites by specifying the full
URL in the src attribute.
Example:
<img src="https://www.example.com/path/to/image.jpg" alt="External Image" />
Controlling Image Size
You can control the size of an image using the width and height attributes or with CSS.
Using HTML Attributes:
Example:
<img src="image.jpg" alt="A small image" width="500" height="300" />
Using CSS:
Example:
<img src="image.jpg" alt="A small image" style="width: 500px; height: 300px;" />
Alternatively, you can use percentages for responsive design:
<img src="image.jpg" alt="A responsive image" style="width: 100%; height: auto;" />
Responsive Images
To ensure that images are responsive and adapt to different screen sizes, you can use the width: 100%
CSS rule. This makes the image resize according to the width of its container while maintaining its aspect
ratio.
Example of a responsive image:
<img src="image.jpg" alt="Responsive Image" style="width: 100%; height: auto;" />
Image Formats
Common image formats used in web development include:
JPEG: Good for photos and images with gradients.
PNG: Supports transparency and is good for images with text or logos.
GIF: Best for simple graphics or animations.
SVG: Scalable vector graphics, which are XML-based and scalable without losing quality.
WebP: A newer format that provides smaller file sizes and better compression than JPEG and
PNG.
Example of Different Image Types
1. JPEG:
2. <img src="image.jpg" alt="JPEG Image" />
3. PNG:
4. <img src="image.png" alt="PNG Image" />
5. GIF:
6. <img src="animation.gif" alt="GIF Animation" />
7. SVG:
8. <img src="logo.svg" alt="SVG Logo" />
Image Accessibility
alt Text: The alt attribute is crucial for accessibility. If the image is purely decorative, you can set
an empty alt attribute (alt="") so screen readers skip it. For example:
<img src="decorative-image.png" alt="" />
Title Attribute: You can also use the title attribute to give additional information about the
image when users hover over it.
Example of a Full HTML Page with Images
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Images in HTML</title>
</head>
<body>
<img src="logo.png" alt="Our Company Logo" width="300" height="200" title="Click here to learn
more" />
</body>
</html>
Summary
The <img> tag is used to display images in HTML.
The src attribute specifies the image's location, and the alt attribute provides a text description.
You can control the image size with width and height attributes or CSS.
Images can be responsive by using CSS (e.g., width: 100% and height: auto).
Using proper alt text ensures your images are accessible to users with disabilities.
Lists, Tables
In HTML, lists and tables are essential elements for organizing and displaying data in a
structured format. Below is an overview of how to use both lists and tables in HTML.
1. Lists in HTML
Lists are used to group and display items in an ordered or unordered fashion. There are three
main types of lists in HTML: unordered lists, ordered lists, and definition lists.
a. Unordered Lists (<ul>)
An unordered list is used when the order of items doesn't matter. It is created using the <ul>
tag, and each list item is enclosed in an <li> tag.
Syntax:
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Unordered List Example</title>
</head>
<body>
<dt>Term 2</dt>
<dd>Definition of Term 2</dd>
</dl>
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Definition List Example</title>
</head>
<body>
<h3>HTML Tags</h3>
<dl>
<dt><h1></dt>
<dd>Defines the largest heading</dd>
<dt><p></dt>
<dd>Defines a paragraph</dd>
<dt><img></dt>
<dd>Defines an image</dd>
</dl>
</body>
</html>
2. Tables in HTML
A table is used to display tabular data in rows and columns. Tables are defined with the <table>
tag, and you use other elements like <tr>, <td>, and <th> to structure the data within the table.
Basic Table Structure
<table>: Defines the table.
<h3>Employee List</h3>
<table border="1">
<tr>
<th>Name</th>
<th>Position</th>
<th>Salary</th>
</tr>
<tr>
<td>John Doe</td>
<td>Manager</td>
<td>$60,000</td>
</tr>
<tr>
<td>Jane Smith</td>
<td>Developer</td>
<td>$80,000</td>
</tr>
<tr>
<td>Bob Johnson</td>
<td>Designer</td>
<td>$55,000</td>
</tr>
</table>
</body>
</html>
Adding More Table Features
1. Table Caption (<caption>): This tag adds a title to the table, which is displayed above
the table.
Syntax:
<table>
<caption>Employee List</caption>
...
</table>
2. Table Row Groups (<thead>, <tbody>, <tfoot>): These elements are used to group
header, body, and footer rows in the table for better organization and styling.
o <thead>: Contains the header row(s).
o <tbody>: Contains the body of the table.
o <tfoot>: Contains the footer row(s).
Example:
<table>
<caption>Employee List</caption>
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Salary</th>
</tr>
</thead>
<tbody>
<tr>
<td>John Doe</td>
<td>Manager</td>
<td>$60,000</td>
</tr>
<tr>
<td>Jane Smith</td>
<td>Developer</td>
<td>$80,000</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="3">Total Employees: 2</td>
</tr>
</tfoot>
</table>
Example with Styling and Formatting
You can use CSS to style your lists and tables for better presentation.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Styled Table</title>
<style>
table {
width: 100%;
border-collapse: collapse;
}
th, td {
padding: 8px;
text-align: left;
border: 1px solid #ddd;
}
th {
background-color: #f2f2f2;
}
caption {
font-size: 1.5em;
margin: 10px;
}
</style>
</head>
<body>
<h3>Employee List</h3>
<table>
<caption>Employee Information</caption>
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Salary</th>
</tr>
</thead>
<tbody>
<tr>
<td>John Doe</td>
<td>Manager</td>
<td>$60,000</td>
</tr>
<tr>
<td>Jane Smith</td>
<td>Developer</td>
<td>$80,000</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="3">Total Employees: 2</td>
</tr>
</tfoot>
</table>
</body>
</html>
Summary
Lists:
o Unordered Lists (<ul>): Use for items where the order doesn't matter.
o Ordered Lists (<ol>): Use for items where the order is important.
o Definition Lists (<dl>): Use for terms and their definitions.
Tables:
o Tables are structured using the <table> tag, with rows (<tr>) and cells (<td> for
data, <th> for headers).
o You can use <caption> for a table title and <thead>, <tbody>, <tfoot> for
grouping rows.
o Tables can be styled with CSS for better presentation and readability.
Using lists and tables effectively will help organize content and present data in a user-friendly
manner.
Div Element, Forms
1. <div> Element in HTML
The <div> tag in HTML is a block-level element used for grouping and structuring content. It
does not have any specific semantic meaning by itself but is used for styling, layout, and
grouping content together for logical organization.
Common Uses of <div>:
Layout: Div is frequently used for creating layouts (e.g., dividing a page into sections
like header, main content, sidebar, footer).
Styling: The <div> tag can be styled using CSS to create various effects like
backgrounds, borders, padding, margins, etc.
JavaScript: It's also commonly used as a container for JavaScript functionality (e.g.,
displaying content dynamically).
Syntax:
<div>
<!-- Content goes here -->
</div>
Example of Using <div> for Layout:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Using <div> for Layout</title>
<style>
.container {
display: flex;
flex-direction: column;
}
.header, .footer {
background-color: #4CAF50;
color: white;
padding: 10px;
}
.main-content {
padding: 20px;
}
.sidebar {
background-color: lightgray;
width: 200px;
padding: 10px;
}
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>Website Header</h1>
</div>
<div class="main-content">
<div class="sidebar">
<h3>Sidebar</h3>
<p>Links or extra information</p>
</div>
<div class="main-area">
<h3>Main Content</h3>
<p>This is where the main content of the page goes.</p>
</div>
</div>
<div class="footer">
<p>Footer Content</p>
</div>
</div>
</body>
</html>
In this example, the <div> elements are used to create different sections of the webpage, such as
the header, sidebar, main content area, and footer.
2. Forms in HTML
HTML forms allow users to submit data (e.g., text, files, selections) to a server. Forms are
created using the <form> element, and different types of input elements are used within the form
to collect data.
Basic Form Structure
A form in HTML is defined using the <form> element. The most common form elements
include:
<input>: Used for various types of input fields (text, password, radio buttons,
checkboxes, etc.).
<textarea>: Used for multi-line text input.
<select> and <option>: Used for dropdown lists.
<button>: Used to submit or reset the form.
Syntax of a Basic Form:
<form action="submit.php" method="POST">
<!-- Form Elements -->
</form>
action: The URL where the form data will be sent.
method: Defines the HTTP method used to send the form data (e.g., GET or POST).
Example of a Simple Form:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>HTML Form Example</title>
</head>
<body>
<h3>Contact Us</h3>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<br><br>
<label for="message">Message:</label>
<textarea id="message" name="message" rows="4" required></textarea>
<br><br>
<button type="submit">Submit</button>
</form>
</body>
</html>
Common Form Elements
1. <input>: Used to create various types of input fields.
o type="text": A single-line text input field.
o type="password": A text input field where the input is masked.
o type="email": For email input, automatically validates the email format.
o type="checkbox": A checkbox input.
o type="radio": A radio button input.
o type="submit": A button to submit the form.
Example:
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
2. <textarea>: Used for multi-line text input. Example:
3. <label for="message">Message:</label>
4. <textarea id="message" name="message" rows="4" cols="50" required></textarea>
5. <select> and <option>: Used to create dropdown lists. Example:
6. <label for="country">Country:</label>
7. <select id="country" name="country">
8. <option value="USA">USA</option>
9. <option value="Canada">Canada</option>
10. <option value="UK">UK</option>
11. </select>
12. <button>: Used to create buttons in a form, like submit or reset buttons. Example:
13. <button type="submit">Submit</button>
Form Attributes
1. action: Defines the server URL where the form data will be submitted.
2. <form action="submit_form.php" method="POST">
3. method: Specifies how the form data will be sent to the server. The two common
methods are:
o GET: Sends the form data as URL parameters (suitable for non-sensitive data).
o POST: Sends the form data in the HTTP request body (suitable for sensitive data,
such as passwords).
Example:
<form action="submit_form.php" method="POST">
4. target: Specifies where to display the response after the form is submitted.
o _self: Opens in the same frame (default).
o _blank: Opens in a new tab or window.
Example:
<form action="submit_form.php" method="POST" target="_blank">
Example of a Complete Form with Different Input Elements:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Registration Form</title>
</head>
<body>
<h3>Register</h3>
</body>
</html>
Summary
The <div> tag is used as a container to structure and style content. It doesn't carry any
inherent meaning but is useful for organizing content and layout.
Forms are created with the <form> element. Inside a form, you can use various input
elements like <input>, <textarea>, <select>, and <button> to collect user data.
Form data is submitted via the action and method attributes of the <form> tag. The GET
method sends data via URL, and the POST method sends data in the body of the HTTP
request.
2. Types of CSS
CSS can be applied to HTML in three main ways: Inline CSS, Internal CSS, and External
CSS.
a. Inline CSS
Inline CSS is used when you want to apply a style to a single element directly within the HTML
style attribute.
Syntax: You define the style in the HTML tag using the style attribute.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Internal CSS Example</title>
<style>
p{
color: blue;
font-size: 14px;
}
</style>
</head>
<body>
</body>
</html>
Pros:
Good for styling a single HTML document.
</body>
</html>
Pros:
Styles can be reused across multiple pages.
Keeps HTML and CSS separate, making the code cleaner and easier to maintain.
Ideal for larger websites.
Cons:
Requires an additional HTTP request to fetch the external CSS file.
3. CSS Selectors
CSS selectors define which HTML elements the styles apply to. There are several types of
selectors in CSS.
a. Universal Selector (*)
The universal selector targets all HTML elements in the document.
*{
margin: 0;
padding: 0;
}
This will remove the margin and padding from all elements on the page.
b. Type Selector (Element Selector)
This targets elements of a specific type (e.g., all <p> tags).
p{
color: red;
}
This will make all paragraphs (<p>) red.
c. Class Selector (.)
The class selector targets elements with a specific class attribute. It is prefixed with a dot (.).
.button {
background-color: blue;
color: white;
}
HTML:
<button class="button">Click Me</button>
This will apply the styles to any element with the class button.
d. ID Selector (#)
The ID selector targets an element with a specific id attribute. It is prefixed with a hash (#).
#header {
font-size: 24px;
text-align: center;
}
HTML:
<div id="header">Welcome to My Website</div>
This will apply the styles to the element with the id="header".
e. Attribute Selector
This targets elements based on their attributes.
input[type="text"] {
background-color: lightgray;
}
This will style all <input> elements with a type attribute equal to "text".
f. Descendant Selector
This targets elements nested inside another element.
div p {
color: green;
}
This will apply the style to all <p> elements that are inside a <div> element.
g. Child Selector (>)
This targets elements that are direct children of another element.
div > p {
color: blue;
}
This will apply the style to all <p> elements that are direct children of a <div>.
h. Pseudo-classes
Pseudo-classes target elements in specific states (e.g., when a link is hovered over).
a:hover {
color: red;
}
This changes the color of a link to red when it is hovered over.
i. Pseudo-elements
Pseudo-elements target a part of an element, such as the first letter or line.
p::first-letter {
font-size: 2em;
}
This will make the first letter of every paragraph 2 times larger than the rest of the text.
4. CSS Properties
CSS properties define the specific styles to apply to elements. Here are some common CSS
properties:
color: Sets the color of text.
p{
font-size: 16px;
color: gray;
line-height: 1.5;
}
This will style all <h1> elements with Arial font, a size of 32px, and center the text. All <p>
elements will have a font size of 16px, gray color, and a line height of 1.5.
Summary
CSS Syntax: Composed of selectors and declaration blocks with properties and values.
Types of CSS:
o Inline CSS: Applied directly within an HTML element.
o Internal CSS: Defined within the <style> tag in the HTML <head>.
o External CSS: Defined in an external .css file linked to the HTML document.
CSS Selectors: Used to target HTML elements. Common types include type selectors,
class selectors, ID selectors, and attribute selectors.
CSS Properties: Define the specific styles applied to elements, such as color,
background, margin, and font-size.
Using these methods and properties, CSS enables you to create visually appealing and well-
structured web pages.
Selectors, Background
CSS Selectors
CSS selectors define which HTML elements the styles should apply to. There are various types
of selectors in CSS, ranging from simple element selectors to complex, specific combinations
that target particular elements on the page.
1. Type Selector (Element Selector)
The type selector targets HTML elements by their tag name.
p{
color: red;
}
This will apply the style (red text) to all <p> elements on the page.
2. Class Selector
The class selector targets elements that have a specific class attribute. It is prefixed with a period
(.).
.button {
background-color: blue;
color: white;
}
HTML:
<button class="button">Click Me</button>
This will apply the styles to any element with the class="button".
3. ID Selector
The ID selector targets a specific element with a particular id attribute. It is prefixed with a hash
(#).
#header {
font-size: 24px;
text-align: center;
}
HTML:
<div id="header">Welcome to My Website</div>
This will apply the styles to the element with the id="header".
4. Universal Selector (*)
The universal selector targets all elements in the document.
*{
margin: 0;
padding: 0;
}
This will reset all margins and padding to 0 for all elements on the page.
5. Descendant Selector
A descendant selector targets elements that are inside another element, at any depth.
div p {
color: green;
}
This will apply the styles to all <p> elements that are inside a <div> element.
6. Child Selector (>)
The child selector targets elements that are direct children of another element.
div > p {
color: blue;
}
This will apply the styles only to <p> elements that are direct children of a <div>, not those
nested deeper.
7. Adjacent Sibling Selector (+)
The adjacent sibling selector targets an element that is immediately after a specified element.
h2 + p {
font-size: 18px;
}
This will apply the styles to the first <p> element immediately following an <h2> element.
8. General Sibling Selector (~)
The general sibling selector targets elements that are siblings of a specified element, but not
necessarily immediately following.
h2 ~ p {
color: purple;
}
This will apply the styles to all <p> elements that are siblings of an <h2>, regardless of how
many elements are between them.
9. Attribute Selector
Attribute selectors target elements based on the presence or value of an attribute.
input[type="text"] {
background-color: lightblue;
}
This will apply the styles to all <input> elements with a type attribute equal to "text".
10. Pseudo-classes
Pseudo-classes target elements in specific states, such as when a link is hovered over.
a:hover {
color: red;
}
This will change the color of a link to red when it is hovered over.
11. Pseudo-elements
Pseudo-elements target a part of an element, like the first letter or first line.
p::first-letter {
font-size: 2em;
}
This will make the first letter of every paragraph 2 times larger than the rest of the text.
contain: Scales the background image so that it is completely visible within the element,
possibly leaving space.
4. background-position
This property defines the position of the background image within the element. It can use values
like percentages, pixel values, or keywords like center, top, bottom, left, and right.
div {
background-image: url('background.jpg');
background-position: center;
}
This centers the background image within the element.
5. background-repeat
This property controls how the background image is repeated within an element. Possible values
include:
repeat: The background image is repeated both horizontally and vertically.
no-repeat: The background image is not repeated.
repeat-x: The background image is repeated horizontally.
repeat-y: The background image is repeated vertically.
div {
background-image: url('background.jpg');
background-repeat: no-repeat;
}
This ensures the background image is not repeated.
6. background-attachment
This property controls how the background image scrolls with the page. It can take the following
values:
scroll (default): The background image scrolls with the page.
fixed: The background image remains fixed in place while the page scrolls.
local: The background image scrolls with the element's content.
div {
background-image: url('background.jpg');
background-attachment: fixed;
}
This makes the background image stay fixed as the page scrolls.
7. background (Shorthand Property)
The background property is a shorthand to define all the background properties in one line.
div {
background: lightblue url('background.jpg') no-repeat center center fixed;
}
This combines multiple background properties:
background-color: lightblue;
background-image: url('background.jpg');
background-repeat: no-repeat;
background-position: center center;
background-attachment: fixed;
/* Class selector */
.content {
background-color: lightyellow;
padding: 20px;
font-size: 18px;
}
/* ID selector */
#footer {
background-image: url('footer-background.jpg');
background-size: cover;
background-position: center;
padding: 10px;
text-align: center;
color: white;
}
/* Universal selector */
*{
font-family: Arial, sans-serif;
}
</style>
</head>
<body>
<h1>Welcome to My Website</h1>
<div class="content">
<p>This is some content with a background color.</p>
</div>
<div id="footer">
<p>Footer Content</p>
</div>
</body>
</html>
In this example:
h1 is styled with a type selector.
Summary
CSS Selectors: Used to select elements in HTML to apply styles. Common types include
type selectors, class selectors, ID selectors, universal selectors, and pseudo-
classes/elements.
CSS Background Properties: Control the appearance of an element's background, such
as background-color, background-image, background-size, background-position,
background-repeat, and background-attachment. These can be combined into a shorthand
background property.
With these tools, you can apply detailed and flexible styles to HTML elements.
CSS Border and Font Properties
In CSS, borders and fonts are essential for styling the appearance of HTML elements. Borders
help define the boundaries of elements, while fonts control the appearance of text. Below is an
in-depth explanation of the border and font properties in CSS.
rem: Relative to the root element's font size (usually 16px by default).
Example with em:
element {
font-size: 1.5em; /* 1.5 times the size of the parent font */
}
c. font-weight
This property defines the thickness of the font. Common values include:
normal (default),
bold,
bolder,
lighter, or
A numeric value ranging from 100 to 900 (where 400 is normal and 700 is bold).
element {
font-weight: bold;
}
This will make the text bold.
d. font-style
This property controls whether the font is italicized or normal.
element {
font-style: italic;
}
This will make the text italic. Other values include normal (default) and oblique.
e. line-height
This property sets the amount of space between lines of text. It can help improve readability.
element {
line-height: 1.5;
}
This will set the line height to 1.5 times the font size.
f. letter-spacing
This property adjusts the space between characters in the text.
element {
letter-spacing: 2px;
}
This will add 2px of space between characters.
g. text-transform
This property defines how the text is transformed. Common values are:
uppercase: Converts text to uppercase.
center
right
justify
element {
text-align: center;
}
This will center the text horizontally within the element.
i. font-variant
This property controls the use of small caps, which renders lowercase letters as smaller capital
letters.
element {
font-variant: small-caps;
}
This will make the text appear in small caps.
button:hover {
background-color: #4CAF50;
color: white;
}
This will create a button with:
3px solid green border,
rounded corners,
bold and 18px text,
Arial font, and
green text that changes to white when hovered over.
Example 2: Card Element with Borders and Font Styling
.card {
border: 2px solid #ccc;
border-radius: 10px;
padding: 20px;
font-family: 'Times New Roman', serif;
font-size: 16px;
line-height: 1.6;
}
.card h2 {
font-size: 24px;
text-align: center;
}
This creates a card with:
2px solid border,
Summary
CSS Border Properties: Control the width, style, color, and radius of borders.
Common values include solid, dashed, dotted, and none.
CSS Font Properties: Control the appearance of text. Important properties include font-
family, font-size, font-weight, font-style, and line-height.
Combining: You can combine border and font properties in a single rule to style
elements in a cohesive way, such as buttons, cards, or headings.
These properties offer flexibility in creating visually appealing and well-structured designs.
CSS for Text and Tables
In CSS, you can use various properties to style text and tables. Below is an overview of how to
style text and tables in CSS, including examples for different styling techniques.
overline
line-through
none
a{
text-decoration: none;
}
This removes any underline from <a> (link) elements.
text-shadow
Applies a shadow effect to the text. You can specify the shadow's horizontal offset, vertical
offset, blur radius, and color.
h3 {
text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);
}
This adds a shadow to the <h3> text with a 2px horizontal and vertical offset and a 4px blur.
b. Example of Text Styling
p{
font-family: 'Times New Roman', serif;
font-size: 18px;
text-align: justify;
line-height: 1.5;
color: #333;
letter-spacing: 0.5px;
text-transform: capitalize;
}
This will style paragraphs with:
Times New Roman font,
18px size,
justified alignment,
1.5 line height,
dark gray color (#333),
0.5px letter-spacing,
capitalized first letter of each word.
th {
background-color: #4CAF50;
color: white;
font-weight: bold;
}
tr:nth-child(even) {
background-color: #f2f2f2;
}
caption {
font-size: 24px;
font-weight: bold;
text-align: center;
margin-bottom: 10px;
}
This example will:
Make the table span 100% of the available width,
Summary
CSS for Text: You can control text appearance using properties like font-family, font-
size, text-align, line-height, letter-spacing, text-transform, and more to create visually
appealing typography.
CSS for Tables: CSS provides various properties to style tables, such as border, padding,
text-align, vertical-align, and background-color. Additionally, nth-child can be used for
styling alternating rows, and caption can style the table caption.
With these text and table styling techniques, you can create well-designed and readable content
for your web pages.
Version Control
Git Basics
Git is a version control system used for tracking changes in code or any other collection of files.
It's especially useful for collaborative projects, allowing multiple people to work on the same
codebase without stepping on each other's toes. Here's a basic introduction to Git:
1. Git Branching
What is a Branch?
A branch in Git is essentially a pointer to one of the commits in your repository. It allows you to
diverge from the main line of development (the main or master branch) and work on something
independently without affecting the main project.
Branches are lightweight and inexpensive in Git, making it easy to experiment with different
features or fixes.
Why Use Branches?
To develop features or bug fixes independently from the main codebase.
3. Merging Branches
Once you’ve made changes on a branch (e.g., feature-xyz) and you’re ready to bring those
changes back into the main branch (e.g., main), you use merging.
Merging Branches
Merging combines the changes from one branch into another. Typically, you’ll want to merge a
feature branch into the main branch.
Steps for Merging:
1. Switch to the branch you want to merge into (typically main):
2. git checkout main
3. Merge the branch you want to integrate (e.g., feature-xyz) into main:
4. git merge feature-xyz
5. If there are no conflicts, Git will automatically merge the changes, and you’ll see a
message like:
6. Merge made by the 'recursive' strategy.
Handling Merge Conflicts
Sometimes, if two branches have conflicting changes (e.g., both branches modified the same line
in a file), Git won’t be able to automatically merge them. In this case, you’ll need to resolve the
conflict manually.
Git will mark the conflicted file(s) with conflict markers (<<<<<<<, =======,
>>>>>>>).
You must open the conflicted file, decide which changes to keep, and remove the conflict
markers.
After resolving the conflicts, stage the file:
git add <file>
Complete the merge by committing the changes:
git commit -m "Resolve merge conflict"
Fast-Forward Merges
If the branch you’re merging is directly ahead of the branch you’re merging into (i.e., no
diverging changes), Git will perform a fast-forward merge. This just moves the pointer of the
branch forward to the latest commit of the feature branch.
5. Deleting Branches
Once you've merged your branch, you may want to delete it to keep the repository clean.
Delete a local branch:
The URL can be HTTPS or SSH depending on how you configured your Git credentials.
1. What is JavaScript?
JavaScript is a scripting language that enables developers to create dynamic and interactive
content for web pages. It's primarily used for:
Manipulating HTML and CSS to update content, structure, and styles on a webpage.
Handling events like user clicks, mouse movements, and keyboard inputs.
Creating interactive features like form validation, animations, and data fetching.
o String ("Hello")
o Number (25)
o Boolean (true, false)
o Null (null)
o Undefined (undefined)
o Symbol (new in ES6)
o BigInt (for large integers)
Complex Types:
o Object ({ name: "Alice", age: 25 })
o Array ([1, 2, 3])
Example:
let name = "Alice"; // String
let age = 25; // Number
let isActive = true; // Boolean
let user = { name: "Alice", age: 25 }; // Object
Operators
JavaScript supports many types of operators, including:
Arithmetic Operators: +, -, *, /, %, ++, --
5. Functions
A function is a block of reusable code designed to perform a particular task.
Function Declaration
You can define a function using the function keyword.
function greet(name) {
return "Hello, " + name + "!";
}
6. Arrays
Arrays are used to store multiple values in a single variable.
Creating an Array
let fruits = ["Apple", "Banana", "Cherry"];
Accessing Array Elements
console.log(fruits[0]); // "Apple"
Array Methods
.push() adds an element to the end of the array.
7. Objects
Objects are used to store key-value pairs. They are like containers for related data.
Creating an Object
let person = {
name: "Alice",
age: 25,
greet: function() {
return "Hello, " + this.name;
}
};
Accessing Object Properties
You can access object properties using either dot notation or bracket notation.
console.log(person.name); // "Alice"
console.log(person["age"]); // 25
8. Events
JavaScript can interact with HTML elements via events. You can respond to actions like clicks,
keypresses, or mouse movements.
Event Listener Example
<button onclick="alert('Button clicked!')">Click me</button>
Alternatively, you can add an event listener using JavaScript:
let button = document.querySelector("button");
button.addEventListener("click", function() {
alert("Button clicked!");
});
9. DOM Manipulation
The Document Object Model (DOM) represents the structure of an HTML document.
JavaScript allows you to interact with the DOM to change the content, structure, or style of a
webpage.
Accessing Elements
You can use various methods to access elements:
let element = document.getElementById("myElement");
let elements = document.getElementsByClassName("myClass");
let elements = document.querySelectorAll("div"); // Selects all <div> tags
Modifying Content
You can modify the content of an element with JavaScript:
document.getElementById("myElement").innerHTML = "New content!";
Conclusion
JavaScript is an essential part of modern web development, enabling dynamic behavior and
interactive user experiences. With its rich set of features, such as variables, loops, functions,
objects, and event handling, it offers powerful tools for building interactive websites and web
applications.
This introduction covered the basics, but JavaScript has many more advanced concepts to
explore, such as asynchronous programming (callbacks, promises, and async/await), working
with APIs, and more.
JavaScript Basics
JavaScript is a powerful, high-level programming language primarily used for creating
interactive effects within web browsers. It is one of the core technologies of the web, alongside
HTML and CSS.
1. What is JavaScript?
JavaScript is a scripting language that enables developers to create dynamic and interactive
content for web pages. It's primarily used for:
Manipulating HTML and CSS to update content, structure, and styles on a webpage.
Handling events like user clicks, mouse movements, and keyboard inputs.
Creating interactive features like form validation, animations, and data fetching.
o String ("Hello")
o Number (25)
o Boolean (true, false)
o Null (null)
o Undefined (undefined)
o Symbol (new in ES6)
o BigInt (for large integers)
Complex Types:
o Object ({ name: "Alice", age: 25 })
o Array ([1, 2, 3])
Example:
let name = "Alice"; // String
let age = 25; // Number
let isActive = true; // Boolean
let user = { name: "Alice", age: 25 }; // Object
Operators
JavaScript supports many types of operators, including:
Arithmetic Operators: +, -, *, /, %, ++, --
5. Functions
A function is a block of reusable code designed to perform a particular task.
Function Declaration
You can define a function using the function keyword.
function greet(name) {
return "Hello, " + name + "!";
}
6. Arrays
Arrays are used to store multiple values in a single variable.
Creating an Array
let fruits = ["Apple", "Banana", "Cherry"];
Accessing Array Elements
console.log(fruits[0]); // "Apple"
Array Methods
.push() adds an element to the end of the array.
7. Objects
Objects are used to store key-value pairs. They are like containers for related data.
Creating an Object
let person = {
name: "Alice",
age: 25,
greet: function() {
return "Hello, " + this.name;
}
};
Accessing Object Properties
You can access object properties using either dot notation or bracket notation.
console.log(person.name); // "Alice"
console.log(person["age"]); // 25
8. Events
JavaScript can interact with HTML elements via events. You can respond to actions like clicks,
keypresses, or mouse movements.
Event Listener Example
<button onclick="alert('Button clicked!')">Click me</button>
Alternatively, you can add an event listener using JavaScript:
let button = document.querySelector("button");
button.addEventListener("click", function() {
alert("Button clicked!");
});
9. DOM Manipulation
The Document Object Model (DOM) represents the structure of an HTML document.
JavaScript allows you to interact with the DOM to change the content, structure, or style of a
webpage.
Accessing Elements
You can use various methods to access elements:
let element = document.getElementById("myElement");
let elements = document.getElementsByClassName("myClass");
let elements = document.querySelectorAll("div"); // Selects all <div> tags
Modifying Content
You can modify the content of an element with JavaScript:
document.getElementById("myElement").innerHTML = "New content!";
Conclusion
JavaScript is an essential part of modern web development, enabling dynamic behavior and
interactive user experiences. With its rich set of features, such as variables, loops, functions,
objects, and event handling, it offers powerful tools for building interactive websites and web
applications.
This introduction covered the basics, but JavaScript has many more advanced concepts to
explore, such as asynchronous programming (callbacks, promises, and async/await), working
with APIs, and more.
Functions in JavaScript
In JavaScript, a function is a block of code designed to perform a specific task or calculation.
Functions are one of the core building blocks in JavaScript, allowing you to write reusable code
and better organize your programs.
1. Function Declaration
A function can be defined using the function keyword followed by the function name,
parentheses, and a block of code. You can pass parameters to the function, which act as
placeholders for values you want to provide when calling the function.
Syntax:
function functionName(parameter1, parameter2) {
// Code to be executed
}
Example:
function greet(name) {
console.log("Hello, " + name + "!");
}
2. Function Expression
Functions in JavaScript can also be defined as expressions, meaning they can be assigned to
variables. These are known as function expressions. A function expression can be anonymous
or named.
Syntax:
const functionName = function(parameter1, parameter2) {
// Code to be executed
};
Example:
const greet = function(name) {
console.log("Hello, " + name + "!");
};
4. Function Parameters
Functions in JavaScript can accept parameters, which are values that you pass into the function
when you call it. You can also use default parameters and rest parameters.
Default Parameters:
You can assign default values to function parameters, which are used when no argument is
passed for those parameters.
function greet(name = "Guest") {
console.log("Hello, " + name + "!");
}
5. Return Statement
Functions in JavaScript can return a value using the return keyword. Once a return statement is
executed, the function stops executing, and the specified value is returned.
Syntax:
function functionName() {
return value;
}
Example:
function add(a, b) {
return a + b;
}
6. Function Hoisting
In JavaScript, hoisting is a behavior where function declarations are moved to the top of their
containing scope during the compilation phase. This means that you can call a function before its
declaration if it's a function declaration, but function expressions are not hoisted.
Function Declaration Hoisting Example:
greet("Alice"); // Output: Hello, Alice!
function greet(name) {
console.log("Hello, " + name + "!");
}
The above code works because the greet function is hoisted to the top.
Function Expression Hoisting Example:
greet("Bob"); // Error: greet is not a function
7. Anonymous Functions
An anonymous function is a function without a name, often used as a function expression or
passed as an argument to other functions.
Example:
setTimeout(function() {
console.log("Hello after 2 seconds!");
}, 2000);
Here, an anonymous function is passed as an argument to setTimeout, which executes after a
delay of 2000 milliseconds (2 seconds).
8. Callback Functions
A callback function is a function that is passed as an argument to another function and is
executed after the completion of the main function. Callback functions are commonly used for
handling asynchronous operations, such as reading files or making network requests.
Example:
function fetchData(callback) {
setTimeout(() => {
let data = { name: "Alice", age: 25 };
callback(data); // Call the callback function with the data
}, 2000);
}
function displayData(data) {
console.log("Data received:", data);
}
9. Closures
A closure is a function that "remembers" its lexical scope, even when the function is executed
outside that scope. Closures allow functions to retain access to variables from their parent
function.
Example:
function outer() {
let counter = 0;
Conclusion
Functions are a fundamental concept in JavaScript and are essential for building maintainable
and reusable code. You can define functions in various ways, pass parameters, return values, and
use advanced features such as closures and callbacks. Understanding how functions work is
crucial to mastering JavaScript and web development.
form validation
Form Validation in JavaScript
Form validation is the process of ensuring that the user inputs data correctly before submitting
the form. In JavaScript, form validation can be used to check if the user has filled out the
required fields, entered valid data (such as email or phone number), or ensured that the form data
matches specific criteria.
Types of Form Validation:
1. Client-side validation (using JavaScript, HTML5, and CSS).
2. Server-side validation (using server-side languages like PHP, Python, Node.js, etc.).
In this article, we will focus on client-side validation using JavaScript.
<label for="email">Email:</label>
<input type="email" id="email" name="email"><br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password"><br><br>
<script src="script.js"></script>
</body>
</html>
Here, we have a form that collects a user’s full name, email, password, and password
confirmation.
<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" minlength="6" required><br><br>
The type="email" ensures that the email field contains a valid email.
The minlength="6" ensures that the password is at least 6 characters long.
HTML5 form validation will automatically display a browser-generated message if the user does
not meet the requirements (e.g., leaving a required field empty or entering an invalid email).
// Validate Name
if (name === "") {
alert("Please enter your name.");
return false;
}
// Validate Email
let emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
if (!email.match(emailPattern)) {
alert("Please enter a valid email address.");
return false;
}
5. Conclusion
Form validation is an important aspect of web development, and JavaScript allows us to easily
perform both client-side and server-side validation. While HTML5 provides built-in validation
features, custom JavaScript validation gives you more control over the error handling and user
feedback.
By combining HTML5 features and JavaScript, you can ensure your forms are properly validated
before data is submitted to the server, improving both user experience and data integrity.
OOPS Aspects of JavaScript
OOP (Object-Oriented Programming) Aspects of JavaScript
JavaScript is a multi-paradigm language, meaning it supports different programming styles,
including procedural, functional, and object-oriented programming (OOP). Object-Oriented
Programming (OOP) in JavaScript is built around objects and classes, allowing developers to
structure code in a more organized and reusable manner.
In JavaScript, OOP concepts are implemented using objects, classes, and other associated
principles such as inheritance, encapsulation, polymorphism, and abstraction.
1. Objects in JavaScript
In JavaScript, an object is a collection of key-value pairs. Objects are used to store related data
and functions.
Example:
let person = {
firstName: "John",
lastName: "Doe",
age: 30,
greet: function() {
console.log("Hello, " + this.firstName + " " + this.lastName);
}
};
// Method to greet
greet() {
console.log("Hello, " + this.firstName + " " + this.lastName);
}
}
3. Inheritance in JavaScript
Inheritance allows one class to inherit properties and methods from another. In JavaScript,
classes can inherit from other classes using the extends keyword.
Example of Inheritance:
// Parent class (Base class)
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(this.name + " makes a sound");
}
}
speak() {
console.log(this.name + " barks");
}
}
The speak method is overridden in the Dog class (this is called method overriding).
super() is used to call the parent class's constructor.
4. Encapsulation in JavaScript
Encapsulation is the concept of bundling the data (properties) and methods that operate on that
data into a single unit (class) and restricting access to certain components to prevent
unauthorized access or modification.
Private and Public Properties/Methods:
In JavaScript, before ES2022, all object properties and methods were public. With ES2022,
private fields and methods were introduced using the # symbol.
Example:
class Person {
#age; // Private field
// Public method
getAge() {
return this.#age;
}
// Private method
#privateMethod() {
console.log("This is a private method.");
}
5. Polymorphism in JavaScript
Polymorphism is the ability to call the same method on different objects, and each object will
respond in its own way. It allows objects to behave differently based on their class type.
Example:
class Animal {
speak() {
console.log("The animal makes a sound");
}
}
6. Abstraction in JavaScript
Abstraction is the concept of hiding the complex implementation details and showing only the
essential features. While JavaScript does not have built-in support for abstract classes like some
other languages (e.g., Java or C#), abstraction can be achieved by using interfaces (through
functions or classes) or abstract methods that child classes are required to implement.
Example of Abstraction Using Abstract Classes:
class Shape {
// Abstract method (must be implemented in child classes)
area() {
throw "Area method must be implemented";
}
}
area() {
return Math.PI * this.radius * this.radius;
}
}
class Rectangle extends Shape {
constructor(length, width) {
super();
this.length = length;
this.width = width;
}
area() {
return this.length * this.width;
}
}
Conclusion
JavaScript's implementation of Object-Oriented Programming (OOP) allows developers to
write clean, modular, and reusable code. The main OOP concepts you can use in JavaScript are:
Objects: Collections of properties and methods.
jQuery Framework
jQuery is a fast, small, and feature-rich JavaScript library. It simplifies things like HTML
document traversal and manipulation, event handling, animation, and Ajax interactions for rapid
web development. jQuery is designed to make it easier to work with JavaScript and handle
common tasks across different browsers, offering cross-browser compatibility and simplifying
JavaScript syntax.
Key Features of jQuery:
DOM Manipulation: Easily manipulate HTML elements.
Event Handling: Simplify event handling, like mouse clicks and keyboard input.
AJAX: Make asynchronous requests to a server without reloading the page.
Animations and Effects: Animate elements and apply effects.
Cross-browser compatibility: jQuery handles browser-specific issues automatically.
Installing jQuery
There are two main ways to add jQuery to your project:
1. Using a CDN (Content Delivery Network): The fastest way to include jQuery in your
project is by linking to a CDN like Google's or jQuery's official CDN.
Example:
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
2. Downloading jQuery: You can download the jQuery library from jQuery's official
website.
Then, link to the local jQuery file in your HTML:
<script src="path/to/jquery-3.6.0.min.js"></script>
$('#elementId').text("New Text");
Changing HTML:
$('#elementId').html("<p>New HTML Content</p>");
Changing an Attribute:
$('#elementId').attr("src", "new-image.jpg");
Appending Content:
$('#elementId').append("<p>Additional Content</p>");
Prepending Content:
$('#elementId').prepend("<p>Prepended Content</p>");
Removing an Element:
$('#elementId').remove();
$('#buttonId').click(function() {
alert("Button clicked!");
});
Hover Event (Mouse Over and Out):
$('#elementId').hover(function() {
$(this).css("background-color", "yellow");
}, function() {
$(this).css("background-color", "");
});
Submit Event (For Forms):
$('#formId').submit(function(event) {
event.preventDefault(); // Prevents the default form submission
alert("Form Submitted!");
});
Keyup and Keydown Events:
$('#inputField').keyup(function() {
console.log("Key released: " + $(this).val());
});
$.get('url-to-server', function(data) {
console.log(data);
});
AJAX POST Request:
$.post('url-to-server', { name: 'John', age: 30 }, function(data) {
console.log(data);
});
AJAX with $.ajax(): You can also use $.ajax() for more complex requests:
$.ajax({
url: 'url-to-server',
type: 'GET', // or 'POST'
data: { name: 'John', age: 30 },
success: function(response) {
console.log(response);
},
error: function(error) {
console.log(error);
}
});
AJAX with JSON: jQuery makes it easy to work with JSON data:
$.getJSON('data.json', function(data) {
console.log(data);
});
5. jQuery UI
In addition to the core jQuery library, jQuery UI provides additional features such as interaction
(drag, drop), effects, and more sophisticated UI components like accordions, datepickers, and
sliders. To use jQuery UI, you need to include both the jQuery UI CSS and JS files.
<!-- jQuery UI CSS -->
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
Conclusion
jQuery is a versatile and powerful JavaScript library that simplifies HTML document
manipulation, event handling, animations, and AJAX requests.
It is widely used in web development to ensure compatibility across different browsers
and reduce the amount of code developers need to write.
While jQuery has become less necessary with the rise of modern JavaScript frameworks
like React, Angular, and Vue, it still remains a powerful tool for many developers,
especially for simpler websites or projects that need fast, efficient DOM manipulation
and cross-browser functionality.
jQuery events
jQuery Events
jQuery provides a simple and consistent way to handle events in web development. Events are
actions that occur in the browser, like user interactions (clicking a button, moving the mouse,
typing text), or other occurrences (page load, focus change). With jQuery, you can easily manage
these events and define actions that should occur when they are triggered.
Common jQuery Event Methods
1. .click()
o Triggered when an element is clicked.
o Syntax: $(selector).click(function)
Example:
$('#button').click(function() {
alert('Button clicked!');
});
2. .dblclick()
o Triggered when an element is double-clicked.
o Syntax: $(selector).dblclick(function)
Example:
$('#button').dblclick(function() {
alert('Button double-clicked!');
});
3. .hover()
o Triggered when the mouse enters and leaves an element. It takes two functions:
one for mouseenter and one for mouseleave.
o Syntax: $(selector).hover(functionIn, functionOut)
Example:
$('#box').hover(
function() { // Mouse enter
$(this).css("background-color", "yellow");
},
function() { // Mouse leave
$(this).css("background-color", "white");
}
);
4. .focus() and .blur()
o .focus() is triggered when an element gets focus (e.g., when a user clicks on an
input field).
o .blur() is triggered when an element loses focus.
o Syntax: $(selector).focus(function) or $(selector).blur(function)
Example:
$('#inputField').focus(function() {
$(this).css("border", "2px solid blue");
});
$('#inputField').blur(function() {
$(this).css("border", "");
});
5. keydown(), .keypress(), and .keyup()
o .keydown() is triggered when a key is pressed down.
o .keypress() is triggered when a key is pressed and held.
o .keyup() is triggered when a key is released.
o Syntax: $(selector).keydown(function), $(selector).keypress(function),
$(selector).keyup(function)
Example:
$('#inputField').keydown(function(event) {
console.log('Key pressed: ' + event.key);
});
6. .change()
o Triggered when the value of a form element (like <input>, <select>, or
<textarea>) changes.
o Syntax: $(selector).change(function)
Example:
$('#selectBox').change(function() {
alert('Selection changed!');
});
7. submit()
o Triggered when a form is submitted.
o Syntax: $(selector).submit(function)
Example:
$('#form').submit(function(event) {
event.preventDefault(); // Prevents default form submission
alert('Form submitted!');
});
8. .keydown()
o Triggered when a key is pressed down, commonly used for text inputs.
o Syntax: $(selector).keydown(function)
Example:
$('#inputField').keydown(function(event) {
console.log("You pressed the " + event.key + " key.");
});
9. resize()
o Triggered when the window or an element is resized.
o Syntax: $(window).resize(function)
Example:
$(window).resize(function() {
console.log('Window resized!');
});
10. scroll()
o Triggered when an element is scrolled.
o Syntax: $(selector).scroll(function)
Example:
$(window).scroll(function() {
console.log('Window scrolled!');
});
11. .mousedown() and mouseup()
o .mousedown() is triggered when the mouse button is pressed down.
o .mouseup() is triggered when the mouse button is released.
o Syntax: $(selector).mousedown(function) or $(selector).mouseup(function)
Example:
$('#box').mousedown(function() {
console.log('Mouse button pressed!');
});
$('#box').mouseup(function() {
console.log('Mouse button released!');
});
Event Object
When an event is triggered, jQuery provides an event object to the handler function that contains
details about the event (e.g., which key was pressed, mouse position, etc.).
Example:
$('#button').click(function(event) {
console.log('Event type: ' + event.type); // type of event (e.g., "click")
console.log('Mouse position: (' + event.pageX + ', ' + event.pageY + ')');
});
Stopping Event Propagation and Preventing Default Behavior
stopPropagation(): Stops the event from propagating (bubbling) up the DOM.
preventDefault(): Prevents the default action associated with the event from being
triggered.
Example:
$('#link').click(function(event) {
event.preventDefault(); // Prevents the link from navigating
event.stopPropagation(); // Prevents the event from bubbling up
alert('Link click prevented!');
});
Conclusion
jQuery makes it much easier to handle events in JavaScript. Whether you're dealing with user
actions like clicks, keyboard input, or form submissions, jQuery provides a concise and cross-
browser-compatible syntax to manage these events.
Common jQuery Event Methods:
.click(), .dblclick(), .hover()
.focus(), .blur()
.keydown(), .keyup(), .keypress()
.submit(), .change()
.resize(), .scroll()
.on() for event delegation
You can use these methods to build dynamic, interactive web pages by binding and managing
events efficiently.
AJAX for data exchange with server
AJAX for Data Exchange with Server in jQuery
AJAX (Asynchronous JavaScript and XML) allows you to send and retrieve data from a server
asynchronously, without refreshing the entire web page. This enables you to update parts of a
web page dynamically, improving user experience by reducing the need to reload the page. In
jQuery, AJAX operations are simplified and can be performed with just a few lines of code.
1. $.ajax() Method
The $.ajax() method is the most flexible and powerful method to make AJAX requests. It allows
you to configure a variety of options like request type (GET or POST), data type, success and
error handling, etc.
Syntax:
$.ajax({
url: 'your-server-url', // URL to send the request to
type: 'GET', // or 'POST', 'PUT', etc.
data: { key1: value1, key2: value2 }, // Data to send to the server (optional)
dataType: 'json', // The type of data you're expecting to receive from the server
success: function(response) {
console.log('Success:', response); // Handle success response
},
error: function(xhr, status, error) {
console.log('Error:', error); // Handle errors
}
});
Example: Sending a GET request to fetch data from the server
$.ajax({
url: 'data.php', // Server URL
type: 'GET', // Request type
dataType: 'json', // Expected data type (JSON)
success: function(data) {
console.log(data); // Process the data received from the server
},
error: function(xhr, status, error) {
console.log('Request failed:', error); // Handle the error
}
});
2. $.get() Method
The $.get() method is a shorthand for making GET requests. It is a simpler way to retrieve data
from the server.
Syntax:
$.get(url, data, callback, dataType);
url: The URL to which the request is sent.
data: Data to be sent to the server (optional).
callback: A function to be executed when the request is successful.
dataType: Expected data type (optional, like 'json', 'xml').
Example: Using $.get() to fetch data
$.get('data.php', { id: 123 }, function(response) {
console.log(response); // Process the server response
});
3. $.post() Method
The $.post() method is a shorthand for making POST requests. It is used when sending data to
the server, usually when submitting form data.
Syntax:
$.post(url, data, callback, dataType);
url: The URL to which the request is sent.
4. $.getJSON() Method
The $.getJSON() method is a shorthand for making GET requests that expect the server to
respond with JSON data.
Syntax:
$.getJSON(url, data, callback);
url: The URL to which the request is sent.
$.ajax({
url: 'data.php',
type: 'GET',
success: function(data) {
$('#loading').hide(); // Hide loading indicator when request completes
console.log(data);
},
error: function(xhr, status, error) {
$('#loading').hide(); // Hide loading indicator on error
console.log('Error:', error);
}
});
$.ajax({
url: 'submit.php',
type: 'POST',
data: formData,
success: function(response) {
console.log('Form submitted successfully:', response);
},
error: function(xhr, status, error) {
console.log('Form submission failed:', error);
}
});
});
Conclusion
AJAX allows you to send and receive data from the server without reloading the page, enabling
dynamic updates to web pages. jQuery provides several methods, like $.ajax(), $.get(), $.post(),
and $.getJSON(), to make AJAX requests easily. Handling AJAX in jQuery is simple and
effective for updating parts of a page dynamically, improving the overall user experience.
Key Concepts:
Asynchronous requests without reloading the page.
Structure of JSON
JSON data consists of two primary structures:
1. Objects
2. Arrays
1. JSON Objects
A JSON object is an unordered collection of key/value pairs. It is written as a set of curly braces
{} with the key/value pairs inside. Each key is a string, followed by a colon :, and then the value
can be a string, number, array, object, boolean, or null.
Syntax of an Object:
{
"key1": "value1",
"key2": "value2",
"key3": "value3"
}
Key/Name: Always a string (enclosed in double quotes "").
Value: Can be a string, number, array, object, boolean (true or false), or null.
Example of a JSON Object:
{
"name": "John",
"age": 30,
"isStudent": false,
"address": {
"street": "123 Main St",
"city": "Anytown",
"zip": "12345"
}
}
"name", "age", "isStudent", and "address" are keys.
"John", 30, false, and the nested object are values.
2. JSON Arrays
A JSON array is an ordered collection of values, enclosed in square brackets []. The values in an
array can be of any data type: string, number, object, array, boolean, or null.
Syntax of an Array:
["value1", "value2", "value3"]
Example of a JSON Array:
{
"fruits": ["apple", "banana", "cherry"],
"numbers": [1, 2, 3, 4, 5],
"isActive": [true, false]
}
"fruits" and "numbers" are keys.
The values are arrays, where each element is a different type (string, number, boolean).
o "name": String
o "age": Number
o "isAdmin": Boolean
o "address": Nested object
o "friends": Array of strings
o "preferences": Null
Conclusion
JSON is a simple and widely-used format for exchanging data. Its syntax is easy to understand
and use, especially in web development, where it plays a key role in APIs, configuration files,
and data storage. Understanding the structure and types of JSON will help you effectively work
with JSON in JavaScript, web applications, and other systems.
UNIT-III
Angular:
Importance of Angular js
AngularJS was a JavaScript framework that helped developers create dynamic web apps. It
was created by Google developers to make it easier to write web apps. Some benefits of AngularJS
include:
Code reduction: AngularJS uses data binding and dependency injection to reduce the amount of
code needed.
HTML templates: AngularJS uses HTML as the template language, which can be used to
develop responsive web apps.
Understanding Angular:
a) AngularJS is a JavaScript framework that can be added to a web page with a script tag.
Syntax:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
b) AngularJS extends HTML with “ng-directives”.
The ng-app directive tells AngularJS that the <div> element is the "owner" of an
AngularJS application.
The ng-model directive binds the value of the input field to the application
variable name.
The ng-bind directive binds the content of the <p> element to the application
variable name.
c) “AngularJS directives” are HTML attributes with an ng prefix. The ng-init directive initializes
AngularJS application variables.
Example:
</div>
In the HTML, add a text field, and bind it to the application with the ng-model directive.
In the controller, make a function named addItem, and use the value of the addMe input
field to add an item to the products array.
Add a button, and give it an ng-click directive that will run the addItem function when the
button is clicked.
Code:
<script>
var app = angular.module("myShoppingList", []);
app.controller("myCtrl", function($scope)
{
$scope.products =["Milk", "Bread", "Cheese"];
$scope.addItem = function ()
{
$scope.products.push($scope.addMe);
}
});
</script>
<div ng-app="myShoppingList" ng-controller="myCtrl">
<ul>
<li ng-repeat="x in products">{{x}}</li>
</ul>
<input ng-model="addMe">
<button ng-click="addItem()">Add</button>
</div>
Angular Components:
Components are the main building blocks for Angular applications which consists of
An HTML template that declares what renders on the page.
Expressions:
AngularJS binds data to HTML using Expressions. They can be written inside double
braces: {{ expression }} or inside a directive: ng-bind="expression". They can contain literals, operators,
and variables.
Example:
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="">
<p>My first expression: {{ 5 + 5 }}</p>
</div>
</body>
</html>
Output:
Without the ng-app directive, HTML will display the expression as it is, without solving it.
My first expression: {{ 5 + 5 }}
Data Binding:
Data binding in AngularJS is the synchronization between the model and the view. AngularJS
applications usually have a data model, which is a collection of data available for the application.
I) HTML View:
The HTML container where the AngularJS application is displayed, is called the view. The view has
access to the model, and there are several ways of displaying model data in the view. The “ng-
bind directive” is used to bind the innerHTML of the element to the specified model property.
When data in the model changes, the view reflects the change, and when data in the view changes,
the model is updated as well. This happens immediately and automatically, which makes sure that the
model and the view is updated at all times.
Example:
Output:
Built-in Directives:
These are classes that include additional behaviour to elements in your angular applications.
Custom Directives:
Custom directives are used in AngularJS to extend the functionality of HTML. they are defined
using "directive" function. A custom directive simply replaces the element for which it is activated.
AngularJS application during bootstrap finds the matching elements and do one time activity using its
compile() method of the custom directive then process the element using link() method of the custom
directive based on the scope of the directive. AngularJS provides support to create custom directives for
following type of elements.
Element directives − Directive activates when a matching element is encountered.
Attribute − Directive activates when a matching attribute is encountered.
CSS − Directive activates when a matching css style is encountered.
Comment − Directive activates when a matching comment is encountered.
Example:
<html>
<head>
<title>Angular JS Custom Directives</title>
</head>
<body>
<h2>AngularJS Sample Application</h2>
<div ng-app = "mainApp" ng-controller = "StudentController">
<student name = "Mahesh"></student><br/>
<student name = "Piyush"></student>
</div>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
</script>
<script>
var mainApp = angular.module("mainApp", []);
mainApp.directive('student', function() {
var directive = {};
directive.restrict = 'E';
directive.template = "Student: <b>{{student.name}}</b>,
Roll No: <b>{{student.rollno}}</b>";
directive.scope = {
student : "=name"
}
directive.compile = function(element, attributes) {
element.css("border", "1px solid #cccccc");
var linkFunction = function($scope, element, attributes) {
element.html("Student: <b>"+$scope.student.name +"</b>,
Roll No: <b>"+$scope.student.rollno+"</b><br/>");
element.css("background-color", "#ff00ff");
}
return linkFunction;
}
return directive;
});
mainApp.controller('StudentController', function($scope) {
$scope.Mahesh = {};
$scope.Mahesh.name = "Mahesh Parashar";
$scope.Mahesh.rollno = 1;
$scope.Piyush = {};
$scope.Piyush.name = "Piyush Parashar";
$scope.Piyush.rollno = 2;
});
</script>
</body>
</html>
Output:
In AngularJS, a service is a function, or object, that is available for, and limited to, your
AngularJS application. AngularJS has about 30 built-in services. Some of them are as follows:
i) $location:
Has methods which return information about the location of the current web page.
Example:
var app=angular.module('myApp',[]);
app.controller('customersCtrl', function($scope, $location)
{
$scope.myUrl =$location.absUrl();
});
Example:
var app=angular.module('myApp',[]);
app.controller('myCtrl', function($scope,$http){
$http.get("welcome.htm").then(function (response){
$scope.myWelcome =response.data;
});
});