Web Fundamentals: Internet & HTML Basics
Web Fundamentals: Internet & HTML Basics
4. Communication Process:
Communication between web clients and servers relies on the HTTP
protocol. A web server, upon execution, notifies the operating system of its
readiness to accept incoming connections through a specific port. Web clients
(browsers) establish connections, send requests and data, receive information,
and then close the connection.
5. Server Characteristics:
Web servers share common characteristics, regardless of origin or
platform. The file structure typically includes two main directories - the document
root (housing accessible web documents) and the server root (storing the server
and support software).
6. Document Retrieval Process:
Clients access documents through top-level URLs, with servers mapping
requested URLs to the document root. Virtual document trees allow servers to
store documents outside the document root, accommodating growing collections.
9. Apache:
Apache, originating from the NCSA server httpd, is popular for its speed,
reliability, and open-source nature. Managed by a large team of volunteers,
Apache is especially favored for Linux systems, reading configuration
information from files.
10. IIS:
Microsoft's IIS, bundled with Windows, dominates on Windows platforms.
Unlike Apache's configuration file control, IIS is managed through a window-
based program, the IIS snap-in, enabling site managers to modify server
parameters.
Definition of URIs:
URL Formats:
URL Components:
URL Paths
Path Structure:
Type Specifications:
Request Phase:
Response Phase:
Security
Security Challenges:
Conclusion
The historical context of HTML and XHTML, detailing their evolution,
challenges, and the emergence of HTML5. It also discusses the ongoing choice
between HTML and XHTML, emphasizing the importance of standards and
syntax rules.
BASIC SYNTAX
Tags and Elements
• Tags: Tags are fundamental syntactic units in HTML used to specify
content categories. They are enclosed in angle brackets (< and >) and
written in lowercase letters. Most tags appear in pairs, with an opening tag
and a closing tag.
• Elements: The combination of an opening tag, its corresponding closing
tag, and the content between them is called an element. Elements form
containers for the specified content.
• Example:
o <p> This is simple stuff. </p>
Attributes
• Attributes: Attributes are used to specify alternative meanings of a tag.
They are written between the opening tag name and the right-angle bracket.
Attributes are in keyword form, with the attribute's name followed by an
equals sign and the attribute's value. Attribute values must be enclosed in
double quotes.
• Example:
o <a href="[Link] [Link]</a>
Comments
• HTML Comments: Comments in HTML are written between <!-- and --
>. They are for human readability and are ignored by browsers. Comments
can span multiple lines.
• Example:
▪ <!-- This is a comment in HTML -->
o Informational Comments: Comments play a crucial role in making
HTML documents more understandable. They can provide information
about the purpose of specific sequences of markup.
Ignored Text
o Unrecognized Tags: Browsers ignore unrecognized tags in HTML.
o Line Breaks: Browsers ignore line breaks unless specified with
appropriate tags.
o Multiple Spaces and Tabs: Similar to line breaks, browsers ignore extra
spaces and tabs unless specified using appropriate tags.
HTML as Suggestions
o HTML vs. Programs: HTML tags are treated more like suggestions to the
browser rather than explicit instructions. Unlike programs, misspelled tags
are often ignored by browsers without indicating an error to the user.
o Browser Configuration: Browsers have the flexibility to ignore
recognized tags or react differently to specific tags based on user
configurations.
Conclusion
This section introduces the foundational concepts of HTML syntax,
emphasizing tags, elements, attributes, and comments. It also highlights the
browser's flexibility in handling HTML content and the role of comments in
improving document readability.
Conclusion
This section presents the fundamental structure of an HTML document,
emphasizing the required elements (`<html>`, `<head>`, `<title>`, `<meta>`, and
`<body>`) and their respective roles in organizing and displaying content. It also
highlights the importance of formatting for readability purposes.
Basic Text Markup
This section discusses how text content in the body of an HTML document
can be formatted using HTML tags. The following elements are covered:
Paragraphs
Text is typically organized into paragraphs using the <p> (paragraph)
element. The browser automatically provides line breaks, and multiple spaces are
condensed to a single space.
Example:
<p>
Mary had
a
little lamb, its fleece was white as snow. And
everywhere that
Mary went, the lamb
was sure to go.
</p>
Line Breaks
The <br> (break) tag is used to create explicit line breaks within text. It
does not have a closing tag, and in XHTML, it can be written as <br />.
Example:
<p>
Mary had a little lamb, <br />
its fleece was white as snow.
</p>
Preserving White Space
The <pre> (preformatted text) element preserves white space, including
multiple spaces and line breaks. The content of <pre> is displayed in a monospace
font.
Example:
<pre>
Mary
had a
little
lamb
</pre>
Headings
Headings are specified using <h1> to <h6>, where <h1> is the highest-
level heading. Headings break the current line and usually appear in bold, with
varying font sizes.
Example:
<h1> Aidan's Airplanes (h1) </h1>
<h2> The best in used airplanes (h2) </h2>
<!-- ... Other headings ... -->
Block Quotations
Long quotations are set off using the <blockquote> element, which is often
indented on both sides.
Example:
<blockquote>
<p>
"Fourscore and seven years ago our fathers brought forth on
this continent, a new nation, conceived in Liberty, and
dedicated to the proposition that all men are created equal."
</p>
<!-- ... Other paragraphs ... -->
</blockquote>
Character Entities
HTML provides special character entities (e.g., < for < and € for
€) to represent characters that cannot be typed directly.
Horizontal Rules
The <hr /> (horizontal rule) element is used to insert a horizontal line
between document sections.
IMAGES
The inclusion of images in an HTML document can significantly improve
its visual appeal, though it may impact the document's download speed. The two
most common image formats are GIF and JPEG, with GIF supporting
transparency and JPEG offering superior compression. PNG is a newer format
with advantages of both GIF and JPEG, but it may result in larger file sizes.
Image Formats
o GIF (Graphic Interchange Format): Supports 8-bit color, allowing 256
different colors. Files have a .gif extension.
o JPEG (Joint Photographic Experts Group): Supports 24-bit color,
enabling more than 16 million colors. Files have .jpg, .jpeg, or .JPG
extensions.
o PNG (Portable Network Graphics): Developed as a free replacement for
GIF and JPEG, offering features of both formats. Files have a .png
extension.
The Image Element
o The <img> element is an inline element used to display images. It includes
the following attributes:
o src: Specifies the file containing the image.
o alt: Specifies text to be displayed when the image cannot be shown.
Optional attributes:
o width and height: Specify the size of the image in pixels.
o width="%": Specifies the width as a percentage of the display width.
Example:
<img src="images/[Link]" alt="Image description" />
<img src="[Link]" height="200" width="200" alt="Picture of a Cessna
210" />
HYPERTEXT LINKS
Hypertext links, specified using the <a> (anchor) element, enable
navigation within and across HTML documents. The <a> element is an inline
element and is used to create clickable links. The essential attribute for creating
links is href (hypertext reference), specifying the target of the link.
Linking to Documents
The href attribute points to the target document. For documents in the same
directory, only the document's name is needed. For documents in other
directories, Unix path conventions are used.
Example:
<a href="[Link]">Information on the Cessna 210</a>
Linking with Images
Links can include images in their content. The image is displayed along
with the textual link.
Example:
<a href="[Link]">
<img src="[Link]" alt="An image of a small airplane"
/> Information on the Cessna 210</a>
An image itself can serve as a link, with the content of the anchor element being
just the image element.
Targets within Documents
To link to a specific element within a document, use the id attribute. The
target element can be specified using the href attribute with a pound sign (#)
followed by the id.
Example:
<a href="#avionics">What about avionics?</a>
If the target is in another document, append the id value to the end of the URL
with a pound sign (#).
Example:
<a href="[Link]#avionics">Avionics</a>
Using Links
o Links are commonly used to create a table of contents within a document,
allowing users to navigate quickly to various parts.
o Design links to blend into the text, avoiding distractions. A well-designed
link should provide additional information without disrupting the reading
flow.
LISTS, TABLES, FORMS
Lists in HTML
HTML facilitates the creation and presentation of lists, offering three
primary types: unordered lists, ordered lists, and definition lists.
Unordered Lists
Unordered lists are crafted with the <ul> (unordered list) element, and each
list item is defined using <li> (list item). This type of list is suitable for items
where the order is not essential, such as a list of aircraft models:
<ul>
<li>Cessna Skyhawk</li>
<li>Beechcraft Bonanza</li>
<li>Piper Cherokee</li>
</ul>
Ordered Lists
When the order of items is crucial, ordered lists come into play. Employing
the <ol> (ordered list) element and <li> for list items, an ordered list provides a
sequential structure. For instance, instructions for starting a Cessna 210 engine
could be presented as:
<ol>
<li>Set mixture to rich</li>
<li>Set propeller to high RPM</li>
<li>Set ignition switch to "BOTH"</li>
<!-- ... other steps ... -->
</ol>
Nested ordered lists are achievable by placing a nested list within an <li> element.
Definition Lists
Definition lists, constructed with the <dl> (definition list) element, are
ideal for presenting terms and their corresponding definitions. The terms are
defined using <dt> (definition term), and the definitions with <dd> (definition
description). An example related to single-engine Cessna airplanes could be:
<dl>
<dt>152</dt>
<dd>Two-place trainer</dd>
<dt>172</dt>
<dd>Smaller four-place airplane</dd>
<!-- ... other terms and definitions ... -->
</dl>
TABLES IN HTML
Tables play a crucial role in presenting information effectively on the web.
HTML provides features for creating tables, which are matrices of cells
containing diverse content. This discussion covers the basic tags, attributes, and
best practices associated with HTML tables.
Conclusion:
HTML tables are powerful tools for organizing and presenting data.
Understanding their tags, attributes, and best practices ensures effective use
without resorting to deprecated practices such as tables for layout, which can lead
to unnecessary complexity and performance issues.
FORM IN HTML
✓ Form is used to collect user input. The user input is most often sent to a
server for processing.
✓ HTML provides tags to generate the commonly used objects on a screen
form. These objects are called controls or widgets or components.
▪ Form Element
▪ The input Element
▪ The Select Element
▪ The text area Element
Form Element (<form>):
▪ Acts as a container for form controls.
▪ Attributes include action (URL where form data is sent) and method (GET
or POST).
Input Element (<input>):
▪ Used for various form controls like text, password, checkboxes, radio
buttons, etc.
▪ Requires a type attribute to specify the control type.
▪ Additional attributes such as name, placeholder, and required can be used.
Select Element (<select>):
▪ Creates a dropdown list for users to choose from.
▪ Contains nested <option> tags that define individual options within the list.
Textarea Element (<textarea>):
▪ Allows users to input multiline text.
▪ Attributes include rows and cols to set the visible size of the textarea.
Form Submission:
▪ Form data is processed on the server and requires a "Submit" button.
▪ The action attribute in the <form> tag specifies the server URL.
▪ The method attribute determines how data is transmitted (GET or POST).
GET vs. POST:
▪ GET appends form data to the URL, visible in the address bar.
▪ POST sends form data in the request body, more secure for sensitive
information.
▪ action and method attributes control form data transmission.
Input Types:
▪ Various input types include text, password, checkboxes, radio buttons,
buttons, URLs, email addresses, and range (numeric input).
Validation:
▪ Textbox contents often need validation to ensure data integrity.
▪ Client-side validation is done to avoid sending invalid data to the server.
▪ Server-side validation is essential for security.
Checkbox and Radio Controls:
▪ Checkboxes collect on/off selections; radio buttons allow a single choice
from a group.
▪ Each control needs a name attribute, and checkboxes have a value attribute.
Menus (<select>):
▪ Dropdown lists for multiple-choice options.
▪ Size and multiple attributes control the display and selection behavior.
Textarea (<textarea>):
▪ Allows multiline text input, useful for longer pieces of information.
▪ Attributes like rows and cols determine the visible size.
Action Buttons (<input type="submit/reset">):
▪ Submit button sends form data to the server.
▪ Reset button clears form controls to their initial states.
Image Button:
▪ Alternative to the Submit button, where an image is the clickable area.
Example of a Complete Form:
▪ Demonstrates a sales order form for popcorn with textboxes, a table for
orders, radio buttons for payment methods, and action buttons.
Accessibility:
▪ Labels improve accessibility; use <label> to associate controls with
descriptive text.
▪ Properly labeled controls assist users and support assistive technologies.
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Sample Form</title>
</head>
<body>
<h2>Sample Form</h2>
<form action="#" method="POST">
<!-- Text Input -->
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<br>
Here's a breakdown of the key components and attributes associated with the
<audio> element:
Syntax:
<audio controls>
<source src="audio_file.mp3" type="audio/mp3">
Your browser does not support the audio element.
</audio>
Attributes:
controls: This attribute adds audio controls like play, pause, and volume to
the <audio> element. It is commonly used, as in the example, as
controls="controls" or just controls.
Source Elements:
Inside the <audio> element, you use one or more <source> elements to
specify the source of the audio files. Each <source> element should include the
src attribute, pointing to the URL of the audio file, and the type attribute,
indicating the MIME type of the file.
Fallback Content:
The text "Your browser does not support the audio element." is included
between the opening and closing <audio> tags. This text is displayed if the
browser does not support the <audio> element.
Browser Compatibility:
Different browsers support different audio container/codec combinations.
Multiple <source> elements allow you to provide alternative audio formats, and
the browser will choose the first one it supports.
Example:
<audio controls>
<source src="audio_file.ogg" type="audio/ogg">
<source src="audio_file.mp3" type="audio/mp3">
Your browser does not support the audio element.
</audio>
In this example, the browser will attempt to play the Ogg file first and fall back
to the MP3 file if Ogg is not supported.
Notes:
▪ Always include alternative audio formats to ensure compatibility across
different browsers.
▪ Be mindful of the file formats and codecs supported by various browsers
(as mentioned in your provided text).
▪ The <audio> element provides a simple and standardized way to integrate
audio into web pages, enhancing the overall user experience.
THE VIDEO ELEMENT
The <video> element in HTML5 is used to embed video content directly
into web pages, providing native support for video playback without the need for
external plugins. It allows you to include video files in various formats, enhancing
the multimedia capabilities of web documents. Here's an explanation of the key
aspects associated with the <video> element:
Syntax:
<video width="600" height="500" autoplay controls preload>
<source src="video_file.mp4" type="video/mp4">
<source src="video_file.ogv" type="video/ogg">
<source src="video_file.webm" type="video/webm">
Your browser does not support the video element.
</video>
Attributes:
▪ width and height: These attributes set the dimensions of the video player
on the page.
▪ autoplay: This attribute, when present, specifies that the video should start
playing automatically as soon as it is ready.
▪ controls: When present, this attribute adds video controls (play, pause,
volume) to the video player.
▪ preload: This attribute tells the browser to load the video file(s) as soon as
the document is loaded. It may not be suitable if not all users will play the
video.
▪ loop: If present, this attribute specifies that the video should play
continuously in a loop.
Source Elements:
Inside the <video> element, you use one or more <source> elements to
specify the source of the video files. Each <source> element should include the
src attribute, pointing to the URL of the video file, and the type attribute,
indicating the MIME type of the file.
Fallback Content:
The text "Your browser does not support the video element." is included
between the opening and closing <video> tags. This text is displayed if the
browser does not support the <video> element.
Browser Compatibility:
Different browsers support different video container/codec combinations.
Multiple <source> elements allow you to provide alternative video formats, and
the browser will choose the first one it supports.
Example:
<video width="600" height="500" autoplay controls preload>
<source src="video_file.mp4" type="video/mp4">
<source src="video_file.ogv" type="video/ogg">
<source src="video_file.webm" type="video/webm">
Your browser does not support the video element.
</video>
In this example, the browser will attempt to play the MP4 file first and fall back
to Ogg and WebM if MP4 is not supported.
Notes:
▪ Provide alternative video formats for broader browser compatibility.
▪ Be aware of the file formats and codecs supported by different browsers
(as mentioned in your provided text).
▪ The <video> element simplifies the process of integrating video content
into web pages, making it more accessible and user-friendly.
ORGANIZATION ELEMENTS
In HTML5, several elements have been introduced to improve the
organization of displayed information. Here's an explanation of some of these
organization elements:
<header> Element:
The <header> element is used to represent introductory content at the
beginning of a section or a page. It often contains headings, logos, and other
elements related to the section or document. For example:
<header>
<h1>The Podunk Press</h1>
<h2>"All the news we can fit"</h2>
</header>
<hgroup> Element:
The <hgroup> element is used to group multiple heading elements (<h1>,
<h2>, etc.) when they are part of a heading. It's useful for situations where
additional information precedes the main heading. For example:
<hgroup>
<header>
<h1>The Podunk Press</h1>
<h2>"All the news we can fit"</h2>
</header>
<!-- Additional content like a table of contents -->
</hgroup>
<footer> Element:
The <footer> element is used to represent footer content in a document. It's
commonly used for information like copyright details and authorship. For
example:
<footer>
© The Podunk Press, 2012
<br />
Editor in Chief: Squeak Martin
</footer>
<section> Element:
The <section> element is used to represent a generic section of a document.
It's often used to encapsulate chapters of a book or separate parts of a paper. For
example:
<section>
<!-- Content of the section -->
</section>
<article> Element:
The <article> element is used to represent a self-contained part of a
document, often coming from an external source. It can include a header, footer,
and sections. For example:
<article>
<header>
<!-- Article header content -->
</header>
<!-- Main content of the article -->
<footer>
<!-- Article footer content -->
</footer>
</article>
<aside> Element:
The <aside> element is used for content that is tangential or related to the
main information in the document. It's often used for sidebars. For example:
<aside><!-- Content related to the main information --></aside>
<nav> Element:
The <nav> element is used to represent a navigation section, typically
containing lists of links to different parts of the document or other documents. It
helps in marking navigation areas, especially useful for accessibility. For
example:
<nav>
<!-- Navigation links -->
</nav>
Example:
<!DOCTYPE html>
<!-- [Link]: An example to illustrate organization elements of HTML5
-->
<html lang="en">
<head>
<title>Organization elements</title>
<meta charset="utf-8" />
</head>
<body>
<hgroup>
<header>
<h1>The Podunk Press</h1>
<h3>"All the news we can fit"</h3>
</header>
<ol>
<li>Local news</li>
<li>National news</li>
<li>Sports</li>
<li>Entertainment</li>
</ol>
</hgroup>
<p>
<!-- Placeholder for the paper's content -->
<!-- Put the paper's content here -->
</p>
<footer>
© The Podunk Press, 2012
<br />
Editor in Chief: Squeak Martin
</footer>
</body>
</html>
Explanation:
The actual content of the paper should be placed inside the <p> element. The
provided HTML serves as a template, and you can replace the placeholder text
with the actual content for each section.
These elements provide a more semantic and structured way to organize content
in HTML documents.
THE TIME ELEMENT
The time element in HTML5 is used to timestamp an article or a document.
It consists of a textual part for human readability and a machine-readable part.
The machine-readable part is represented by the datetime attribute, while the
human-readable part is the content of the element.
▪ The content: The content inside the time element is the human-readable
representation of the date and time. In this example, it is "February 14,
2011 8:00am MDT". The information in the content is not necessarily
related to the information in the datetime attribute.
▪ Time zone offset: The datetime attribute can include a time zone offset,
represented as an offset in the range of –12:00 to +14:00 from Coordinated
Universal Time (UTC). For example, "2011-02-14T08:00-06:00" indicates
a time zone offset of UTC-6:00.
It's important to note the limitations of the time element: it cannot represent years
before the beginning of the Christian era (negative years are not acceptable), and
it does not allow for approximations (e.g., "circa 1900").
UNIT – 2
1. Inline Style Sheets: These are style definitions that are applied
directly within the HTML elements using the style attribute. They have the
lowest level of precedence and only affect the specific element they are applied
to. While convenient for individual element styling, they can lead toscattered and
unmanageable style definitions within the document.
example: An inline style sheet is defined directly within an HTML
element using the style attribute. It affects only that specific element.
<p style="color: blue; font-size: 16px;">This is a blue and larger font-size
paragraph. </p>
2. Document-level Style Sheets: These style sheets are defined within the
<style> tags in the <head> section of an HTML document. They apply to the
entire content of the document, providing a consistent style throughout.
Document-level styles have a higher precedence than inline styles, allowing
them to override properties defined inline.
example: A document-level style sheet is placed within the <style> tags
in the <head> section of an HTML document. It applies to the entire content of
the document.
<!DOCTYPE html>
<html>
<head>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f0f0f0;
}
h1 {
color: red;
}
</style></head>
<body>
<h1>This is a red heading</h1>
<p>This is a paragraph with the default font family.</p>
</body>
</html>
3. External Style Sheets: External style sheets are separate files with a
.css extension that contain style rules. They are linked to HTML documents
using the <link> element within the <head> section. External style sheets
provide the highest level of separation between content and style, making it
easier to maintain and apply consistent styles across multiple documents. They
have the lowest precedence, allowing them to be overridden by both inline and
document-level styles.
example: An external style sheet is a separate .css file that is linked to
HTML documents using the <link> element in the <head> section.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="[Link]">
</head>
<body>
<h1>This is a green heading</h1>
<p>This is a paragraph with the default font family.</p>
</body>
</html>
/* [Link] */
body {
font-family: Verdana, sans-serif;
background-color: #ffffff;
}
h1 {
color: green;
}
Precedence and Conflict Resolution:
When conflicting style rules are encountered for a specific element,the
following precedence order is followed:
• Inline styles take precedence over document-level styles.
• Document-level styles take precedence over external style sheets.
• Lower-level style sheets (inline and document-level) have precedenceover
higher-level style sheets (external).
In the case of conflicting property values for an element, the value specifiedin the
lower-level style sheet will be applied.
Advantages of External Style Sheets:
• They promote separation of concerns by keeping CSS separate from
HTML markup.
• They allow for consistent styling across multiple documents.
• They enhance maintainability and ease of updates.
It's important to note that inline style sheets, while useful for specific element
customization, can lead to code redundancy and are generally discouraged for
large-scale styling. Document-level and external style sheets are preferred for
more organized and maintainable styles.
When using external style sheets, they can be validated using tools like the W3C
CSS Validator.
Remember that browser defaults are used when no specific style is definedin any
of the style sheets.
STYLE SPECIFICATION FORMATS
The format of a style specification depends on the level of the style sheet
being used. Inline style specifications appear as values of the "style" attribute of
a tag. The general form of this attribute is as follows:
style = "property_1: value_1; property_2: value_2; ...; property_n:
value_n;"
Although it is not mandatory, it is recommended that the last property-value pair
be followed by a semicolon.
1. An alternative to using the <link> tag for importing stylesheets is
the @import rule. However, it's worth noting that the @import rule
tends to be slower in loading styles, so there is usually no good
reason to use it.
2. The "style" attribute is deprecated in the XHTML 1.1
recommendation. However, it is still a valid part of HTML5.
Document style specifications appear as the content of a <style> element within
the <head> section of an HTML document. The format of the specification is
quite different from that of inline style sheets. The general form of the content
of a <style> element is as follows:
<style type="text/css">
rule_list
</style>
The "type" attribute of the <style> tag informs the browser about the type
of style specification being used, which is typically set to text/css for CSS.
Each style rule within a rule list consists of two parts: a selector, which
specifies the element or elements affected by the rule, and a list of property-value
pairs. The list has a similar structure to that of inline style sheets, but it is
enclosed within curly braces. The form of a style rule is as follows:
selector {
property_1: value_1;
property_2: value_2;
...
property_n: value_n;
}
If a property is assigned multiple values, these values are generally
separated by spaces. However, some properties require multiple values to be
separated by commas.
Just like any other form of coding, complex CSS rule lists should be
documented with comments. Since HTML comments cannot be used within CSS,
a different form of comment is required. CSS comments are introduced using /*
and terminated with */, as shown in the following example:
<style type="text/css">
/* Styles for the initial paragraph */
...
SELECTOR FORMS
A selector in Cascading Style Sheets (CSS) specifies the elements to
which a particular style should be applied. Selectors come in various forms, each
serving different purposes.
Here are examples to illustrate the different selector forms mentioned in your
provided text within the context of a hypothetical HTML and CSS scenario:
1. Number Values:
Number values represent integers or decimal numbers with an optional
sign (+ or -). For instance, font-size: 14px; sets the font size to 14 pixels.
2. Length Values:
Length values, like width, are numbers followed by a unit abbreviation
(e.g., px, in, cm, mm, pt, pc). For instance, margin-left: 10mm; sets a left margin
of 10 millimeters.
3. Percentage Values:
Percentage values are relative to a previous measure, often used for
scaling. For example, width: 50%; sets the element's width to 50% of its parent's
width.
4. URL Values:
URL property values are enclosed in parentheses after the url keyword,
e.g., background-image: url([Link]);.
5. Color Values:
Color property values can be color names, hexadecimal numbers, or RGB
format. For instance, color: red;, background-color: #336699;, and border-color:
rgb(255, 0, 0); set the text color, background color, and bordercolor, respectively.
6. Inheritance:
Some property values are inherited by descendant elements. For example,
setting font-size on the <body> tag affects the font size of all elements within
the body. However, not all properties are inherited. For instance, background-
color and margin properties are not inherited.
Example HTML and CSS:
Html code:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="[Link]">
</head>
<body>
<h1>Welcome to Property-Value Examples</h1>
<p class="normal">This is a normal paragraph.</p>
<p class="warning">This is a warning paragraph.</p>
</body>
</html>
CSS Stylesheet ([Link]):
/* Number Values */
h1 {
font-size: 24px;
}
/* Length Values */
[Link] {
margin-left: 20px;
}
/* Percentage Values */
[Link] {
width: 75%;
}
/* URL Values */
body {
background-image: url([Link]);
}
/* Color Values */p
{
color: blue;
background-color: #FFD700; /* Gold */ border:
2px solid rgb(0, 128, 0); /* Green */}
Outuput:
FONT PROPERTIES
CSS provides various font properties to control the appearance of text on a
web page. These properties include font-family, font-size, font-variant,font-style,
font-weight, text-decoration, letter-spacing, word-spacing, and line-height.
1. Font-Family:
The font-family property specifies the font to be used for text. Multiple
font names can be provided as alternatives in case the browser doesn't support
the first choice. For example:
p { font-family: Arial, Helvetica, sans-serif;}
2. Font-Size:
The font-size property determines the size of the font. It can be specified
in absolute units like pixels (px), points (pt), or relative units like percentages
(%) or em. For example:
h1 {
font-size: 24px;
}
3. Font-Variant:
The font-variant property controls the display of capital letters. It canbe
set to small-caps to display small capital letters:
[Link] {
font-variant: small-caps;}
4. Font-Style:
The font-style property sets the style of the font, such as italic or
oblique:
em {
font-style: italic;}
5. Font-Weight:
The font-weight property determines the thickness of the font. Valueslike
bold, normal, and numeric values from 100 to 900 are available:
strong {
font-weight: bold;
}
6. Text-Decoration:
The text-decoration property adds special features to text, likeunderlining
or strike-through:
a:hover {
text-decoration: underline;
}
7. Letter-Spacing:
The letter-spacing property controls the space between letters in a
word: [Link]
{
letter-spacing: 1px;
}
8. Word-Spacing:
The word-spacing property adjusts the space between words:
[Link] {
word-spacing: 5px;}
9. Line-Height:
The line-height property specifies the space between lines of text:
[Link] { line-height: 1.5;}
Example HTML and CSS:
Html code
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="[Link]">
</head>
<body>
<p class="capital">This text has small capital letters.</p>
<em>This text is italicized.</em>
<strong>This text is bold.</strong>
<a href="#">Hover over me</a>
<p class="tracked">This text is spaced out.</p>
<p class="spaced">These words are spaced apart.</p>
<p class="poetry">Lines of poetry<br>with adjusted spacing.</p>
</body>
</html>
CSS Stylesheet ([Link]):
p{
font-family: Arial, Helvetica, sans-serif;
font-size: 16px;
}
/* Additional styles for different properties */
Output:
This text has small capital [Link]
text is italicized.
This text is bold.
Hover over me
This text is spaced out.
These words are spaced apart.
Lines of poetry
with adjusted spacing.
LIST PROPERTIES:
Two presentation details of lists can be specified in HTML documents:
the shape of the bullets that precede the items in an unordered list and the
sequencing values that precede the items in an ordered list. The list-style-type
property is used to specify both of these. If list-style-type is set for a <ul> or an
<ol> tag, it applies to all the list items in the list. If a list- style-type is set for an
<li> tag, it only applies to that list item.
Explanation:
In the output, the unordered list items have square bullets, and the ordered
list items are sequenced using upper-roman numerals for the first level, upper-
alpha letters for the second level, and decimal numerals for thethird level.
COLOR PROPERTIES IN WEB DOCUMENTS
Over the last decade, the issue of color in Web documents has become
much more settled. In the past, one had to worry about the range of colors client
machine monitors could display, as well as the range of colors browsers could
handle. Now, however, there are few color limitations with the great majority of
client machine monitors and browsers.
Color Groups: There are three groups of predefined colors that were designed
for Web documents:
1. The original group of seventeen named colors, which included far too few
colors to be useful.
2. A group of 147 named colors that are widely supported by browsers.
3. The so-called Web palette, which includes 216 named colors that wereonce
the only predefined colors widely supported by browsers. Contemporary
professional Web designers are more likely to define their own colors.
Output:
When displayed by a browser, the text "To really make it stand out, use a
magenta background!" will appear with blue font color and a magenta
background color, as shown in the example.
Explanation:
The color property sets the color of the text, while the background- color
property sets the background color of the element. In the provided example, the
paragraph with class "standout" has blue text color and a magenta background
color.
ALIGNMENT OF TEXT IN WEB DOCUMENTS
The presentation of text in web documents can be further enhanced by
adjusting its alignment and indentation. CSS provides properties to control these
aspects and improve the visual layout of content.
Text Indentation
The text-indent property is used to indent the first line of a paragraph.
This property accepts length or percentage values. For instance:
Example Markup ([Link]):
<style type="text/css">
[Link] { text-indent: 2em; }
</style>
...
<p class="indent">
Now is the time for all good Web developers to begin using
cascading style sheets for all presentation details in their
documents. No more deprecated tags and attributes, just nice,
precise style sheets.
</p>
Output:
The text within the paragraph with the class "indent" will be indented by
2em (equivalent to two times the size of the current font), creating a visually
appealing layout.
Text Alignment
The text-align property is used to horizontally arrange text within an
element. Common keyword values are left, center, right, and justify.
Example Markup ([Link]):
<style type="text/css">
[Link]-align { text-align: center; }
</style>
...
<p class="center-align">
This text is centered horizontally.
</p>
Output:
The text within the paragraph with the class "center-align" will be
centered horizontally within its container.
Float Property
The float property is used to make text flow around elements likeimages.
It accepts values left, right, and none.
Example Markup ([Link]):
<!DOCTYPE html>
<html lang="en">
<head>
<title>The float property</title>
<meta charset="utf-8" />
<style type="text/css">
img { float: right; }
</style>
</head>
<body>
<p>
<img src="[Link]" alt="Picture of a Cessna 210" />
</p>
<p>
<!-- Text describing the Cessna 210 -->
</p>
</body>
</html>
Output:
In the example, the image with the class "float" is floated to the right,and the
text flows around it accordingly.
THE BOX MODEL IN CSS
The Box Model is a fundamental concept in CSS that defines how
elements are structured and spaced within a web page. It encompasses the
element's content, padding, border, and margin. These components work
together to determine the overall appearance and spacing of elements on a
webpage.
Output:
The examples illustrate how margins and padding create spacearound
elements and paragraphs, affecting their positioning and appearance within
the webpage.
Explanation:
The Box Model consists of content, padding, border, and margin. Borders
have styles, widths, and colors. Shorthand properties simplify border styling.
Margins and padding control spacing around elements. [Link]
demonstrates different margin and padding combinations.
BACKGROUND IMAGES
The background-image property is used to place an image in the
background of an element. For example, an image of an airplane might be an
effective background for text about the airplane. The following example,
back_image.html.
The provided HTML code demonstrates the use of background images in
combination with text. Here's the output of the given HTML code along with an
explanation:
Html code:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Background images</title>
<meta charset="utf-8" />
<style type="text/css">
body {
background-image: url(../images/[Link]);
background-size: 375px 300px;
}
p{
margin-left: 30px;
margin-right: 30px;
margin-top: 50px;
font-size: 1.1em;
}
</style>
</head>
<body>
<p>
The Cessna 172 is the most common general aviation
airplane
in the world. It is an all-metal, single-engine piston,
high-wing, four-place monoplane. It has fixed gear and is
categorized as a non-high-performance aircraft. The
current
model is the 172R.
<!-- ... (more text) ... -->
</p>
</body>
</html>
Explanation:
The given HTML code sets a background image for the entire body of the
document and places text over the background image.
The <style> block within the <head> section sets the background image
using the background-image property. It also specifies the dimensions of the
background image using the background-size property.
The <body> section contains a paragraph (<p>) element that contains text
about the Cessna 172 airplane. The text is indented from the left and right
margins and is also pushed down from the top margin.
The background image [Link] is tiled (repeated) to fill the
background of the entire body.
Output:
THE<SPAN> AND <DIV>TAGS:
The provided text explains the use of the <span> and <div> elements for
applying special font properties and styling sections of a document. Here's a
breakdown of the explanation and an example for each element:
CONFLICT RESOLUTION:
When different values for the same property are specified on the same
element in an HTML document, conflicts arise, and the browser needs to
resolve them. The process of conflict resolution involves considering various
factors such as the origin, specificity, and importance of the style declarations.
Here's an explanation with an example:
Output:
The key takeaway is that while JavaScript can be embedded directly or indirectly
in HTML documents, proper syntax, commenting, and code organization are
crucial for compatibility and avoiding unexpected behavior, especially in older
browsers.
Certainly! Here's the example HTML document with a simple "Hello World"
message using JavaScript:
<!DOCTYPE html>
<!-- [Link]
A trivial hello world example of HTML/JavaScript
-->
<html lang="en">
<head>
<title>Hello world</title>
<meta charset="utf-8" />
</head>
<body>
<script type="text/javascript">
<!--
[Link]("Hello, fellow Web programmers!");
// -->
</script>
</body>
</html>
In this example:
• The <!DOCTYPE html> declaration defines the document type and
version.
• HTML comments (<!-- ... -->) are used for documentation within the
HTML.
• The <html> tag represents the root of an HTML document.
• The <head> section contains metadata like the document title and character
set.
• The <body> section contains the content of the document.
• The <script> tag embeds JavaScript code. The type attribute specifies the
script type as "text/javascript."
• The JavaScript code inside the <script> tag uses the [Link]
method to output the message "Hello, fellow Web programmers!" to the
document.
This is a minimal example to demonstrate the integration of JavaScript within an
HTML document. It showcases the basic structure and syntax for creating a
simple dynamic web page.
These primitive data types are the building blocks of JavaScript programs. They
are passed by value (copied) when assigned to variables, making each variable
independent of the others. Additionally, JavaScript has special objects that are
closely related to some primitive types, such as the Number, String, and Boolean
objects. These objects provide additional methods and properties for working
with primitive values.
However, in most cases, developers use the primitive forms (like 'Hello') rather
than the object forms (like new String('Hello')) for simplicity and efficiency.
Assignment Operators
1. Assignment =: Assigns the value of the right operand to the left operand.
a. let x = 10; // x is assigned the value 10
2. Compound Assignments (+=, -=, *=, /=): Perform the operation and then
assign the result to the left operand.
a. let num = 5;
b. num += 3; // num is now 8 (equivalent to num = num + 3)
Comparison Operators
Type Operators
EXPRESSIONS
Arithmetic Expressions:
Comparison Expressions:
Logical Expressions:
• function square(x) {
return x * x;
}
• let result = square(4); // Calling the function
Assignment Expressions:
• let x = 10;
• x += 5; // Equivalent to x = x + 5
SCREEN OUTPUT AND KEYBOARD INPUT
The process of handling screen output and keyboard input in JavaScript
involves interacting with the Document Object Model (DOM) and using various
methods provided by the Document and Window objects. Let's delve into these
aspects:
The Document object has a method called write() that is used to dynamically
create HTML document content. For example:
let result = 42;
[Link]("The result is: ", result, "<br />");
In this example, the write() method is used to create content in the HTML
document dynamically.
The Window object in JavaScript includes three methods that create dialog
boxes for user interactions:
3. prompt(): Opens a dialog window with a text box for user input, returning
the entered value.
a. let name = prompt("What is your name?", "");
These methods can be used for debugging or for interactive user experiences.
They cause the browser to wait for user input.
These examples illustrate how JavaScript can interact with users, receive input,
and dynamically create content within an HTML document.
CONTROL STATEMENTS
Control statements in JavaScript are essential for managing the flow of a
program based on specific conditions. These statements allow developers to make
decisions and execute different blocks of code depending on whether a given
condition is true or false. There are primarily two types of control statements:
Conditional Statements and Iterative Statements.
There are several methods that can be used to perform control statements
in JavaScript.
• If Statement
• Using If-Else Statement
• Using Switch Statement
• Using the ternary operator (conditional operator)
• Using For loop
1. Conditional Statements:
a. If Statement:
Output:
b. If-Else Statement:
if (num > 0) {
[Link]("The number is positive.");
} else {
[Link]("The number is negative.");
}
Output:
2. Iterative Statements:
a. For Loop:
The for loop is a common iterative statement. It repeats a block of code for
a specified number of iterations.
for (statement 1; statement 2; statement 3) {
// Code here . . .
}
for (let i = 0; i <= 10; i++) {
if (i % 2 === 0) {
[Link](i);
}
}
Output:
10
3. Switch Statement:
let num = 5;
switch (num) {
case 0:
[Link]("Number is zero.");
break;
case 1:
[Link]("Number is one.");
break;
case 2:
[Link]("Number is two.");
break;
default:
[Link]("Number is greater than 2.");
}
Output:
4. Ternary Operator:
Output:
Objects in JavaScript can be created using the new keyword along with a
constructor function. Unlike some other programming languages, JavaScript
objects are not bound to specific types. The constructor both creates and
initializes the properties of the object.
// Creating an object using the Object constructor
var my_object = new Object();
In this example, my_object is initialized as a new, empty object using the Object
constructor. The properties of the object can be added dynamically.
In this example, my_car is created as an object with properties make and model
using object literal notation.
Nested Objects
In this example, the engine property of my_car is itself an object with properties
config and hp.
JavaScript provides a for-in loop, which is useful for iterating over the
properties of an object:
// Iterating over object properties
for (var prop in my_car) {
[Link]("Name: ", prop, "; Value: ", my_car[prop], "<br />");
}
This loop iterates over all properties of my_car, and for each iteration, prop takes
on the name of the property, allowing easy access to both the property name and
its value.
Arrays created using the constructor can have a specified length, while arrays
created using literal notation automatically adjust their length based on the
number of elements.
3. Array Methods
4. Two-Dimensional Arrays
Arrays offer a flexible and powerful way to organize and manipulate data in
JavaScript. They play a crucial role in various programming scenarios, including
data storage, manipulation, and iteration.
FUNCTION
JavaScript functions play a crucial role in structuring code and performing
specific tasks. Here are the fundamental concepts related to JavaScript functions,
followed by an example illustrating their usage.
1. Function Fundamentals
A function definition consists of a header and a body. The header includes
the reserved word function, the function name, and a list of parameters in
parentheses.
function add(a, b) {
// body of the function
return a + b;
}
• The body of a function is a compound statement that describes the actions
of the function.
• A return statement is used to return control from the function to the caller.
It may include an expression whose value is returned to the caller.
JavaScript functions are objects and can be treated as such. They can be assigned
to variables passed as parameters, and used as method references.
2. Local Variables
• Variables declared using var within a function have local scope, meaning
they are only visible within the body of the function.
• Undeclared variables are implicitly global, even if used within a function.
It is recommended to explicitly declare all variables using var to avoid
unexpected behavior.
3. Parameters
• Parameters in a function call are actual parameters, while those in the
function definition are formal parameters.
• JavaScript uses a pass-by-value parameter-passing method. Objects are
passed by reference, but changes to the reference itself (not the object it
points to) don't affect the caller.
• The arguments array provides access to all actual parameters, and its length
property indicates the number of parameters passed.
• Variable numbers of parameters can be handled using the arguments array.
4. Example: Computing Median
Let's consider an example of a JavaScript function that computes the median of
an array of numbers.
// Function to compute the median of an array
function median(list) {
[Link](function (a, b) { return a - b; });
if (list_len % 2 === 1)
return list[[Link](list_len / 2)];
else
return [Link]((list[list_len / 2 - 1] + list[list_len / 2]) / 2);
}
// Test driver
var my_list_1 = [8, 3, 9, 1, 4, 7];
var my_list_2 = [10, -2, 0, 5, 3, 1, 7];
This function sorts the array in ascending order and then calculates the median,
leaving the original array unchanged.
Median of [8, 3, 9, 1, 4, 7] is: 5.5
Median of [10, -2, 0, 5, 3, 1, 7] is: 3
Understanding these fundamentals is crucial for effective JavaScript
programming. Functions enhance code modularity, reusability, and readability,
making them a cornerstone of JavaScript development.
CONSTRUCTORS
Constructors in JavaScript are special functions that are used to create and
initialize objects. When a constructor is invoked using the new keyword, it creates
a new object and this variable inside the constructor refers to that newly created
object. Constructors are crucial in establishing a blueprint for objects, providing
a way to set initial properties and methods.
2. Delimiting Patterns
This searches for the pattern 'bits' in the string and returns the position.
• \d: Digit
• \D: Not a digit
• \w: Word character (alphanumeric)
• \W: Not a word character
• \s: White-space character
• \S: Not a white-space character
5. Quantifiers
Numeric and symbolic quantifiers allow repetition in patterns (e.g., {4}, *, +, ?).
6. Anchors
Anchors (^ and $) specify that a pattern must match at the beginning or end of a
string.
7. Pattern Modifiers
Example:
var str = "Having 4 apples is better than having 3 oranges";
var matches = [Link](/\d/g);
// matches is set to [4, 3]
This summary covers the key concepts of pattern matching using regular
expressions in JavaScript. If you have specific questions or need further
clarification, feel free to ask!
ERRORS IN SCRIPTS
[Link] in Scripts:
2. Debugging Assistance:
• Default settings for IE8 provide JavaScript syntax error detection and
debugging.
• IE9 and successors may have these features turned off by default. To enable
them, go to Tools/Internet Options > Advanced tab.
• Internet Explorer settings: Remove the check on "Disable script debugging
(Internet Explorer)" and set the check on "Display a notification about
every script error."
3. Debugging in Internet Explorer:
• IE8 shows syntax error detection and error messages with line and
character positions.
Example:
var row;
row = 0;
while(row != 4 {
[Link]("row is ", row, "<br />");
row++;
}
5. Chrome Browsers:
This summary covers the key points related to debugging JavaScript scripts,
including error detection and debugging tools in different browsers. If you have
specific questions or need further clarification, feel free to ask!
JAVASCRIPT AND XHTML DOCUMENTS
THE JAVASCRIPT EXECUTION ENVIRONMENT
The JavaScript execution environment is the context in which JavaScript
code is run, and it involves various objects and elements that facilitate the
interaction between JavaScript and the browser. Here are key components of the
JavaScript execution environment:
1. Window Object:
2. Document Object:
3. Global Variables:
• The forms array of the Document object contains all form elements in the
document.
• Each form has an elements array with references to individual form
elements.
• Form elements can be accessed and manipulated through JavaScript.
5. Object Hierarchy:
6. Execution Flow:
7. Error Handling:
8. Debugging Tools:
• The DOM has been developed by the W3C (World Wide Web Consortium)
to provide a standardized interface for interacting with HTML and XML
documents.
• DOM Level 3 (DOM 3) is the current approved version.
• DOM 0 refers to the version implemented in Netscape 3.0 and Internet
Explorer 3.0 browsers.
DOM Versions:
1. DOM 0:
a. Used by early browsers supporting JavaScript (Netscape 3.0 and IE
3.0).
b. Partially documented in the HTML 4 specification.
2. DOM 1:
a. First W3C DOM specification (October 1998).
b. Focused on the HTML and XML document model.
3. DOM 2:
a. Issued in November 2000.
b. Specified a style-sheet object model, document traversals, and a
comprehensive event model.
4. DOM 3:
a. Issued in 2004, focused on XML content models, document
validation, document views, and key events.
b. Not covered in this book.
Abstract Model:
Document Structure:
Purpose:
Resources:
The DOM is essential for web developers working with JavaScript to create
dynamic and interactive web pages. It provides a structured way to interact with
and manipulate the content of HTML and XML documents.
Certainly! Let's consider a simple example of how you can use JavaScript to
interact with the DOM. In this example, we'll create an HTML page with a button,
and when the button is clicked, it will change the content of a paragraph.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>DOM Interaction Example</title>
<style>
/* Some basic styling for demonstration purposes */
body {
font-family: Arial, sans-serif;
text-align: center;
margin: 50px;
}
button {
padding: 10px;
font-size: 16px;
}
p{
font-size: 18px;
color: green;
}
</style>
</head>
<body>
<script>
// JavaScript code to interact with the DOM
</body>
</html>
This example demonstrates the following:
1. Using [Link]:
a. var element = [Link]("elementId");
b. This method retrieves an element by its unique ID.
2. Using [Link]:
a. var elements = [Link]("className");
b. This method returns a collection of elements with the specified class
name.
3. Using [Link]:
a. var elements = [Link]("tagName");
b. This method returns a collection of elements with the specified tag
name.
4. Using [Link]:
a. var element = [Link]("CSS selector");
b. This method returns the first element that matches the specified CSS
selector.
5. Using [Link]:
a. var elements = [Link]("CSS selector");
b. This method returns a NodeList containing all elements that match
the specified CSS selector.
6. Using [Link]:
a. var elements = [Link]("name");
b. This method returns a collection of elements with the specified name
attribute.
You can navigate the DOM hierarchy using properties like parentNode,
childNodes, nextSibling, and previousSibling. For example:
Events:
1. User-Initiated Events:
a. Click: The user clicks the mouse button.
b. Mouseover/Mouseout: The mouse pointer enters/leaves an
element.
c. Keydown/Keypress/Keyup: A keyboard key is pressed/pressed and
released/released.
2. Document-Related Events:
a. Load: The HTML document or an external resource has finished
loading.
b. Unload: The user leaves the current page, and the document is about
to be unloaded.
c. Resize: The browser window is resized.
3. Form Events:
a. Submit: A form is submitted.
b. Change: The value of a form element changes.
c. Focus/Blur: An element gains/losses focus.
Event Handling:
JavaScript File([Link])
// An example to illustrate the load event
// The onload event handler
function load_greeting () {
alert("You are visiting the home page of \n" +
"Pete's Pickled Peppers \n" + "WELCOME!!!");
}
In this example:
1. The <body> element has an onload attribute set to "handleLoadEvent()".
This attribute specifies that the handleLoadEvent function should be
executed when the body is loaded.
2. The handleLoadEvent function, defined in the [Link] file, contains
JavaScript code that will be executed when the load event occurs. In this
case, it displays an alert indicating that the body has been loaded.
3. The JavaScript file ([Link]) is included in the <head> section of the
HTML document using the <script> tag.
4. When the HTML document is loaded in a web browser, the
handleLoadEvent function is triggered by the load event, and an alert is
shown to the user.
This is a simple example, and in practice, you might use the load event to perform
more complex tasks, such as initializing variables, making API requests, or
setting up event listeners for other elements on the page. The load event is just
one of many events that can be handled in the <body> element. Other events
include click, mouseover, keydown, etc., depending on the desired interaction or
behavior.
HANDLING EVENTS FROM TEXT BOX AND PASSWORD
ELEMENTS
Handling events from text boxes and password elements is crucial for
validating user input and ensuring data integrity. In the provided examples,
JavaScript is used to check and validate the input in real-time, providing
immediate feedback to users.
In the first example, the focus event is used to prevent changes to the total
cost in a coffee order form. This is done to ensure the integrity of the order before
submission.
In the second example, the focus and blur events are used to check and
verify passwords entered by the user. The chkPasswords function is triggered on
blur and form submission to ensure password consistency.
Event Propagation:
In the DOM 2 event model, when an event occurs, an event object
implementing the associated interface is implicitly passed to the event handler.
The event object contains properties with information related to the event.
Note: The DOM 2 event model can be mixed with the DOM 0 event model in a
document. The choice depends on convenience and compatibility considerations.
UNIT-4
DYNAMIC DOCUMENTS WITH JAVASCRIPT AND XML
INTRODUCTION
The passage you provided outlines the concept of Dynamic HTML (DHTML)
and its use in web development. Let me break down the key points:
DOM Event Models: The DOM 0 event model is predominantly used in the
examples, with an exception in Section 6.11, which utilizes the DOM 2 event
model. The choice depends on the specific requirements of the example. The
passage notes that the example using DOM 2 event model does not work with
IE8 but is compatible with IE9 and later versions, which support the DOM 2 event
model.
POSITIONING ELEMENTS
Introduction of CSS-P: The World Wide Web Consortium (W3C)
released Cascading Style Sheets–Positioning (CSS-P) in 1997, offering a solution
to the limitations of traditional HTML layout. CSS-P allows web developers not
only to position elements anywhere in a document but also to dynamically move
elements using JavaScript by changing the positioning style properties.
Positioning Properties in CSS: CSS-P introduces several positioning
properties, including left, top, and position. The left and top properties dictate the
distance from the left and top of a reference point to where an element should
appear. The position property has three possible values: absolute, relative, and
static.
1. Absolute Positioning: Specifies that an element should be placed at a
specific location in the document display without regard to the positions of
other elements. Example:
<p style="position: absolute; left: 100px; top: 200px;">-- text --</p>
MOVING ELEMENT:
Using JavaScript to move an HTML element within a document by
dynamically changing its top and left CSS properties. Here's a breakdown of the
provided code:
HTML Structure ([Link]):
• The HTML file contains a form with two text input fields labeled 'x-
coordinate' and 'y-coordinate'. These fields allow users to input new
values for the left and top properties of an image.
• There's a button labeled 'Move it', which triggers the moveIt() function
when clicked.
• An image of Saturn is initially positioned absolutely within a <div>
element.
JavaScript Logic ([Link]):
• The moveIt() function is defined in the JavaScript file. This function
takes three parameters: the ID of the element to be moved (movee), the
new top position (newTop), and the new left position (newLeft).
• Inside the moveIt() function, it retrieves the DOM element to be moved
using [Link](movee).
• It then updates the top and left CSS properties of the specified element
with the new values obtained from the user input. The values are
concatenated with "px" to ensure they are interpreted as pixel units in
CSS.
HTML Structure ([Link]):
<!DOCTYPE html>
<html lang="en">
<head>
<title>Moving elements</title>
<meta charset="utf-8" />
<!-- Include the JavaScript file -->
<script type="text/javascript" src="[Link]"></script>
</head>
<body>
<!-- Form for user input -->
<form action="">
<p>
<!-- Text input for x-coordinate -->
<label>
x-coordinate:
<input type="text" id="leftCoord" size="3" />
</label>
<br />
<!-- Text input for y-coordinate -->
<label>
y-coordinate:
<input type="text" id="topCoord" size="3" />
</label>
<br />
<!-- Button to trigger the moveIt function -->
<input type="button" value="Move it" onclick="moveIt('saturn',
[Link]('topCoord').value,
[Link]('leftCoord').value)" />
</p>
</form>
<!-- Container div with initial absolute positioning -->
<div id="saturn" style="position: absolute; top: 115px; left: 0;">
<!-- Image of Saturn -->
<img src="../images/[Link]" alt="(Picture of Saturn)" />
</div>
</body>
</html>
JavaScript Logic ([Link]):
// Illustrates moving an element within a document
// The event handler function to move an element
function moveIt(movee, newTop, newLeft) {
// Get the style property of the element to be moved
var dom = [Link](movee).style;
After clicking the 'Move It' button with new coordinates entered, Figurewould
show the updated position of the Saturn image based on the user-inputted values
for top and left.
ELEMENT VISIBILITY
Document elements can be specified to be visible or hidden with the value
of their visibility property. The two possible values for visibility are, quite
naturally, visible and hidden. The appearance or disappearance of an element can
be controlled by the user through a widget. The following example displays an
image and allows the user to toggle a button, causing the image to appear and not
appear in the document display (once again, the event handler is in a separate
file):
// The event handler function to toggle the visibility of the image of Saturn
function flipImag() {
var dom = [Link]("saturn").style;
Explanation:
HTML Structure:
• The HTML file includes a form containing a <div> with an image of Saturn
initially set to visible.
• A button with the text "Toggle Saturn" triggers the flipImag() function
when clicked.
JavaScript Logic:
• The flipImag() function toggles the visibility of the Saturn image.
• It retrieves the style property of the element with the ID "saturn" using
[Link]("saturn").style.
• The visibility is toggled by checking the current visibility value. If it's
"visible," it changes it to "hidden," and vice versa.
This example demonstrates a basic way to use JavaScript to toggle the visibility
of an element in response to user interaction.
JavaScript ([Link]):
// [Link]
// Illustrates dynamic foreground and background colors
// The event handler function to dynamically set the color of background
or foreground
function setColor(where, newColor) {
if (where === "background") {
[Link] = newColor;
} else {
[Link] = newColor;
}
}
In this example:
• Users are presented with text boxes to input color values for the document's
background and foreground.
• JavaScript ([Link]) provides an event handler (setColor) that
changes either the background or foreground color based on user input.
JavaScript ([Link]):
// [Link]
// Illustrates dynamic font styles and colors
// The function to dynamically change font styles
function changeFont(element, color, style, size) {
[Link] = color;
[Link] = style;
[Link] = size;
}
In this example:
• The word "Washington" is styled with a specific font, color, and size
initially.
• JavaScript ([Link]) provides a function (changeFont) to dynamically
change the font color, style, and size when the mouse cursor hovers over
or leaves the word.
These examples illustrate how you can use JavaScript to dynamically manipulate
the appearance of elements in response to user interactions, providing a more
interactive and engaging user experience.
DYNAMIC CONTENT
We've explored dynamic changes like moving elements, changing
visibility, colors, background colors, and text font styles. Now, let's dive into
changing the content of HTML elements dynamically. The content of an element
is accessed through the value property of its associated JavaScript object. So,
altering the content is similar to changing style properties.
Consider a scenario where a user needs assistance filling out a form. An
associated text area, often referred to as a help box, can dynamically change its
content based on the element the cursor hovers over. For instance, when the cursor
is over a specific input field, the help box displays advice on how to fill in that
field. When the cursor moves away, the help box content changes to indicate
general assistance.
In the example below, an array of messages is defined in JavaScript to be
displayed in the help box. The mouseover event triggers a handler function that
changes the help box content to the appropriate message associated with the input
field. The mouseout event resets the content back to a standard message.
JavaScript ([Link]):
// [Link]
// Illustrates dynamic values
var helpers = [
"Your name must be in the form: \nfirst name, middle initial., last
name",
"Your email address must have the form: user@domain",
"Your user ID must have at least six characters",
"Your password must have at least six characters and it must include
one digit",
"This box provides advice on filling out the form on this page. Put the
mouse cursor over any input field to get advice"
];
STACKING ELEMENT
This web page utilizes HTML, CSS, and JavaScript to demonstrate
dynamic stacking of images. The stacking effect is achieved by manipulating the
z-index attribute, allowing elements to overlap in a three-dimensional space. The
z-index determines the stacking order, with higher values bringing elements to
the forefront.
HTML Structure:
• Three images (plane1, plane2, and plane3) are positioned using absolute
coordinates with initial z-index values set to 0.
• Each image has an onclick attribute triggering the toTop JavaScript
function, facilitating dynamic stacking.
JavaScript ([Link]):
• The toTop function is responsible for rearranging the stacking order.
• It receives the ID of the clicked image and updates the z-index values
accordingly.
• The global variable topp keeps track of the currently topmost image.
CSS Styles:
• Each image is styled with a specific class (plane1, plane2, plane3) defining
its initial position and z-index.
Example Execution:
• Initial Display (Figure 1): All images have a z-index of 0.
• After Clicking Second Image (Figure 2): The second image's z-index
becomes 10, bringing it to the top.
• After Clicking Bottom Image (Figure 3): The bottom image's z-index is set
to 10, placing it above the others.
• This dynamic stacking technique enhances user interaction, enabling the
user to bring different images to the forefront by clicking on them.
LOCATING MOUSE CURSOR COORDINATES EXAMPLE
This example demonstrates how to capture and display the coordinates of
the mouse cursor when a click event occurs. The provided HTML document
([Link]) includes two pairs of text boxes for displaying the clientX, clientY,
screenX, and screenY properties. The associated JavaScript file ([Link]) defines
an event handler to extract and present these coordinates.
HTML Structure ([Link]):
• Two pairs of text boxes are embedded in a form to display mouse cursor
coordinates.
• The findIt function is triggered by the onclick attribute of the <body>
element.
• An image is included to add visual interest to the webpage.
JavaScript ([Link]):
• The findIt function takes the event object (evt) as a parameter, capturing
mouse click details.
• Using getElementById, it updates the values of the text boxes with the
corresponding cursor coordinates (clientX, clientY, screenX, screenY).
Implementation Details:
• clientX and clientY represent coordinates relative to the upper-left corner
of the browser window.
• screenX and screenY represent coordinates relative to the client's computer
screen.
• The event object (evt) is implicitly created and passed to the handler
function by the onclick event.
HTML ([Link]):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Where is the cursor?</title>
<script type="text/javascript" src="[Link]"></script>
<style>
body {
display: flex;
align-items: center;
justify-content: center;
text-align: center;
height: 100vh;
margin: 0;
}
</style>
</head>
<body onclick="findIt(event)">
<form action="">
<p>
Within the client area: <br />
x: <input type="text" id="xcoor1" size="4" />
y: <input type="text" id="ycoor1" size="4" />
<br /><br />
Relative to the origin of the screen coordinate system: <br />
x: <input type="text" id="xcoor2" size="4" />
y: <input type="text" id="ycoor2" size="4" />
</p>
</form>
<p>
<img src="../images/[Link]" height="300" alt="(Picture of an
airplane)" width="450" />
</p>
</body>
</html>
JavaScript ([Link]):
// [Link]
// Show the coordinates of the mouse cursor position
// in an image and anywhere on the screen when the mouse
// is clicked
// The event handler function to get and display the
// coordinates of the cursor, both in an element and
// on the screen
function findIt(evt) {
[Link]("xcoor1").value = [Link];
[Link]("ycoor1").value = [Link];
[Link]("xcoor2").value = [Link];
[Link]("ycoor2").value = [Link];
}
Example Execution:
JavaScript ([Link]):
var element, targetX = 200, targetY = 200;
function initMovement() {
element = [Link]('movingElement').style;
moveElement();
}
function moveElement() {
var currentX = parseInt([Link]) || 50;
var currentY = parseInt([Link]) || 50;
XML
INTRODUCTION TO XML
XML, or eXtensible Markup Language, is a powerful tool for organizing
and sharing data. Let's break down its key points:
1. What is XML?
✓ XML is a meta-markup language, a tool for defining markup languages.
✓ Markup languages help structure and describe content in documents.
2. Origin and Standards:
✓ SGML (Standard Generalized Markup Language) was the precursor to
XML.
✓ In 1986, SGML became an ISO standard.
✓ HTML (Hypertext Markup Language) was developed based on SGML
for the web in 1990.
✓ In 1996, W3C started working on XML, a simplified version of SGML.
✓ The first XML standard (1.0) was published in 1998.
3. XML vs. HTML:
✓ HTML describes the layout of information on the web but lacks meaning.
✓ XML addresses this by allowing users to define their own markup
languages.
✓ XML focuses on representing data meaningfully, making it versatile.
4. XML Application:
✓ XML is not a replacement for HTML; it's a meta-markup language.
✓ HTML can be defined as an XML markup language.
✓ XML is a universal data interchange language for storing textual data.
5. XML Document:
✓ Documents using XML-based markup language are called XML
documents.
✓ XML documents can be written by hand or generated by programs.
✓ Universal readability makes XML ideal for data interchange.
6. XML Processing:
✓ XML processors analyze documents for applications before data access.
✓ Browsers need style sheets for displaying XML content.
✓ XML processors parse XML documents to extract elements, attributes,
and data.
7. Uses of XML:
✓ CDF for scalar and multidimensional data.
✓ SVG for scalable vector graphics.
✓ MathML for mathematical notation.
✓ CML for chemical information.
✓ GPX for GPS data.
✓ MML for medical information.
✓ OOXML for Microsoft Office formats.
✓ W3C-developed tag sets for web applications.
In essence, XML provides a standardized, readable, and universal way to
structure and exchange data. It's not just a markup language; it's a tool for
creating tailored markup languages to meet diverse data needs.
SYNTAX OF XML
XML syntax has two levels: low-level (basic rules for all documents) and
schemas (rules for specific documents). Let's focus on the basic syntax:
Low-Level Syntax:
✓ XML documents start with an XML declaration, specifying the version
and encoding.
✓ Comments are like HTML and can't have consecutive dashes.
✓ XML names (for elements and attributes) start with a letter or underscore,
case-sensitive, and can include digits, hyphens, and periods.
Document Structure:
✓ Every XML document has a single root element.
✓ Elements must be properly nested inside the root.
✓ XML tags, like HTML, use angle brackets.
✓ Elements with content must have closing tags; self-closing tags end with
/.
Attributes:
✓ XML tags can have attributes specified with name-value assignments.
✓ Attribute values must be enclosed in single or double quotes.
Well-Formed XML:
✓ An XML document adhering to syntax rules is considered well-formed.
Example:
<?xml version="1.0" encoding="utf-8"?>
<ad>
<year>1960</year>
<make>Cessna</make>
<model>Centurian</model>
<color>Yellow with white trim</color>
<location>
<city>Gulfport</city>
<state>Mississippi</state>
</location>
</ad>
Design Choices:
✓ Choose between adding attributes or defining nested elements.
✓ Attributes are great for identifiers or data from a set of possibilities.
✓ Nested elements are preferable when dealing with substructure or
growing complexity.
✓ Consider nested elements if data is subdata of the parent.
Example Choices:
Attribute Example:
<patient name="Maggie Dee Magpie">...</patient>
Nested Element Example:
<patient>
<name>Maggie Dee Magpie</name>
...
</patient>
Nested Element with Substructure:
<patient>
<name>
<first>Maggie</first>
<middle>Dee</middle>
<last>Magpie</last>
</name>
...
</patient>
Remember, simplicity and clarity guide your choice between attributes and
nested elements in XML design.
Document Entity:
Named Entities:
Entity Naming:
Entity References:
Predefined Entities:
Example Usage:
Instead of:
Important Note:
Entities help structure XML documents, and predefined entities handle common
characters. CDATA sections allow including special characters directly without
cluttering the content. Keep entity naming rules in mind for consistency.
In essence, XML Namespaces are like last names for XML elements, preventing
confusion when elements from different families (vocabularies) come together
in one document.
XML SCHEMAS
XML Schemas are like blueprints for XML documents, providing rules and
structures. Here's a simplified breakdown:
Purpose of Schemas:
• XML Schemas define elements, attributes, and structure rules for XML
documents.
• They ensure consistency and standardization in XML data.
Comparison to Classes and Objects:
• Schemas are akin to class definitions in object-oriented programming.
• An XML document following a schema is like an instance of that schema.
Namespace Centric:
• XML Schemas, like XML, use namespaces represented by URIs.
• Unique URIs, often starting with the author’s web address, prevent
conflicts.
Schema Declaration:
• Schemas are written using elements from the
[Link] namespace.
• The schema element is the root, specifying namespace and often a prefix.
• Example:
o <xsd:schema xmlns:xsd="[Link]
targetNamespace="[Link]
xmlns="[Link]
elementFormDefault="qualified">
Defining a Schema Instance:
• An instance must specify namespaces it uses in the root element.
• Example:
o <planes xmlns="[Link]
xmlns:xsi="[Link]
xsi:schemaLocation="[Link] [Link]">
Validation:
• XML documents are validated against XML Schemas for correctness.
• Validation programs, like xsv, ensure conformance to schema rules.
Schema Fundamentals:
• Schemas serve three primary purposes: element/attribute specification,
structure definition, and data type specification.
• XML Schemas are namespace-centric, using URIs for uniqueness.
Schema Instance Details:
• The schemaLocation attribute in an instance points to the schema file.
• Namespaces like xsi and xsd are used for schema-related declarations.
Example:
• A snippet of schema declaration:
o <xsd:schema xmlns:xsd="[Link]
targetNamespace="[Link]
xmlns="[Link]
elementFormDefault="qualified">
• A snippet of instance declaration:
o <planes xmlns="[Link]
xmlns:xsi="[Link]
xsi:schemaLocation="[Link] [Link]">
In essence, XML Schemas act as guardians, ensuring XML documents follow
predefined rules and maintain order and consistency.
1. Formatting Challenges:
• Viewing raw XML isn't a common practice and is mainly reserved for
document development stages.
• Internet Explorer (prior to IE9) might have restrictions on eliding;
Chrome, on the other hand, lacks a default style sheet.
• The raw XML display is a tool used by developers to review and check
the structure of a document during the development phase.
• It's not intended for regular consumption by end-users.
7. Browser-Specific Behaviour:
In essence, the raw display of XML serves as a developer's tool, offering an in-
depth look at the document's underlying structure and content during the
developmental stages. It's a practical way to inspect the XML markup before
finalizing the document for end-user consumption.
DISPLAYING XML DOCUMENTS WITH CSS
When presenting an XML document, style-sheet information can be added
to enhance its appearance. Cascading Style Sheets (CSS) provide a way to define
the style for XML elements, making the document more visually appealing.
Below is a simplified explanation of how to achieve this:
Develop a Cascading Style Sheet (CSS) file with style information for
XML elements. For instance, in the example below ([Link]), styles are
defined for elements like ad, year, make, model, etc.
ad { display: block; margin-top: 15px; color: blue;}
year, make, model { color: red; font-size: 16pt;}
color {display: block; margin-left: 20px; font-size: 12pt;}
description {display: block; margin-left: 20px; font-size: 12pt;}
seller { display: block; margin-left: 15px; font-size: 14pt;}
location {display: block; margin-left: 40px; }
city {font-size: 12pt;}
state {font-size: 12pt;}
Connect the XML document to the CSS style sheet using the xml-
stylesheet processing instruction. Include this line at the beginning of your XML
document.
This line specifies the type of style sheet (text/css) and the file name ([Link]).
Example:
[Link]:
/* CSS styles for elements in
[Link] */
ad { /* styles for ad element */ }
year, make, model { /* styles for year,
make, model elements */ }
color { /* styles for color element */ }
description { /* styles for description
element */ }
seller { /* styles for seller element */ }
location { /* styles for location element */ }
city { /* styles for city element */ }
state { /* styles for state element */ }
By following these steps, you can utilize CSS to format and enhance the display of XML documents,
making them more visually appealing and easier to understand. Note: Refer Lab Program 5
XSLT
XSLT (Extensible Stylesheet Language Transformations) is a powerful
technology developed by the W3C for transforming and styling XML documents.
It allows you to define rules for how XML data should be presented or
transformed into different structures, such as HTML or other XML formats.
Here's a simplified guide to understanding XSLT style sheets:
1. Basics of XSLT:
Rules in XSLT are defined using patterns to match elements in the source
XML document. Once matched, you can specify how to transform or present
those elements in the output.
Example:
<xsl:template match="book">
<!-- Transformation rules for book element -->
</xsl:template>
4. Output Specification:
You can define the structure and format of the output document using
elements like <xsl:element> and <xsl:attribute>.
Example:
<xsl:template match="book">
<div>
<h2><xsl:value-of select="title"/></h2>
<!-- Other content -->
</div>
</xsl:template>
5. Applying Templates:
Example:
<xsl:template match="library">
<html>
<body>
<xsl:apply-templates select="book"/>
</body>
</html>
</xsl:template>
6. Example:
<xsl:template match="book">
<div>
<h2><xsl:value-of select="title"/></h2>
<p>Author: <xsl:value-of select="author"/></p>
</div>
</xsl:template>
</xsl:stylesheet>
7. Applying XSLT:
To apply an XSLT style sheet to an XML document, you can use various
tools, APIs, or browsers that support XSLT transformations.
8. Output:
The result of applying the XSLT style sheet to your XML document
would be an HTML document with the transformed content.
XSLT provides a flexible and powerful way to transform and stylize XML data,
making it suitable for various scenarios such as converting XML to HTML for
web display or generating different XML structures.
WEB SERVICES
Web services allow different software applications, written in various
languages and residing on different platforms, to connect and work together. This
concept started gaining traction with Bill Gates introducing BizTalk in 1999, later
renamed .NET.
Basic Idea:
Key Standards:
• Developed using tools like Microsoft’s Visual Studio (VS) and Oracle’s
NetBeans.
OVERVIEW OF PHP
PHP is a server-side scripting language embedded in HTML, offering an
alternative to Java Server Pages and Active Server Pages. When a browser
encounters JavaScript in HTML, it uses a JavaScript interpreter. In contrast, if it
finds PHP script, the web server's PHP processor is called, identified by file
extensions like .php.
The PHP processor has two modes: copy mode and interpret mode. It reads
a PHP document, copies HTML code, and interprets PHP script, producing an
HTML output file. This file is sent to the browser, hiding the PHP script. PHP,
like JavaScript, is usually interpreted but may have some precompilation for
speed.
PHP shares syntax and semantics with JavaScript, making it easy to learn
for JavaScript users. It uses dynamic typing, meaning variable types are set when
assigned values. PHP is forgiving and supports both procedural and object-
oriented programming.
With a wide range of functions and extensive library support, PHP is
versatile for server-side development. Many functions provide interfaces to
systems like mail and databases, making PHP a powerful tool.
GENERAL SYNTACTIC CHARACTERISTICS
PHP scripts are either embedded in markup documents or stored in separate
files. In documents, PHP code is enclosed between <?php and ?> tags. To include
a script from another file, the include construct is used, like include("[Link]").
Variable names in PHP start with a dollar sign ($), followed by letters,
digits, or underscores. They are case-sensitive. Reserved words in PHP, like if,
while, and break, are not case-sensitive.
// Integer
$number = 42;
// Double
$floatNumber = 3.14;
// String
$text = "Hello, PHP!";
// Unsetting a variable
unset($number);
// Now $number is NULL
// Type Coercion
$numericContext = $unassignedVariable + 10; // NULL coerced to 0
$stringContext = "Value: " . $unassignedVariable; // NULL coerced to an
empty string
echo $numericContext . "\n"; // Outputs: 10
echo $stringContext . "\n"; // Outputs: Value:
?>
Variable Types and Type Conversions:
<?php
// Implicit Type Conversion
$integerValue = 10;
$doubleValue = $integerValue / 2; // Integer is coerced to double
echo $doubleValue . "\n"; // Outputs: 5
These examples cover the basics of scalar types, NULL, variable handling,
type coercion, and type conversions in PHP. Feel free to run these examples in a
PHP environment to see the output.
OUTPUT
• All output in PHP is part of HTML or XHTML, including embedded
client-side scripts.
• The print function is used for simple, unformatted output.
• It can be called with or without parentheses around its parameter.
Example:
<?php
// Using print for simple output
print "Some apples are red <br /> No kumquats are <br />";
This example displays a welcome message and the current day, month, and day
of the month using the date function. The date format is specified in the first
parameter of the date function.
CONTROL STATEMENTS
• PHP control statements (if, switch, while, for, do-while) are similar to
those in C and its descendants.
• Control expressions can be of any type, but they are coerced to Boolean.
• PHP has relational operators (>, <, >=, <=, !=, ==, ===, !==) for
comparisons.
• Boolean operators (and, or, xor, !, &&, ||) are available.
• Selection statements (if, switch) are used for conditional execution.
Examples:
Example 1 - If Statement:
<?php
$num = 5;
if ($num > 0)
$pos_count++;
elseif ($num < 0)
$neg_count++;
else {
$zero_count++;
print "Another zero! <b />";
}
?>
Example 2 - Switch Statement:
<?php
$bordersize = "4";
switch ($bordersize) {
case "0": print "<table>"; break;
case "1": print "<table border='1'>"; break;
case "4": print "<table border='4'>"; break;
case "8": print "<table border='8'>"; break;
default: print "Error-invalid value: $bordersize <br />";
}
?>
Example 3 - Loop Statements:
<?php
// While loop
$count = 1;
$sum = 0;
while ($count <= 100) {
$sum += $count;
$count++;
}
// Do-while loop
$count = 1;
$sum = 0;
do {
$sum += $count;
$count++;
} while ($count <= 100);
// For loop
for ($count = 1, $fact = 1; $count < $n;) {
$count++;
$fact *= $count;
}
?>
Example Document - HTML-PHP Integration:
<!DOCTYPE html>
<html lang="en">
<head>
<title>[Link]</title>
<meta charset="utf-8" />
<style type="text/css">
td, th, table {border: thin solid black;}
tr {text-align: center;}
</style>
</head>
<body>
<table>
<caption>Powers table</caption>
<tr>
<th>Number</th>
<th>Square Root</th>
<th>Square</th>
<th>Cube</th>
<th>Quad</th>
</tr>
<?php
for ($number = 1; $number <= 10;
$number++) {
$root = sqrt($number);
$square = pow($number, 2);
$cube = pow($number, 3);
$quad = pow($number, 4);
print("<tr> <td> $number </td>");
print("<td> $root </td> <td> $square </td>");
print("<td> $cube </td> <td> $quad </td> </tr>");
}
?>
</table>
</body>
</html>
This example generates an HTML table with mathematical calculations using
loops and functions.
ARRAYS
• Unique Structure: PHP arrays combine features of typical arrays and
associative arrays (hashes).
• Elements: Each array element has a key and a value.
• Key Types: Keys can be nonnegative integers or strings.
• Creation:
o Assignment: Creating an array by assigning values to specific
keys.
$list[0] = 17;
$list[1] = "Today is my birthday!";
o Array Construct: Creating an array using the array() construct.
$list = array(17, 24, 45, 91);
$ages = array("Joe" => 42, "Mary" => 41, "Bif" => 17);
Accessing Array Elements:
• Subscripting: Accessing individual elements using keys (subscripting).
$ages['Mary'] = 29;
• List Construct: Assigning multiple elements to scalar variables.
$trees = array("oak", "pine", "binary");
list($hardwood, $softwood, $data_structure) = $trees;
Functions for Dealing with Arrays:
• unset: Deleting array elements.
unset($list[2]);
• array_keys, array_values: Extracting keys and values from an array.
$days = array_keys($highs);
$temps = array_values($highs);
• array_key_exists: Checking if a key exists in an array.
if (array_key_exists("Tue", $highs)) {
$tues_high = $highs["Tue"];
}
• is_array: Checking if a variable is an array.
if (is_array($variable)) {
// It's an array.
}
• sizeof: Getting the number of elements in an array.
$len = sizeof($list);
• implode, explode: Converting between strings and arrays.
$str = implode(" ", $words);
$words = explode(" ", $str);
Sequential Access and Functions:
• Internal Pointer: Arrays have an internal pointer for sequential access.
• foreach: A loop to process all elements of an array.
foreach ($list as $temp)
print("$temp <br />");
Sorting Arrays:
• sort, asort, ksort: Sorting arrays by values or keys.
sort($new);
asort($new);
ksort($new);
FUNCTIONS
PHP supports user-defined functions that are typical of C-based
programming languages.
function name([parameters]) {
// function body
}
Parameters are optional, and function definitions can appear anywhere in
the document.
Return Statement:
• Used to specify the value to be returned to the caller.
• Function execution ends when a return statement is encountered or the last
statement in the function has been executed.
Include Function:
• Used to include function definitions from a separate file into a document.
• Helpful for reusing functions across multiple documents.
Parameters:
Actual vs. Formal Parameters:
• Actual parameters are used in the function call.
• Formal parameters are listed in the function definition.
• Number mismatch is allowed, supporting functions with a variable number
of parameters.
Passing by Value:
• Default parameter-passing mechanism.
• Values of actual parameters are copied into memory locations associated
with formal parameters.
• No changes to actual parameters.
Passing by Reference:
• Achieved by using an ampersand (&) with formal parameters or actual
parameters.
• Allows two-way communication, modifying actual parameters within the
function.
Scope of Variables:
Local Variables:
• Defined in a function and have local scope.
• Hidden from non-local variables with the same name.
• Changes to local variables don't affect non-local variables.
Global Declaration:
• Used to access non-local variables within a function.
• Global variables have the same meaning inside and outside the function.
Lifetime of Variables:
Static Local Variables:
• Specified using the static keyword in a function.
• Retains information across multiple function activations.
• Lifetime begins at the first use in the first execution of the function and
ends when the script execution ends.
PATTERN MATCHING
In PHP, there are two types of string pattern matching using regular
expressions: POSIX regular expressions and Perl-Compatible Regular
Expressions (PCRE). The preg_match function is used for pattern matching with
PCRE. Below is a brief overview and an example:
Using preg_match for Pattern Matching
The preg_match function takes two parameters:
1. Pattern: The Perl-style regular expression as a string.
2. Subject: The string to be searched.
Example:
if (preg_match("/^PHP/", $str)) {
print "\$str begins with PHP <br />";
} else {
print "\$str does not begin with PHP <br />";
}
This example checks if the string $str begins with "PHP" using a regular
expression.
Using preg_split for Splitting Strings
The preg_split function is used to split strings based on a pattern. It returns
an array of substrings.
Example:
$fruit_string = "apple : orange : banana";
$fruits = preg_split("/ : /", $fruit_string);
Here, the string $fruit_string is split into an array named $fruits using the
pattern " : ".
Example: Word Frequency Table
The following example demonstrates the use of preg_split to parse words
and create a frequency-of-occurrence table:
<?php
// Function splitter
function splitter($str) {
$freq = array(); // Empty word frequency array
$words = preg_split("/[ \.,;:!\?]\s*/", $str); // Split the string into words
foreach ($words as $word) {
$keys = array_keys($freq);
if (in_array($word, $keys)) {
$freq[$word]++;
} else {
$freq[$word] = 1;
}
}
return $freq;
}
Output:
Word Frequency
apples 3
are 1
better 1
don't 1
for 1
good 1
like 2
maybe 1
or 2
oranges 1
than 1
you 3
This script splits the input string into words, counts their frequencies, and displays
a word frequency table. The output shows each word and its occurrence
frequency.
FORM HANDLING
• To get form data, we need to use PHP superglobals $_GET and $_POST.
• The form request may be get or post. To retrieve data from get request, we
need to use $_GET, for post request $_POST.
Certainly! Below is an extended explanation and code example for PHP form
handling using both GET and POST methods. The example includes HTML form
files ([Link]) and corresponding PHP handling files ([Link] and
[Link]).
Explanation:
GET Request Example:
• A simple HTML form is created with a text input for the name.
• The form's action is set to "[Link]" with the method "get."
• The PHP script ([Link]) retrieves the name from the URL using
$_GET and displays a welcome message.
POST Request Example:
• Another HTML form is created with text inputs for name and password.
• The form's action is set to "[Link]" with the method "post."
• The PHP script ([Link]) retrieves the name and password using
$_POST and displays a welcome message.
Output:
COOKIES
A session in web development refers to the duration during which a user's
browser interacts with a specific server. Sessions start when a browser connects
to the server and end either when the browser is closed or due to server-defined
inactivity. Cookies, small pieces of information with names and values, play a
crucial role in managing sessions.
Common Uses of Cookies:
• Shopping Carts: Identify each user's shopping cart using session
identifiers stored in cookies.
• Personalization: Create visitor profiles to personalize user experiences
based on past interactions.
• Targeted Advertising: Store information about user preferences to deliver
targeted advertisements.
Cookie Lifetime:
• Cookies are assigned a lifetime, and when this duration expires,
the cookie is deleted from the browser.
• Every HTTP communication between a browser and a server
includes a header containing cookies.
• Cookies are exchanged exclusively between a specific browser
and a specific server.
Privacy Concerns:
• Cookies record browser activities, raising privacy concerns.
• Browsers allow users to reject cookies by changing settings,
limiting the effectiveness of cookies.
Deletion of Cookies:
• Users can delete cookies, although the process varies by browser.
PHP Support for Cookies
setcookie Function:
• PHP provides the setcookie function to create and manage cookies.
• Parameters:
• Name (mandatory): Cookie name as a string.
• Value (optional): New value for the cookie as a string. If absent, the
cookie is undefined.
• Expiration Time (optional): Lifetime of the cookie in seconds. Default
is zero, expiring at the end of the session.
• Example:
setcookie("voted", "true", time() + 86400);
This creates a cookie named "voted" with the value "true" and a lifetime of
one day.
Cookie Retrieval in PHP:
• Cookies and their values arriving with a request are stored in the
$_COOKIES array.
• Check if a cookie exists using the IsSet predicate function on the
associated variable.
Important Consideration:
• Cookie creation or modification must occur before any HTML is
generated in the PHP document, as cookies are stored in the HTTP
header.
Cookies in PHP are essential for managing sessions and storing information
between server and browser interactions. While widely used, it's crucial to
consider user privacy and browser settings that may reject or limit the
effectiveness of cookies.
SESSION TRACKING
Session tracking is a process used to manage information about a user's
session, particularly during the session's duration. Unlike cookies, which are
stored on the client-side, session tracking often involves the use of a session array
stored on the server. A unique session identifier is commonly used for tasks such
as shopping cart applications.
Key Points:
1. Purpose of Session Tracking:
• To manage information about a client during a session.
• Often involves storing a unique session ID in a session array.
2. Session ID in PHP:
• In PHP, a session ID is an internal value that identifies a session.
• PHP scripts become aware of session tracking by calling the
session_start function, which creates or retrieves a session ID.
• The session ID is created and recorded on the first call to
session_start in a session.
3. Session Arrays:
• Session arrays, stored on the server, hold information about previous
client requests during a session.
• Variables and their values registered in previously executed scripts
are stored in the $_SESSION array.
• Values can be created, changed, or destroyed using assignments and
the unset operator.
4. Example:
session_start();
$page_num = $_SESSION["page_number"];
echo "You have now visited $page_num page(s) <br />";
// Increment page_number
$_SESSION["page_number"]++;
• This example demonstrates session tracking for the number of pages
visited.
• If page_number is not set, it initializes it to 1; otherwise, it displays
the current count and increments it.
5. Session ID Handling:
• PHP manages session IDs internally, and scripts need not handle
them explicitly.
• Subsequent calls to session_start in the same session retrieve the
existing $_SESSION array.
To use jQuery, you need to include the jQuery library in your HTML document.
You can either download the library and host it on your server or include it
directly from a content delivery network (CDN). For example:
<!-- Include jQuery from a CDN -->
<script src="[Link]
Once included, you can start writing jQuery code in your JavaScript files or
directly in your HTML documents using script tags.
jQuery syntax
The jQuery syntax is tailor-made for selecting HTML elements and
performing some action on the element(s).
Basic syntax is: $(selector).action()
• A $ sign to define/access jQuery
• A (selector) to "query (or find)" HTML elements
• A jQuery action() to be performed on the element(s)
Examples:
• $(this).hide() - hides the current element.
• $("p").hide() - hides all <p> elements.
• $(".test").hide() - hides all elements with class="test".
• $("#test").hide() - hides the element with id="test".
1. `$(this).hide()`: This jQuery code hides the current HTML element that
triggers an event. It is often used in event handlers to hide the element that
triggered the event.
2. `$("p").hide()`: This jQuery code hides all `<p>` elements on the page.
It uses the "element" selector (`$("p")`) to select all paragraphs and then
applies the `hide()` action to hide them.
3. `$("[Link]").hide()`: This jQuery code hides all `<p>` elements with the
class "test". It uses the "class" selector (`$("[Link]")`) to select paragraphs
with the specified class and hides them.
4. `$("#test").hide()`: This jQuery code hides the HTML element with the
id "test". It uses the "id" selector (`$("#test")`) to select the element with
the specified id and hides it.
These examples illustrate the basic structure of jQuery syntax:
`$(selector).action()`. The dollar sign `$` is used to define jQuery, the `(selector)`
is used to select HTML elements, and the `.action()` is used to perform an action
on the selected element(s).
jQuery Selectors
• jQuery Selectors are used to select and manipulate HTML elements. They
are very important part of jQuery library.
• With jQuery selectors, you can find or select HTML elements based on
their id, classes, attributes, types and much more from a DOM.
• In simple words, you can say that selectors are used to select one or more
HTML elements using jQuery and once the element is selected then you
can perform various operation on that.
• All jQuery selectors start with a dollor sign and parenthesis e.g. $(). It is
known as the factory function.
Factory Function:
- jQuery selectors start with the factory function: `$()`. This function is used
to select and manipulate HTML elements.
Basic Selectors:
1. Tag Name:
- Example: `$("p")`
- Selects all `<p>` elements in the document.
2. Tag ID:
- Example: `$("#real-id")`
- Selects a specific element with the ID "real-id".
3. Tag Class:
- Example: `$(".real-class")`
- Selects all elements with the class "real-class".
Additional Selectors:
Filtering:
o `:first`, `:last`, `:even`, `:odd`
Child and Descendant:
o `:first-child`, `:first-of-type`, `:last-child`, `:last-of-type`
o `:nth-child(n)`, `:nth-last-child(n)`, `:nth-of-type(n)`, `:nth-last-of-
type(n)`
o `:only-child`, `:only-of-type`
Attribute Selectors:
o `[attribute]`, `[attribute=value]`, `[attribute!=value]`,
`[attribute$=value]`
o `[attribute|=value]`, `[attribute^=value]`, `[attribute~=value]`,
`[attribute*=value]`
Form Element Selectors:
o `:input`, `:text`, `:password`, `:radio`, `:checkbox`
o `:submit`, `:reset`, `:button`, `:image`, `:file`
State Selectors:
o `:enabled`, `:disabled`, `:selected`, `:checked`
Other Selectors:
o `:header`, `:animated`, `:focus`, `:contains(text)`, `:has(selector)`
o `:empty`, `:parent`, `:hidden`, `:visible`, `:root`, `:lang(language)`
$("div").mouseleave(function() {
// Code to be executed when the mouse leaves the div
});
Change Event:
Triggers when the value of an input element changes (for form
elements).
$("input").change(function() {
// Code to be executed when the input value changes});
Keydown, Keypress, and Keyup Events:
Triggered when a key on the keyboard is pressed, while it's being
pressed, or when it's released.
$("input").keydown(function() {
// Code to be executed when a key is pressed
});
$("input").keypress(function() {
// Code to be executed when a key is pressed and held down
});
$("input").keyup(function() {
// Code to be executed when a key is released
});
Submit Event:
Triggers when a form is submitted.
$("form").submit(function() {
// Code to be executed when the form is submitted
});
Focus and Blur Events:
Triggers when an element gains or loses focus.
$("input").focus(function() {
// Code to be executed when the input gets focus
});
$("input").blur(function() {
// Code to be executed when the input loses focus
});
Resize Event:
Triggers when the browser window is resized.
$(window).resize(function() {
// Code to be executed on window resize
});
Custom Events:
Besides the standard events, you can also create and trigger custom events using
jQuery.
Triggering a Custom Event:
$("#myButton").on("customEvent", function() {
// Code to be executed when the custom event is triggered
});
jQuery HTML
In jQuery, HTML manipulation involves dynamically changing or
updating the content and structure of HTML elements. jQuery provides methods
to easily select and modify HTML elements. Here are some common HTML
manipulation methods in jQuery:
Setting Content:
text() Method:
Sets or returns the text content of selected elements.
// Set text content
$("p").text("New text content");
// Remove a class
$("div").removeClass("oldClass");
// Toggle a class
$("p").toggleClass("highlight");
These jQuery methods make it easy to manipulate the HTML content and
structure dynamically, providing a more interactive and responsive user
experience on a web page.
jQuery EFFECT
jQuery provides a set of built-in effects that allow you to add animations
and transitions to your web page elements. These effects can enhance the user
experience and make the interface more dynamic. Here are some common jQuery
effects:
These are just a few examples of the many effects jQuery provides. Effects can
be combined, chained, and customized to create a wide variety of dynamic and
visually appealing interactions on your web page.
jQuery css()
In jQuery, the css() method is used to get or set the CSS properties of
HTML elements. It provides a convenient way to dynamically manipulate the
styling of elements on a web page. Here are examples of using the css() method
in various scenarios:
1. Setting CSS Properties:
Setting a Single Property:
// Example: Set the color of paragraphs to red
$("p").css("color", "red");
Setting Multiple Properties:
// Example: Set multiple CSS properties for a div
$("div").css({
"color": "blue",
"font-size": "16px",
"background": "#f0f0f0"
});
2. Getting CSS Properties:
Getting a Single Property:
// Example: Get the font-size of the first paragraph
var fontSize = $("p:first").css("font-size");
[Link]("Font Size: " + fontSize);
Getting Multiple Properties:
// Example: Get multiple CSS properties of an image
var imgProperties = $("img").css(["width", "height", "border"]);
[Link](imgProperties);
3. Modifying Existing Styles:
Modifying Existing Styles:
// Example: Increase the font-size of paragraphs by 2 pixels
$("p").css("font-size", function(index, value) {
return parseFloat(value) + 2 + "px";
});
4. Manipulating Classes:
Adding a Class:
// Example: Add a class to a div
$("div").addClass("highlight");
Removing a Class:
// Example: Remove a class from a div
$("div").removeClass("highlight");
Toggling a Class:
// Example: Toggle a class on a button click
$("button").click(function() {
$("div").toggleClass("highlight");
});
5. Chaining:
The css() method supports method chaining, allowing you to perform
multiple operations in a single line.
// Example: Chain multiple CSS operations
$("p")
.css("color", "green")
.css("font-weight", "bold")
.hide("slow");
These examples demonstrate how the css() method in jQuery can be used to
manipulate the styling of HTML elements, either by setting or retrieving CSS
properties. It provides a flexible and efficient way to dynamically update the
appearance of elements on your web page.
INTRODUCTION TO ANGULAR JS
<div ng-controller="myController">
<input type="text" ng-model="name">
<h1>Hello, {{ name }}</h1>
</div>
<script>
var app = [Link]('myApp', []);
[Link]('myController', function($scope) {
$[Link] = 'World';
});
</script>
</body>
</html>
This example creates a simple AngularJS application with a controller that
binds a variable name to an input field and displays a greeting message. As the
user types in the input field, the greeting message dynamically updates.
AngularJS has been widely used for building dynamic and interactive web
applications. However, it's important to note that AngularJS has reached its end
of life, and developers are encouraged to migrate to the newer versions of the
Angular framework for continued support and updates.
AngularJS DIRECTIVES
AngularJS directives are markers on a DOM element that tell AngularJS to
attach a specified behavior to that DOM element or transform the DOM element
and its children. Directives are a core feature of AngularJS, allowing developers
to extend HTML with new attributes and elements to create dynamic and reusable
components. Here are some commonly used AngularJS directives:
1. ng-app:
Defines the root element of an AngularJS application. It indicates the
starting point of the AngularJS application.
<div ng-app="myApp">
<!-- Your AngularJS application content goes here -->
</div>
2. ng-controller:
Attaches a controller to a DOM element, defining the controller's scope.
<div ng-controller="myController">
<!-- Controller-specific content goes here -->
</div>
3. ng-model:
Binds an HTML element (like an input field) to a property on the scope,
enabling two-way data binding.
<input type="text" ng-model="username">
4. ng-repeat:
Iterates over a collection (array or object) and repeats a set of HTML
elements for each item in the collection.
<ul>
<li ng-repeat="item in items">{{ [Link] }}</li>
</ul>
5. ng-click:
Specifies an expression to evaluate when an element is clicked.
<button ng-click="doSomething()">Click me</button>
6. ng-show and ng-hide:
Conditionally shows or hides an element based on the evaluation of an
expression.
<p ng-show="isVisible">This is visible</p>
<p ng-hide="isVisible">This is hidden</p>
7. ng-if:
Conditionally includes or excludes an element based on the evaluation of
an expression.
<div ng-if="isDisplayed">This is displayed</div>
8. ng-class:
Conditionally applies CSS classes based on the evaluation of an
expression.
<div ng-class="{ 'highlight': isHighlighted, 'italic': isItalic }">Styled
Text</div>
9. ng-src:
Binds the src attribute of an HTML element to an expression, typically used
with images.
<img ng-src="{{ imageUrl }}">
10. ng-disabled:
Disables or enables an HTML element based on the evaluation of an
expression.
<button ng-disabled="isDisabled">Click me</button>
11. ng-options:
Generates a dropdown list (<select>) based on the values of an array.
<select ng-model="selectedOption" ng-options="[Link] as
[Link] for item in options"></select>
These are just a few examples of the many directives available in AngularJS.
Directives play a crucial role in extending HTML to create dynamic, interactive,
and reusable components in AngularJS applications.
AngularJS Expressions
AngularJS expressions are JavaScript-like code snippets enclosed in
double curly braces ({{ }}). These expressions are used to bind data from the
AngularJS scope to the HTML and are evaluated against the current scope.
AngularJS expressions are commonly used to display data in the view, and they
support a subset of JavaScript expressions.
Here are some key points about AngularJS expressions:
1. Data Binding: AngularJS expressions provide two-way data binding
between the model (JavaScript variables in the scope) and the view (HTML
elements). When the model changes, the view is automatically updated,
and vice versa.
<p>{{ message }}</p>
2. Simple Expressions: Expressions can be as simple as displaying a
variable value.
<p>{{ username }}</p>
3. Arithmetic Operations: Basic arithmetic operations can be performed
in expressions.
<p>{{ num1 + num2 }}</p>
4. String Concatenation: Strings can be concatenated using expressions.
<p>{{ "Hello, " + username }}</p>
5. Object Property Access: You can access properties of objects defined
in the scope.
<p>{{ [Link] }}</p>
6. Array Access: You can access elements of an array using expressions.
<p>{{ myArray[0] }}</p>
7. Function Calls: You can call functions defined in the scope.
<p>{{ getGreeting() }}</p>
8. Conditional Statements: Expressions can include simple conditional
statements.
<p>{{ isLogged ? 'Welcome' : 'Please log in' }}</p>
9. Filters: AngularJS expressions support filters for formatting data.
<p>{{ dateValue | date:'dd/MM/yyyy' }}</p>
10. Expression Limitations: AngularJS expressions do not support certain
JavaScript features like loops, conditionals, and exceptions. They are
intentionally limited for security reasons.
Example:
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title>AngularJS Expressions</title>
<script
src="[Link]
></script>
</head>
<body ng-controller="myController">
<script>
var app = [Link]('myApp', []);
[Link]('myController', function($scope) {
$[Link] = 'AngularJS Expressions';
$scope.num1 = 5;
$scope.num2 = 10;
$[Link] = 'John';
$[Link] = { name: 'Jane' };
$[Link] = ['Apple', 'Banana', 'Orange'];
$[Link] = function() {
return 'Good morning';
};
$[Link] = true;
$[Link] = new Date();
});
</script>
</body>
</html>
In this example, AngularJS expressions are used to display various data and
perform simple operations in the view. The expressions are evaluated against the
AngularJS controller's scope.
AngularJS CONTROLLER
AngularJS controllers are JavaScript functions that manage the application
data and behavior. They are responsible for handling user input, updating the
model, and interacting with services.
Example 1: Basic AngularJS Controller
<!DOCTYPE html>
<html>
<script
src="[Link]
</script>
<body>
<script>
var app = [Link]('myApp', []);
[Link]('myCtrl', function($scope) {
$[Link] = "Elanchezhian";
$[Link] = "Muthukumar";
});
</script>
</body>
</html>
Explanation:
✓ ng-app="myApp" defines the AngularJS application named "myApp."
✓ ng-controller="myCtrl" associates the controller named "myCtrl" with the
specified <div>.
✓ $scope is the application object, and it holds variables (firstName and
lastName) and functions.
✓ ng-model binds input fields to controller properties.
✓ The {{firstName + " " + lastName}} expression displays the full name.
Example 2: AngularJS Controller with Methods
<!DOCTYPE html>
<html>
<script
src="[Link]
</script>
<body>
</div>
<script>
var app = [Link]('myApp', []);
[Link]('personCtrl', function($scope) {
$[Link] = "Elanchezhian";
$[Link] = "M";
$[Link] = function() {
return $[Link] + " " + $[Link];
};
});
</script>
</body>
</html>
Explanation:
✓ This example adds a method, fullName(), to the controller.
✓ The input fields are still bound using ng-model.
✓ The expression {{fullName()}} calls the fullName function to
display the full name.
External Controller File
You can store controllers in external files. Example file named
"[Link]":
[Link]('myApp', []).controller('personCtrl', function($scope) {
$[Link] = "Elan";
$[Link] = "M";
$[Link] = function() {
return $[Link] + " " + $[Link];
};
});
Include the external file in the HTML:
<!DOCTYPE html>
<html>
<script
src="[Link]
[Link]"></script>
<body>
<div ng-app="myApp" ng-controller="personCtrl">
First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{firstName + " " + lastName}}
</div>
<script src="[Link]"></script>
</body>
</html>
FILTERS:
AngularJS filters are used for formatting data in the view. They can be
applied to expressions in the view to modify the way data is displayed.
Example:
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title>AngularJS Filter Example</title>
<script
src="[Link]
></script>
</head>
<body ng-controller="myController">
<script>
var app = [Link]('myApp', []);
[Link]('myController', function($scope) {
$[Link] = new Date();
});
</script>
</body>
</html>
SERVICES:
AngularJS services are objects or functions that carry out specific tasks and
can be used throughout the application. They provide a way to organize and share
code across controllers.
Example:
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title>AngularJS Service Example</title>
<script
src="[Link]
></script>
</head>
<body ng-controller="myController">
<script>
var app = [Link]('myApp', []);
[Link]('greetingService', function() {
[Link] = function() {
return 'Hello from the Service!';
};
});
<head>
<title>AngularJS Events Example</title>
<script
src="[Link]
></script>
</head>
<body ng-controller="ParentController">
<div>
<h2>Parent Component</h2>
<button ng-click="broadcastEvent()">Broadcast Event</button>
</div>
<div ng-controller="ChildController">
<h2>Child Component</h2>
<div>{{ eventData }}</div>
</div>
<script>
var app = [Link]('myApp', []);
</body>
</html>
Explanation:
✓ There are two controllers: `ParentController` and `ChildController`.
✓ The `ParentController` broadcasts a custom event called `'customEvent'`
when a button is clicked.
✓ The `ChildController` listens for the `'customEvent'` and updates the view
with the received data.
Key Points:
✓ `$rootScope.$broadcast('eventName', eventData)` is used to broadcast an
event from a parent scope.
✓ `$scope.$on('eventName', function(event, args) { /* handle event */ })` is
used to listen for an event in a child scope.
✓ Events can carry data, and this data can be accessed through the `args`
parameter.
FORMS IN AngularJS:
AngularJS provides a robust framework for handling forms in web
applications. Forms consist of various input controls such as text fields,
checkboxes, radio buttons, select boxes, and more. The ng-model directive is
essential for achieving data-binding between these controls and the underlying
AngularJS application.
Input Controls:
Text Input:
<input type="text" ng-model="firstname">
The ng-model directive binds the input controller to the application's data,
creating a property named firstname.
Checkbox:
<input type="checkbox" ng-model="myVar">
Checkboxes have a boolean value (true or false). The ng-model directive
binds the checkbox value to the application.
Radio Buttons:
<form>
Pick a topic:
<input type="radio" ng-model="myVar" value="dogs"> Dogs
<input type="radio" ng-model="myVar" value="tuts"> Tutorials
<input type="radio" ng-model="myVar" value="cars"> Cars
</form>
Radio buttons with the same ng-model but different values allow selection
among multiple options.
Select Box:
<form>
Select a topic:
<select ng-model="myVar">
<option value="">Choose...</option>
<option value="dogs">Dogs</option>
<option value="tuts">Tutorials</option>
<option value="cars">Cars</option>
</select>
</form>
The ng-model directive binds the selected option's value to the myVar
property.
FORM VALIDATION:
AngularJS facilitates form validation to ensure data integrity. Validation
messages can be displayed using directives like ng-show based on the form's
state.
<input type="text" ng-model="firstname" required>
<div ng-show="[Link].$dirty &&
[Link].$[Link]">
First Name is required.
</div>
In this example, the error message is shown only when the field is dirty and the
required condition is not met.
FORM EXAMPLE:
Here's a complete example of an AngularJS form with data-binding and
validation:
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title>AngularJS Forms</title>
<script
src="[Link]
></script>
</head>
<body ng-controller="formCtrl">
<script>
var app = [Link]('myApp', []);
[Link]('formCtrl', function ($scope) {
$[Link] = {};
$[Link] = false;
$[Link] = function () {
if ($[Link].$valid) {
// Form submission logic can be added here
$[Link] = true;
}
};
});
</script>
</body>
</html>
In this example, the form includes text input, validation messages, and a submit
button. The submitted data is displayed after a successful form submission.