WEB Tech
WEB Tech
WEB Tech
Uses:
Purpose:
Features:
1. Markup Tags: Tags define page structure, like <p> for paragraphs.
2. Semantic Elements: HTML5 added meaningful tags like <header> and <footer>.
3. Attributes: Elements can have extra info, like <img src=""> for images.
4. Hyperlinks: <a> makes links to other pages.
5. Forms: Elements like <input> gather user info.
6. Multimedia Support: Embeds images, videos, and audio.
7. Cross-Browser Compatibility: Works well on different browsers.
Overall, HTML is the foundation for making web pages and is vital for web developers.
These are just a few of the most commonly used HTML tags. There are many more tags available
for various purposes and functionalities in HTML.
HTML program that uses some common tags:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple HTML Example</title>
</head>
<body>
<h1>Hello, World!</h1>
<p>This is a simple HTML example.</p>
<a href="https://www.example.com">Visit Example.com</a>
<img src="example.jpg" alt="Example Image" width="200">
</body>
</html>
1. Meaning: It's like a container for introductory content, such as logos, navigation, or branding. It
helps browsers and search engines understand the content's purpose.
2. Position: Normally, it's at the top of the page or section, before the main content. It often holds
things like a logo and navigation menu.
3. Content: You can put headings, paragraphs, menus, logos, or search forms in the <header>. What
goes in it depends on what's needed for the page or site.
4. Accessibility: Using <header> properly helps people with disabilities understand the content's
structure. Screen readers can easily recognize it.
5. Style and Layout: You can use CSS to make the <header> look nice and fit with the rest of the
page's design.
6. Nested Headers: You can put a <header> inside other elements like <article> or <section>,
making more complex structures while keeping things clear.
Here's a simple example of how the <header> tag might be used in an HTML document:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Example Website</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<header>
<h1>Example Website</h1>
<nav>
<ul>
<li><a href="#home">Home</a></li>
<li><a href="#about">About</a></li>
<li><a href="#services">Services</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
</nav>
</header>
<main>
<!-- Main content of the website goes here -->
</main>
<footer>
<!-- Footer content goes here -->
</footer>
</body>
</html>
In this example, the <header> tag contains the website's title (<h1>) and a navigation menu (<nav>),
providing essential introductory content and navigation links at the top of the page. This helps users quickly
navigate the website and understand its purpose.
The HTML <head> element is a container for metadata (data about data) and other information
about the HTML document. It contains elements such as <title>, <meta>, <link>, <style>, and
<script>, which provide important information about the document and its relationship with other
resources.
Here's a simple and short HTML program that demonstrates the use of the <head> element:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="description" content="A simple HTML page with a brief explanation.">
<meta name="keywords" content="HTML, tutorial, example">
<meta name="author" content="Your Name">
<title>Simple HTML Example</title>
<link rel="stylesheet" href="styles.css">
<script src="script.js" defer></script>
</head>
<body>
<h1>Hello, World!</h1>
<p>This is a simple HTML example.</p>
</body>
</html>
1. <meta charset="UTF-8">: Specifies the character encoding for the document (UTF-8).
2. <meta name="description" content="...">: Provides a brief description of the document for
search engines.
3. <meta name="keywords" content="...">: Specifies a list of keywords relevant to the document
for search engines.
4. <meta name="author" content="...">: Specifies the author of the document.
5. <title>Simple HTML Example</title>: Sets the title of the HTML document.
6. <link rel="stylesheet" href="styles.css">: Links an external CSS file (styles.css) to the
document for styling.
7. <script src="script.js" defer></script>: Links an external JavaScript file (script.js) to the
document and defers its execution until after the document has been parsed.
The <head> element is crucial for providing essential information about the HTML document, such
as its title, character encoding, metadata, stylesheets, and scripts.
<header>
<h1>Welcome to My Website</h1>
<nav>
<ul>
<li><a href="#about">About</a></li>
<li><a href="#services">Services</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
</nav>
</header>
<section id="about">
<h2>About Us</h2>
<p>We are a team of <strong class="important">passionate</strong> web developers...</p>
</section>
<section id="services">
<h2>Our Services</h2>
<ul>
<li>Web Development</li>
<li>Graphic Design</li>
<li>SEO Optimization</li>
</ul>
</section>
<section id="contact">
<h2>Contact Us</h2>
<p>Feel free to <a href="mailto:[email protected]" title="Email Us">email us</a> for any
inquiries.</p>
</section>
<footer>
<p>© 2024 Example Company. All rights reserved.</p>
</footer>
</body>
</html>
These CSS bits let you control how text looks on your webpage, making it attractive and organized.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Text Styling Example</title>
<style>
/* CSS styles for text */
p{
color: blue; /* Changes text color to blue */
font-family: Arial, sans-serif; /* Sets font family to Arial or sans-serif */
font-size: 16px; /* Sets font size to 16 pixels */
text-align: center; /* Aligns text to the center */
background-color: lightgray; /* Sets background color to light gray */
}
</style>
</head>
<body>
</body>
</html>
Website </a>
2. Absolute Links:
• Absolute links specify the complete URL of the destination resource, including the protocol (e.g.,
http://, https:// ).
• Example:
<a href="https://www.example.com">Visit Example Website</a>
Us </a>
4. Anchor Links (Internal Links):
• Anchor links are used to navigate within the same webpage by linking to specific sections of the
page.
• They use the href attribute with a fragment identifier ( #) followed by the ID of the target element.
• Example:
on Tit <a href="#section-id">Jump to Section</a>
...
le </h2>
5. Email Links:
• Email links are used to create links that, when clicked, open the user's default email client to
compose a new email.
• They use the mailto: protocol followed by the email address.
• Example:
<a href="mailto:[email protected]">Send Email</a>
1. src (source): This is a must-have attribute that tells the browser where to find the image.
• Example: <img src="image.jpg" alt="Example Image">
2. alt (alternative text): This gives a text description of the image for accessibility. It shows if
the image can't load or for visually impaired users.
• Example: <img src="image.jpg" alt="Alternative text for the image">
3. width: Optional attribute to set the image's width in pixels.
• Example: <img src="image.jpg" alt="Example Image" width="300">
4. height: Similar to width but sets the image's height.
• Example: <img src="image.jpg" alt="Example Image" height="200">
5. title: Extra info about the image, shows as a tooltip when hovering over it.
• Example: <img src="image.jpg" alt="Example Image" title="This is an example image">
6. loading: Optional attribute introduced in HTML5. Tells the browser how to load the image,
like lazy or eager.
• Example: <img src="image.jpg" alt="Example Image" loading="lazy">
1. Font Styles:
Bold Text: Use the <strong> tag or <b> tag to make text bold.
<strong>This text is bold</strong>
<b>This text is also bold</b>
Italic Text: Use the <em> tag or <i> tag to italicize text.
<em>This text is italic</em>
<i>This text is also italic</i>
Underlined Text: Use the <u> tag to underline text. However, this tag is not recommended for semantic reasons.
<u>This text is underlined</u>
2. Headings:
HTML provides six levels of headings, from <h1> (the most important) to <h6> (the least important). Headings
are used to structure content hierarchically.
<h1>This is a heading level 1</h1>
<h2>This is a heading level 2</h2>
<!-- And so on... -->
3. Text Alignment:
Use the align attribute within elements like <p>, <div>, or <table> to control text alignment. However, using
CSS is recommended for modern web development.
<p align="center">This text is centered</p>
<p align="right">This text is aligned to the right</p>
4. Font Attributes (Deprecated):
HTML used to support font-related attributes like size, face, and color. However, these attributes are deprecated
in HTML5 in favor of CSS for styling.
<font size="4" face="Arial" color="blue">Customized text</font>
5. Lists:
Strong Emphasis: Use the <strong> tag to denote stronger emphasis, typically displayed in bold.
Emphasis: Use the <em> tag for emphasized text, usually displayed in italic.
7. Superscript and Subscript:
Use the <sup> tag for superscript text and the <sub> tag for subscript text.
E=mc<sup>2</sup> <!-- Displays as E=mc² -->
H<sub>2</sub>O <!-- Displays as H₂O -->
These are some of the basic text formatting techniques in HTML. However, for more advanced and consistent
styling, it's recommended to use CSS (Cascading Style Sheets).
CSS allows for finer control over the presentation of HTML elements and promotes separation of concerns
between content and style.
lists
HTML provides different types of lists to organize and present information effectively. These
include ordered lists (<ol>), unordered lists (<ul>), nested lists, and description lists (<dl>).
1. Ordered Lists (<ol>): Ordered lists are used when the order of items matters. Each list item
(<li>) is automatically numbered, starting from 1 by default. You can customize the starting
number, change the numbering type (decimal, alphabetical, or Roman numerals), and even
reverse the numbering order.
<ol>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ol>
2. Unordered Lists (<ul>): Unordered lists are used when the order of items is not significant.
Each list item is marked with a bullet point by default. You can customize the bullet style
using CSS.
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
3. Nested Lists: Lists can be nested inside one another to represent sub-items. This is
achieved by placing one list inside another, typically as a child of a list item.
<ul>
<li>Item 1</li>
<li>Item 2
<ul>
<li>Sub-item 2.1</li>
<li>Sub-item 2.2</li>
</ul>
</li>
<li>Item 3</li>
</ul>
4. Description Lists (<dl>): Description lists consist of name-value pairs, where each name
(<dt>) is followed by one or more corresponding values ( <dd>).
<dl>
<dt>Name 1</dt>
<dt>Name 2</dt>
</dl>
These list types offer flexibility in organizing content and presenting information in a
structured manner on web pages. They serve different purposes based on the nature of the
data being presented.
Tables
HTML tables are used to organize data into rows and columns, making it easier to present
information such as text, images, and links in a structured format. They are commonly utilized in
various fields like data analysis, research, and communication. Here's a simplified overview of
HTML tables:
Basic Structure:
Tables in HTML are enclosed within the <table> tag, which serves as the main container. Within the
table, data is organized row by row.
Example:
<table>
<tr>
<th>Heading</th>
<th>Heading</th>
<th>Heading</th>
</tr>
<tr>
<td>Data</td>
<td>Data</td>
<td>Data</td>
</tr>
</table>
Table Components:
Key Tags:
• <table>: Main container for the table.
• <tr>: Defines a table row.
• <th>: Defines a table header.
• <td>: Defines a table data/cell.
Conclusion:
HTML tables are invaluable for organizing and presenting data in a structured format. By using rows and
columns, tables make it easier to comprehend complex information. They are commonly used in various
scenarios, including displaying student records, creating timetables, and presenting research findings.
HTML tables are used to display data in rows and columns on webpages. They are
constructed using various tags and attributes to customize their appearance and structure. Here's
a simplified breakdown of how tables are created and customized in HTML:
Basic Structure:
Example:
<table border="1" cellpadding="10" cellspacing="0" align="center">
<caption>Student Information</caption>
<tr>
<th>Name</th>
<th>Age</th>
<th>Grade</th>
</tr>
<tr>
<td>John</td>
<td>18</td>
<td>A</td>
</tr>
<tr>
<td>Jane</td>
<td>17</td>
<td>B</td>
</tr>
</table>
th, td {
padding: 10px;
border: 1px solid black;
}
caption {
font-weight: bold;
font-style: italic;
}
Output:
Student Information
---------------------------------
| Name | Age | Grade |
|------|-----|-------|
| John | 18 | A |
| Jane | 17 | B |
Conclusion:
HTML tables are versatile tools for displaying structured data on webpages. By using appropriate
tags and attributes, along with CSS for styling, you can create visually appealing and well-
organized tables to present information effectively.
The <pre> tag is used to define preformatted text. Text within this element is displayed in a fixed-width font
(usually Courier), and it preserves both spaces and line breaks
<pre>
Example:
The <blockquote> tag is used to define a section that is quoted from another source. Browsers usually indent
content within a <blockquote> .
Example:
<blockquote>
</blockquote>
These tags are used to create lists. <ul> creates an unordered list, <ol> creates an ordered list, and <li> defines
each list item.
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
<ol>
<li>First</li>
<li>Second</li>
<li>Third</li>
</ol>
The <table> tag is used to create tables in HTML. Tables allow for the presentation of information in rows and
columns.
Example:
<table border="1">
<tr>
</tr>
<tr>
</tr>
</table>
HTML attributes like align , valign , and width can be used within elements like <table>, <td>, <img> , etc., to control
alignment and spacing.
Example:
<tr>
</tr>
</table>
Conclusion:
While HTML itself does not provide specific "Tabs" or "Format" tags, it offers various elements and attributes to
structure and format content effectively. Additionally, CSS (Cascading Style Sheets) can be used to further control
the presentation and appearance of HTML content, including aspects like spacing, indentation, and alignment.
1. HTML Forms: Use <form> tags to create forms with various input fields like text boxes,
checkboxes, and buttons.
<form action="submit.php" method="post"> <input type="text" name="username"
placeholder="Username"> <input type="password" name="password" placeholder="Password"> <button
type="submit">Submit</button> </form>
2. Validation: Ensure data entered meets specific criteria using HTML attributes like "required" or
"pattern" or through JavaScript.
<input type="email" name="email" placeholder="Email" required>
3. JavaScript: Enhance form functionality with JavaScript for validation, dynamic updates, or fetching
data without refreshing the page.
4. Submission: Send form data to a server-side script for processing using the <form> tag's "action" and
"method" attributes.
<form action="submit.php" method="post"> <!-- Form fields --> </form>
5. AJAX: Use AJAX to send and receive data from the server asynchronously without page refresh,
useful for dynamic form handling.
6. Form Linking: Link between different sections or documents using hyperlinks, buttons, or
JavaScript event listeners, especially in multi-step forms.
7. Feedback and Error Handling: Provide feedback to users after form submission or during data
entry, ensuring accessibility for all users.
By integrating these elements, you can create complex form interactions in HTML for a better user
experience.
In HTML documents, it becomes important to specify some additional features about the data/content of the
website being entered. The meta tag is used enter meta data (basic information about the HTML webpage)
about the content on an HTML page. The meta tag is declared within the head tag. This is used to specify
specific properties of the HTML document. To know more about the head tag, check out this article.
Used to specify character encoding for the HTML document. This is nothing but a process
charset
of representing individual characters based on an encoding scheme
Used to provide an HTTP header for the value of the content attribute. This is significant
http-equiv
in identifying HTML documents.
Used to specify a name for the metadata. This is significant in naming the HTML
name
document's meta data specifics.
Used to specify the value of the attribute. This is used to signify what content is actually
content
held by the document.
The meta tag is used to describe the meta data for an HTML document. Meta data can be said to be
additional information that tells us more about the data in the HTML document. The meta tag is used to
specify features such as page portrayals, specific Keywords, document's author's name, viewport
settings, character sets etc. These meta tag properties help in SEO ranking the web page on a browser,
Conclusion
1. Meta tags are used to provide extra information about the HTML document
2. Meta tags can be used to set author names, cookie settings, viewport settings etc.
3. Themeta tag is declared within the head tag.
4. Meta tags are used for search engine optimization.
explain in detail of Dynamic HTML and its uses
Dynamic HTML (DHTML) combines HTML, CSS, and JavaScript to make web pages interactive
without reloading. Here's a simpler breakdown:
1. HTML: Provides page structure with elements like headings and lists.
2. CSS: Controls how elements look with styles for colors and spacing.
3. JavaScript: Makes pages dynamic by changing content and responding to user actions.
• DOM Manipulation: Lets developers change HTML elements and attributes.
• Event Handling: Triggers actions like clicks or key presses.
• AJAX: Fetches data from servers without reloading the page.
4. Animations: Adds visual effects and movement to elements.
5. Form Validation: Checks user input instantly without submitting forms.
6. Dynamic Content Loading: Updates parts of the page without refreshing, making it faster
and smoother.
• Cascading: Styles can cascade from one style sheet to another, meaning multiple CSS files
can be linked to the same HTML document, with the last one taking precedence.
• Style: Adding visual styling to HTML elements.
• Sheets: Writing style rules in separate documents.
CSS Syntax:
selector {
property_1: value;
property_2: value;
property_3: value;
}
Example:
h1 {
text-align: left;
color: blue;
#select {
color: red;
In CSS, selectors target specific HTML elements, and properties define the style attributes to be
applied. Values are assigned to these properties to determine how the element should be styled.
How CSS Works: CSS applies style options to HTML elements to make webpages visually
appealing. For example, to style a <h1> header as red and centered, you would use CSS like:
h1 {
color: red;
text-align: center;
Here, h1 is the selector targeting the header element. Properties such as color and text-align are
defined within curly brackets, with their corresponding values.
Basic principles of CSS can be applied to change various properties, such as background color:
body {
background-color: grey;
This code sets the background color of the entire webpage to grey.
Cascading Style Sheets (CSS) is a stylesheet language used to describe the presentation of a
document written in HTML or XML (including XML dialects like SVG or XHTML). CSS describes how elements should
be rendered on screen, in print, or in other media.
Key Concepts:
1. Selectors: CSS selectors are patterns used to select the elements you want to style. There are various types
of selectors:
• Element Selector: Selects elements based on their element type (e.g., p for paragraphs).
• Class Selector: Selects elements based on their class attribute (e.g., .classname).
• ID Selector: Selects a single element based on its ID attribute (e.g., #idname).
• Attribute Selector: Selects elements based on their attributes.
• Pseudo-classes and Pseudo-elements: Allow you to style elements based on their state or position.
2. Properties: CSS properties define how the selected elements should be styled. Each property has a name and
a value. For example:
In this example, color and font-size are properties, and blue and 16px are their respective values.
3. Values: Values are assigned to properties to define how the property should be applied. Values can be
numerical, text, colors, etc.
4. Cascade and Specificity: CSS follows a set of rules to determine which styles should be applied when there
are conflicting rules. These rules are based on specificity and inheritance. Specificity determines which rule
takes precedence, while inheritance allows styles to be passed down from parent elements to their children.
5. Box Model: The box model describes the layout of elements in CSS. Each element is considered as a
rectangular box with content, padding, borders, and margins. CSS properties like width, height, padding,
border, and margin are used to control the dimensions and spacing of these boxes.
6. Responsive Design: CSS allows for creating responsive designs that adapt to different screen sizes and
devices. Media queries are used to apply different styles based on factors like screen width, height,
resolution, etc.
7. Transitions and Animations: CSS can be used to create transitions and animations to add interactivity and
visual effects to web pages. Properties like transition and animation are used for this purpose.
Usage:
1. Embedded CSS: CSS can be embedded directly within an HTML document using the <style> tag.
2. External CSS: CSS can also be stored in separate external files with a .css extension and linked to HTML
documents using the <link> tag.
3. Inline CSS: Styles can be applied directly to individual HTML elements using the style attribute.
Example:
<!DOCTYPE html>
<html>
<head>
<title>Sample Page</title>
<style>
/* Embedded CSS */
p{
color: blue;
font-size: 16px;
}
.important {
font-weight: bold;
}
</style>
<link rel="stylesheet" type="text/css" href="styles.css"> <!-- External CSS -->
</head>
<body>
<!-- Inline CSS -->
<p style="background-color: yellow;">This is a paragraph with inline CSS.</p>
<p class="important">This is an important paragraph.</p> <!-- Class selector -->
<p id="unique">This is a unique paragraph.</p> <!-- ID selector -->
</body>
</html>
/* styles.css */
p{
margin: 10px;
}
In this example, we have a combination of embedded, external, and inline CSS. The styles defined in each location
are applied to the respective HTML elements. The cascading nature of CSS allows us to combine styles from different
sources while maintaining specificity and inheritance rules.
In this example, the "style" attribute is used directly within the HTML tags to apply CSS styles. Each CSS property and
value pair is separated by a semicolon within the value of the "style" attribute. This method is useful for applying
styles to individual elements when you don't want to create a separate CSS rule or when styles need to be
dynamically generated. However, it's generally considered best practice to use external or internal stylesheets for
larger projects to maintain separation of concerns and improve maintainability.
CSS Combinators
Here, four types of CSS selectors can consist of one simple selector. We can involve a combinator between the simple
selectors.
In this example:
• The <div> element has inline styles applied directly within the style attribute. The text color is set to red, and
the font size is set to 20 pixels.
• The <p> element also has inline styles applied within the style attribute. It has a yellow background color and
10 pixels of padding.
Using inline styles via the style attribute can be convenient for applying styles to individual elements when you don't
want to create separate CSS rules. However, it's generally considered best practice to separate content (HTML) from
presentation (CSS) whenever possible, so the use of inline styles should be limited to cases where it's necessary or
beneficial.
body {
font-family: Arial, sans-serif;
background-color: #f0f0f0;
}
h1 {
color: blue;
}
.container {
width: 80%;
margin: 0 auto;
}
Linking the External Style Sheet to HTML: In the HTML document, you use the <link> element within the <head>
section to reference the external style sheet.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<!-- Content of the webpage goes here -->
<h1>Welcome to my webpage</h1>
<p>This is a paragraph.</p>
<div class="container">
<!-- Content within the container -->
</div>
</body>
</html>
In this example, the <link> element specifies the relationship (rel) of the linked document (stylesheet) and its location
(href).
Applying Styles: Once linked, the styles defined in the external CSS file will be applied to the HTML elements
according to the selectors specified in the CSS rules.
A CSS basic box model consists of a content area, where any text, images, or other HTML elements are
displayed. This is optionally surrounded by padding (space inside the element's border), a border (wraps the
content area and padding), and a margin (space outside the element's border), on one or more sides. In the
standard box model, if you give a box width and a height attribute, this defines the width and height of the
content area of the element. Any padding and border is then added to that width and height to get the total
size of the box.
Takeaway:
The CSS Box Model simplifies webpage design by representing all elements as rectangular boxes.
These boxes consist of four main components: content, padding, border, and margin. Here's a
simplified explanation:
1. Content: This is where the actual text, images, or other elements are displayed within the
box. You can adjust its size using properties like width and height.
2. Padding: Padding creates space around the content area, inside the border. It's like adding
cushioning within the box. You can control the padding with properties such as padding-
top, padding-right, padding-bottom, and padding-left.
3. Border: The border wraps around the padding and content, defining the outer edge of the
box. You can style the border with properties like border-width, border-style, and border-
color. It can have different styles like solid, dashed, or dotted.
4. Margin: Margin is the transparent space outside the border, separating one box from
another. It's like the empty space around the box. You can set the margin using properties
like margin-top, margin-right, margin-bottom, and margin-left. Understanding the CSS Box
Model is crucial for designing webpage layouts effectively. It helps in positioning elements
and creating visually appealing designs.
Padding Vs Margin
One can get easily confused between padding and margin as they both give the effect of adding space. The
key differences between padding and margin are listed below.
Padding Margin
Padding is the inner space of an element i.e. the Margin is the outer space of an element i.e. the space outside
space inside the element’s border. the element’s border.
The styling of an element, such as the background The styling of an element, such as the background color, does
color, affects the padding. not affect the margin.
The following example illustrates the use of the CSS Box model properties:
HTML
<!DOCTYPE html>
<head>
<title>CSS Box Model</title>
<style>
.main {
width: 700px;
border: 5px solid black;
}
.box1 {
font-size: 30px;
font-weight: bold;
background-color: chartreuse;
border: 5px solid darkgreen;
margin: 20px;
}
.box2 {
font-size: 50px;
font-weight: bold;
padding: 100px;
background-color: yellow;
border: 5px solid red;
margin: 100px;
}
</style>
</head>
<body>
<div class="main">
<div class="box1">CSS Box-Model Property</div>
<div class="box2">Content Area</div>
</div>
</body>
</html>
After the execution of above code, the output will look like
HTML (Hypertext Markup Language) DHTML (Dynamic Hypertext Markup Language)
HTML is a mark-up language. DHTML is a collection of technology.
HTML is used to build a static document page DHTML describes the technologies used to build
and to specify the hyperlinks. dynamic and interactive web pages.
HTML does not include server-side code. DHTML includes server-side code.
HTML is a simple static page with no DHTML is a dynamic page with HTML,
JavaScript or styles. CSS, DOM and JavaScript.
HTML files have the.htm or.html extension. DHTML files have the .dhtml extension.
DHTML may require database connectivity as it
HTML does not require database connectivity.
interacts with the user.
HTML pages do not use event methods. DHTML pages make use of event methods.
DHTML enables the incorporation of minor animations
HTML provides tags such
and dynamic menus into Web pages. It employs events,
as <body>, <li>, <form>, etc., to control the
methods, and properties to provide dynamism
presentation of information on the web pages.
to HTML pages.
HTML does not permit changes to the current DHTML also allows you to modify the current pages at
pages without returning to the webserver first. any time. Without initially returning to the webserver.
1. Text Flow: Text flow refers to how text content is rendered and positioned within its containing element.
In web design, text flow is primarily influenced by properties such as text-align, line-height , word-wrap,
white-space , and text-overflow.
• text-align: This property determines the horizontal alignment of text within its container,
allowing it to be aligned left, right, center, or justified.
• line-height: It specifies the height of a line of text. A larger line-height can improve readability
by increasing spacing between lines.
• word-wrap: When set to break-word , this property allows long words to be broken and wrapped
onto the next line if they exceed the width of their container.
• white-space: This property controls how white space characters (such as spaces and tabs) within
the text are handled. Values like normal , nowrap , and pre dictate whether white space is collapsed,
preserved, or rendered as-is.
• text-overflow: When content overflows the boundaries of its container, this property determines
how it is displayed. Options include ellipsis , which truncates overflowing text with an ellipsis (...),
or clip, which simply hides the overflow.
2. Box Model: The box model is a fundamental concept in CSS that defines the layout and structure of
elements on a web page. According to the box model, every element in a web page is represented as a
rectangular box, consisting of four main parts:
• Content: This is the actual content of the element, such as text, images, or other media.
• Padding: Padding is the space between the content and the border of the element. It can be set
using properties like padding-top, padding-right , padding-bottom , and padding-left .
• Border: The border surrounds the padding and content of the element. It can be styled using
properties like border-width , border-style , and border-color.
• Margin: Margin is the space outside the border of the element, which separates it from other
elements on the page. Like padding, it can be adjusted using properties such as margin-top,
margin-right , margin-bottom, and margin-left .
By manipulating these components of the box model and applying various CSS properties, designers can control
the size, spacing, and alignment of elements on a web page, allowing for precise layout and presentation.
CSS (Cascading Style Sheets) comes in different types, each serving specific
purposes and offering unique features. Here's an explanation of the main types of CSS along with
examples:
1. Internal CSS: Internal CSS is defined within the <style> element in the head section
of an HTML document. It applies styles to the entire document or specific elements.
Example:
<p style="color: red; font-size: 16px;">This is a paragraph with inline CSS.</p>
2. Inline CSS: Inline CSS involves styling HTML elements directly within the HTML
document using the style attribute. This type of CSS is applied directly to individual
elements and takes precedence over other CSS rules.
Example:
<!DOCTYPE html>
<html>
<head>
<style>
p{
color: blue;
font-size: 14px;
</style>
</head>
<body>
</body>
</html>
3. External CSS: External CSS involves linking an external CSS file to the HTML
document using the <link> element. This allows you to separate the style definitions
from the HTML content, making it easier to maintain and reuse styles across multiple
pages.
Example (styles.css):
/* styles.css */
p{
color: green;
font-size: 18px;
}
Example (HTML with external CSS):
<!DOCTYPE html>
<html>
<head>
</head>
<body>
</body>
</html>
UNIT-2
The object model allows Web authors to control the presentation of their pages and gives them access to all
elements on their Web page. The whole Web page—elements, forms, frames, tables, etc.—is represented in an
object hierarchy. Using scripting, an author is able to retrieve and modify any properties or attributes of the Web
page dynamically.
Object Referencing
The simplest way to reference an element is by using the element’s id attribute. The element is represented as an
object, and its various XHTML attributes become properties that can be manipulated by scripting. Figure 13.1 uses
this method to read the innerText property of a p element.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-
strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Object Model</title>
<script type="text/javascript">
function start() {
var pText = document.getElementById("pText");
alert(pText.innerText);
pText.innerText = "Thanks for coming.";
}
</script>
</head>
<body onload="start()">
<p id="pText">Welcome to our Web page!</p>
</body>
</html>
plays an alert box containing the value of pText.innerText. The object pText refers to the p element whose id is
set to pText (line 25). The innerText property of the object refers to the text contained in that element (Welcome
to our Web page!). Line 17 of function start sets the innerText property of pText to a different value. Changing
the text displayed on screen in this manner is an example of a Dynamic HTML capability called dynamic content.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Object Model</title>
<script>
function start() {
var elements = "";
for (var loop = 0; loop < document.all.length; ++loop) {
elements += "<br>" + document.all[loop].tagName;
}
document.getElementById("pText").innerHTML += elements;
alert(elements);
}
</script>
</head>
<body onload="start()">
<p id="pText">Elements on this Web page:</p>
</body>
</html>
The script walks through all XHTML elements in a document using a function called start. It goes
through each element and displays its name using tagName.
The document.all collection contains all elements in the document. Each element also has its own
all collection, which holds its contained elements. Similarly, the children collection contains a
specific element's child elements.
A function called child uses recursion to navigate through all elements on the page. It starts from
the html element and iterates through its children. If a child element has its own children, the
function recursively calls itself to explore them.
The script gathers tag names while looping and formats them into a hierarchical structure using ul
and li tags. Finally, it updates the display by changing the HTML content of a paragraph element
(<p id="myDisplay">) with the collected elements, including their enclosing tags.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Object Model</title>
<script>
var elements = "<ul>";
function child(object) {
var loop = 0;
elements += "<li>" + object.tagName + "<ul>";
elements += "</ul></li>";
}
</script>
</head>
<body onload="child(document.all[4]); myDisplay.outerHTML += elements;">
<p>Welcome to our <strong>Web</strong> page!</p>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Frames collection</title>
</head>
<body>
<iframe src="top.html" name="upper" style="width: 100%; height: 100px; border: none;"></iframe>
<iframe src="bottom.html" name="lower" style="width: 100%; height: calc(100% - 100px); border:
none;"></iframe>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>The frames collection</title>
<script>
function start() {
var text = prompt("What is your name?", "");
parent.frames["lower"].document.write("<h1>Hello, " + text + "!</h1>");
}
</script>
</head>
<body onload="start()">
<h1>Cross-frame scripting!</h1>
</body>
</html>
Lines 17–18 (Fig. 13.8) apply changes to the lower frame. To reference the lower frame, we first reference the parent
frame of the current frame, then use the frames collection. We use a new notation here—frames( "lower" )—to refer
to the element in the frames collection with an id or name of lower. The tag for the lower frame appears second in
the XHTML file, so the frame is second in the frames collection. We then use the familiar document.write method in
that frame to update it with the user input from our prompt on line 17.
navigator Object
One of the most appealing aspects of the Internet is its diversity. Unfortunately, because of this diversity, sometimes
standards are compromised. Each of the two most popular browsers currently on the market, Netscape’s
Communicator and Microsoft’s Internet Explorer, has many features that give the Web author great control over the
browser, but many of their features are incompatible. Each, however, supports the navigator object, which contains
information about the Web browser that is viewing the page. This allows Web authors to determine which browser
the user has—this is especially important when the page uses browser-specific features, because it allows the author
to redirect users to pages that their browsers can display properly. Figure 13.9 demonstrates how to determine the
type of browser that requests the document navigator.html.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>The navigator Object</title>
<script>
function start() {
if (navigator.appName == "Microsoft Internet Explorer") {
if (parseInt(navigator.appVersion) >= 4) {
document.location = "newIEversion.html";
} else {
document.location = "oldIEversion.html";
}
} else {
document.location = "NSversion.html";
}
}
</script>
</head>
<body onload="start()">
<p>Redirecting your browser to the appropriate page, please wait...</p>
</body>
</html>
When the page loads, the onload event calls function start, which checks the value of the property
navigator.appName. This property of the navigator object contains the name of the browser application (for IE, this
property is “Microsoft Internet Explorer”; for Netscape, it is “Netscape”). If the browser viewing this page is not
Internet Explorer, in line 24 we redirect the browser to the document “NSversion.html” by assigning the document
name to property document.location— the URL of the document being viewed. When a script assigns
document.location a new URL, the browser immediately switches Web pages. Line 18 checks the version of the
browser with the navigator.appVersion property. The value of appVersion is not a simple integer, however—it is a
string containing other information, such as the Operating System of the user’s computer. Therefore, the script uses
method substring to retrieve the first character of the string, which is the actual version number. If the version
number is 4 or greater, we redirect to newIEversion.html. Otherwise, we redirect the browser to oldIEversion.html.
As we see here, the navigator object is crucial in providing browser-specific pages so that as many users as possible
can view your site properly
"Scripting can control XHTML pages, and Dynamic HTML (DHTML) uses an event model to respond to what
users do on a webpage. This makes websites more interactive and easier to use. It also helps reduce the
workload on servers. With the event model, scripts react to actions like moving the mouse or typing. This
makes content more dynamic and interfaces easier to understand. In this chapter, we learn how to use the
event model to respond to user actions. We cover 10 common events, like mouse movements and form
submissions. For instance, we might use an event called 'onreset' to ask users if they're sure they want to
reset a form. We also include a table of all DHTML events for reference."
The onclick event is a key part of web development, allowing developers to respond to
user clicks on elements like buttons or links. Here's a simplified breakdown:
1. Triggering: onclick happens when a user clicks a webpage element with the mouse.
2. Event Binding: Developers link onclick to HTML elements using methods like inline HTML,
DOM manipulation, or frameworks.
3. Event Handler: When clicked, a JavaScript function (event handler) executes to define
actions.
4. Event Information: The event object provides details like mouse position and target
element.
5. Preventing Default Behavior: Developers can stop default actions, like link navigation,
using preventDefault().
6. Usage Examples: onclick commonly creates interactive buttons, validates forms, or triggers
actions.
Overall, onclick is crucial for making web pages interactive and responsive to user clicks.
<!DOCTYPE html>
<html>
<head>
<title>DHTML Event Model onclick</title>
<script>
function showAlert() {
alert("Hi there");
}
</script>
</head>
<body>
<p id="para" onclick="showAlert()">Click on this text!</p>
<input type="button" value="Click Me!" onclick="alert('Hi again')" />
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>DHTML Event Model onload</title>
<script>
var seconds = 0;
function startTimer() {
// 1000 milliseconds = 1 second
window.setInterval(updateTime, 1000);
}
function updateTime() {
seconds++;
document.getElementById("soFar").innerText = seconds;
}
</script>
</head>
<body onload="startTimer()">
<p>Seconds you have spent viewing this page so far: <strong id="soFar">0</strong></p>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>DHTML Event Model - onerror</title>
<script>
// Set up the error handler
window.onerror = handleError;
To implement an onmouseout event handler in HTML5, you can use JavaScript to define a function
that will be triggered when the mouse moves out of an element. Here's an example:
<!DOCTYPE html>
<html>
<head>
<title>Mouse Out Event Handler</title>
<script>
function handleMouseOut() {
// Update some element when mouse moves out
document.getElementById("message").innerText = "Mouse is out!";
}
</script>
</head>
<body>
<div onmouseout="handleMouseOut()">
<p>Move your mouse out of this area.</p>
</div>
Features:
1. Dynamic Content: DHTML allows developers to dynamically modify the content of a web page without
requiring a page reload. This enables the creation of interactive user interfaces where elements can
change in response to user actions or other events.
2. Animation: With DHTML, developers can create animations and transitions using CSS and JavaScript.
This allows for the creation of visually appealing effects such as fading, sliding, and scaling elements on
the page.
3. Event Handling: DHTML enables the handling of various user events such as mouse clicks, keyboard
inputs, and form submissions. Developers can define event handlers in JavaScript to execute custom
actions in response to these events.
4. DOM Manipulation: The Document Object Model (DOM) represents the structure of an HTML
document as a tree of nodes. DHTML provides mechanisms for dynamically manipulating the DOM,
allowing developers to add, remove, or modify elements on the page programmatically.
5. Ajax (Asynchronous JavaScript and XML): DHTML facilitates the implementation of Ajax, which
enables asynchronous communication between the web browser and the server. This allows for the
updating of parts of a web page without reloading the entire page, resulting in a smoother and more
responsive user experience.
Components:
1. HTML: The foundation of DHTML, HTML provides the structure of the web page, including elements
such as headings, paragraphs, images, and forms.
2. CSS: Cascading Style Sheets are used to define the presentation and layout of HTML elements. CSS
allows developers to control the appearance of elements, including their size, color, font, and positioning.
3. JavaScript: The primary scripting language used in DHTML, JavaScript enables dynamic manipulation of
HTML and CSS. It allows developers to respond to user actions, modify the DOM, perform calculations,
and interact with server-side resources.
Uses:
1. Interactive Web Applications: DHTML is commonly used to create interactive web applications, such as
online forms, data visualizations, and multimedia content.
2. Dynamic User Interfaces: DHTML enables the creation of dynamic user interfaces with features like
dropdown menus, collapsible panels, and tabbed navigation.
3. Web Animation: DHTML allows for the creation of animated elements and transitions, enhancing the
visual appeal and usability of web pages.
4. Real-time Updates: With Ajax, DHTML can be used to implement real-time updates in web applications,
such as live chat, notifications, and dynamic content loading.
5. Responsive Design: DHTML techniques can be applied to create responsive web designs that adapt to
different screen sizes and devices, providing a consistent user experience across desktops, tablets, and
smartphones.
Overall, DHTML empowers developers to create dynamic, interactive, and visually engaging web experiences that
enhance user engagement and usability.
To implement an onfocus event handler in HTML5, you can use JavaScript to define a function that will
be triggered when an element receives focus. Here's an example:
<!DOCTYPE html>
<html>
<head>
<script>
function handleFocus() {
</script>
</head>
<body>
</body>
</html>
To implement an onblur event handler in HTML5, you can use JavaScript to define a function that will
be triggered when an element loses focus. Here's an example:
<!DOCTYPE html>
<html>
<head>
<script>
function handleBlur() {
</script>
</head>
<body>
</body>
</html>
To implement an onsubmit event handler in HTML5, you typically use JavaScript to define a function that will
be triggered when a form is submitted. Here's an example:
<!DOCTYPE html>
<html>
<head>
<script>
function handleSubmit(event) {
alert("Form submitted!");
</script>
</head>
<body>
<form onsubmit="handleSubmit(event)">
</body>
</html>
In Dynamic HTML (DHTML), filters and transitions are used to apply visual effects to elements on a
web page. These effects can enhance the user experience and make the webpage more engaging.
Here's an overview of filters and transitions in DHTML:
1. Filters: Filters are a set of visual effects that can be applied to elements using CSS or
JavaScript. They can change the appearance of elements by altering properties like color,
transparency, and distortion. Some commonly used filters include:
Filters can be applied using CSS properties like filter and -webkit-filter, or they can be manipulated
dynamically using JavaScript.
Example CSS:
cssCopy code
2. Transitions: Transitions allow you to smoothly change the property values of an element
over a specified duration. This can create effects such as fading in/out, sliding, or scaling.
Transitions are typically defined using CSS and can be applied to properties like opacity,
width, height, color, etc.
Example CSS:
cssCopy code
In the above example, when the opacity of the element changes, it will transition over a duration of
0.5 seconds with an ease-in-out timing function.
Transitions can be triggered by user actions (like hover or click) or applied dynamically using
JavaScript.
Both filters and transitions can greatly enhance the visual appeal and interactivity of a webpage.
However, it's important to use them judiciously, as excessive use may impact performance and
distract users from the main content. Additionally, not all browsers support all filter effects or
transition properties, so it's essential to consider cross-browser compatibility when using these
features.
@ColorName@|@ColorHexRGBValue@
2 @aqua@|@#00FFFF@
3 @black@|@#000000@
4 @blue@|@#0000FF@
5 @fuchsia@|@#FF00FF@
6 @gray@|@#808080@
7 @green@|@#008000@
8 @lime@|@#00FF00@
9 @maroon@|@#800000@
10 @navy@|@#000080@
11 @olive@|@#808000@
12 @purple@|@#800080@
13 @red@|@#FF0000@
14 @silver@|@#C0C0C0@
15 @teal@|@#008080@
16 @yellow@|@#FFFF00@
17 @white@|@#FFFFFF@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script>
// Sample data
var Colors = {
recordset: {
EOF: false,
MoveNext: function() {
},
MoveFirst: function() {
};
function reNumber() {
if (!Colors.recordset.EOF)
document.getElementById("recordNumber").innerText = Colors.recordset.absolutePosition;
else
function forward() {
Colors.recordset.MoveNext();
if (Colors.recordset.EOF)
Colors.recordset.MoveFirst();
document.getElementById("colorSample").style.backgroundColor =
document.getElementById("colorRGB").innerText;
reNumber();
}
</script>
</head>
<p>
</p>
</body>
</html>
Binding to an img
Many different types of XHTML elements can be bound to data sources. One of the more interesting elements in
which to bind data is the img element. Figure 16.4 lists a data source that contains image file names. Figure 16.5
binds an img element to the data source
Lines 59–60 bind the data source to an img element. When binding to an img element, changing the recordset
updates the src attribute of the image. Clicking any of the navigation buttons changes the image displayed on screen.
16.5 Binding to a table
Binding data to a table element is perhaps the most important feature of data binding. This is done somewhat
differently from the data binding we have seen. Figure 16.6 binds to a table element the data in Fig. 16.1.
<!DOCTYPE html>
<html>
<head>
<title>Data Binding and Tables</title>
</head>
<body style="background-color: darkseagreen">
<h1>Binding Data to a <code>table</code></h1>
<table id="ColorsTable" style="border-style: ridge; border-color: darkseagreen; background-color: lightcyan">
<thead>
<tr style="background-color: mediumslateblue">
<th>Color Name</th>
<th>Color RGB Value</th>
</tr>
</thead>
<tbody>
<tr style="background-color: lightsteelblue">
<td><span id="ColorName"></span></td>
<td><span id="ColorHexRGBValue" style="font-family: monospace"></span></td>
</tr>
</tbody>
</table>
<!-- Include script for data binding -->
<script>
// Sample data
var colorsData = [
{ ColorName: "Red", ColorHexRGBValue: "#FF0000" },
{ ColorName: "Green", ColorHexRGBValue: "#00FF00" },
{ ColorName: "Blue", ColorHexRGBValue: "#0000FF" }
];
Here's how you can achieve structured graphics and active control in dynamic HTML:
1. HTML: Define the structure of your webpage using HTML. This includes elements like <div>,
<canvas>, <svg>, etc., which can be used to contain and organize your graphics.
2. CSS: Use CSS to style and position your graphical elements. You can set properties like
width, height, background-color, border, position, etc., to control the appearance and layout of
your graphics.
3. JavaScript: JavaScript is the primary language for adding interactivity and dynamic
behavior to your graphics. You can use it to manipulate the DOM (Document Object Model)
to create, modify, and remove elements dynamically. Additionally, JavaScript libraries like
D3.js, Paper.js, Raphael.js, etc., provide powerful tools for working with structured graphics.
4. Canvas: The <canvas> element allows you to draw graphics dynamically using JavaScript. You
can use methods like getContext('2d') to obtain a drawing context and then use functions
like fillRect(), strokeRect(), drawImage(), etc., to draw shapes, images, and text onto the
canvas.
5. SVG (Scalable Vector Graphics): SVG is an XML-based language for describing two-
dimensional vector graphics. You can embed SVG directly into your HTML and use
JavaScript to manipulate its elements. SVG provides a wide range of graphical primitives like
<rect>, <circle>, <line>, <text>, etc., which can be styled and animated using CSS and
JavaScript.
6. Events and Interaction: Use event handling in JavaScript to make your graphics interactive.
You can attach event listeners to graphical elements to respond to user actions like mouse
clicks, keyboard input, touch events, etc. This allows you to create interactive visualizations,
games, simulations, and other dynamic content.
7. Animation: You can animate your graphics using CSS animations or JavaScript. CSS
animations allow you to define keyframes and transitions for CSS properties like transform,
opacity, color, etc. JavaScript-based animation libraries provide more flexibility and control
over the animation process, allowing you to create complex motion effects and timed
sequences.
By combining HTML, CSS, and JavaScript, you can create rich and interactive graphical content in
DHTML, ranging from simple shapes and animations to complex data visualizations and
multimedia applications.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Interactive Drawing Canvas</title>
<style>
#drawingCanvas {
border: 1px solid #000;
cursor: crosshair;
}
</style>
</head>
<body>
<script>
// Get canvas element and its drawing context
const canvas = document.getElementById('drawingCanvas');
const ctx = canvas.getContext('2d');
</body>
</html>
This code creates an HTML page with a canvas element where users can draw circles by clicking and
dragging the mouse. The JavaScript code listens for mouse events (mousedown, mousemove, mouseup) on the
canvas and draws circles at the mouse coordinates using the canvas drawing API.
UNIT-3 JAVASCRIPT
Javascript is a cross-platform, interpreted, object-oriented scripting language.It can be used for both client-
side and server-side programming. Pages made with HTML and CSS are static but using javascript makes
them dynamic allowing them to respond and interact with the user.
Features of JavaScript
JavaScript is a versatile scripting language used for making web pages interactive and dynamic. Here's a
simplified breakdown of its features, applications, how engines work, and its pros and cons:
Features of JavaScript:
• Cross-platform: Works on various operating systems like Windows, macOS, and Linux.
• Object-Oriented: Follows a prototype-based approach for object-oriented programming.
• Scripting Language: Executes scripts in web browsers, mostly for client-side tasks like managing
webpages and user interactions.
• Dynamically Typed: Doesn't require declaring variable types beforehand, allowing flexibility.
• Loosely Typed: Supports implicit type conversion, making operations flexible.
• Case Sensitive: Recognizes differences in letter case.
• Browser Support: Compatible with major web browsers.
• JIT Compilation: Combines interpretation and Just-In-Time compilation for faster execution.
• Interpreted: Uses an interpreter to convert code for execution.
• Lightweight: Contains fewer language constructs compared to other languages like C++ or Java.
Applications of JavaScript:
1. Parsing: Reads and generates an Abstract Syntax Tree (AST) from the script.
2. Interpretation: Converts AST to bytecode.
3. JIT Compilation: Optimizes bytecode for execution.
4. Execution: Executes optimized code.
Advantages of JavaScript:
Limitations of JavaScript:
JavaScript has a prototype-based object model Java has a class-based object model
Javascript cannot write to the hard disk automatically Java can write to the hard disk automatically
The following table briefs the difference between let and var and const in javascript:
It gets hoisted to the top of its It also got hoisted to the top of its It also got hoisted to the top of its scope
scope and initialized undefined. scope but didn't initialize. but didn't initialize.
It's an old way to declare a It's a new way to declare variables It's also a new way to declare a variable,
variable. introduced in ES6. which introduces in ES6.
Can be accessed without Cannot be accessed without Cannot be accessed without initialization,
initialization as its default value is initialization, leading to as it cannot be declared without
“undefined”. ‘referenceError’. initialization in the first place.
Non-primitive Data Types: These are complex data types created from combinations of primitive types. Here
are some examples:
Understanding these data types is crucial for organizing and manipulating data effectively in JavaScript.
// Arithmetic operations
let num2 = 5;
console.log("Addition:", addition);
console.log("Subtraction:", subtraction);
console.log("Multiplication:", multiplication);
console.log("Division:", division);
console.log("Modulus:", modulus);
Addition: 15
Subtraction: 5
Multiplication: 50
Division: 2
Modulus: 0
Is Equal: false
Is Not Equal: true
Is Greater Than: true
Is Less Than: false
Is Greater Than or Equal: true
Is Less Than or Equal: false
Assignment
b); // false (strict equality, different types)
1. Assignment Operators:
• = : Assigns a value to a variable
• += : Adds and assigns
• -= : Subtracts and assigns
• *= : Multiplies and assigns
• /= : Divides and assigns
• %= : Modulus and assigns
let x = 10;
15
Increment and Decrement Operators:
• ++ : Increment operator (increases value by 1)
• -- : Decrement operator (decreases value by 1)
These can be used as prefix or postfix operators. When used as postfix operators,
they first return the current value before incrementing/decrementing. When used
as prefix operators, they first increment/decrement and then return the value.
Example:
let x = 10;
These are fundamental operators in JavaScript that are used extensively for various
purposes, including arithmetic calculations, variable manipulation, and control flow
operations.
let i = 0;
do {
console.log(i);
i++;
} while (i < 5);
4. Break Statement: The break statement is used to terminate the current loop, switch, or label
statement and transfer program control to the statement immediately following the terminated
statement.
Example:
for (let i = 0; i < 10; i++) {
if (i === 5) {
break;
}
console.log(i);
}
These control structures are essential for controlling the flow of your JavaScript programs, allowing you to
execute code conditionally and iteratively.
JavaScript programs are composed of functions, which can be either predefined (built-in) or programmer-
defined. Predefined functions that belong to JavaScript objects are often called methods, implying they
belong to a specific object. However, the terms function and method can be used interchangeably. JavaScript
provides various objects with rich collections of methods for mathematical, string, date/time, and array
manipulations.
Programmer-defined functions are functions written by the programmer to accomplish specific tasks. These
functions encapsulate statements that are hidden from other functions, promoting modularity and good
software engineering practices.
Functions are invoked (called) through function calls. A function call includes the function name and any
arguments needed for the function to perform its task. This relationship is analogous to hierarchical
management, where a boss (caller) delegates tasks to a worker (called function), unaware of the worker's
internal workings. Worker functions may call other worker functions, forming complex relationships.
Functions and methods are invoked by writing the function or method name followed by parentheses
containing any arguments. For example, the parseFloat() function converts a string to a floating-point
number. Arguments can be constants, variables, or expressions, providing flexibility in function invocation.
// math.js
export function add(a, b) {
return a + b;
}
// main.js
import { add } from './math.js';
console.log(add(2, 3)); // Output: 5
<!DOCTYPE html>
<html>
<head>
<title>A Programmer-Defined square Function</title>
</head>
<body>
<h1>Square the numbers from 1 to 10</h1>
<script type="text/javascript">
document.writeln("<h1>Square the numbers from 1 to 10</h1>");
function factorial(n) {
if (n === 0) {
return 1; // Base case
} else {
return n * factorial(n - 1); // Recursive case
}
}
2. Recursion vs Iteration: Recursion and iteration are two ways to achieve repetition in programming.
• Recursion: As mentioned above, recursion involves a function calling itself. It can be a
powerful technique for solving certain types of problems, but it may consume more memory
and be less efficient than iteration in some cases.
• Iteration: Iteration involves looping constructs like for and while loops to repeatedly
execute a block of code. It's generally more efficient in terms of memory usage and
performance compared to recursion.
Example (Factorial using iteration):
function factorial(n) {
let result = 1;
for (let i = 1; i <= n; i++) {
result *= i;
}
return result;
}
These descriptions provide a simplified overview of each global function's purpose and behavior.
Arrays
An array is a group of memory locations that all have the same name and normally are of the same type (although
this attribute is not required). To refer to a particular location or element in the array, we specify the name of the
array and the position number of the particular element in the array.
In JavaScript, arrays are a fundamental data structure used to store multiple values in a single variable. They
can contain various types of data, including numbers, strings, objects, and even other arrays. Here's a basic
overview of arrays in JavaScript:
Creating Arrays:
You can create an array in JavaScript using array literal notation or the Array constructor.
// Using array literal notation
let fruits = ['apple', 'banana', 'orange'];
Array Length:
You can get the length of an array using the length property.
console.log(fruits.length); // Output: 3
Array Methods:
JavaScript arrays come with various built-in methods for manipulation, such as push(), pop(), shift(),
unshift(), splice(), slice(), concat(), join(), indexOf(), includes(), forEach(), map(), filter(), reduce(), etc.
javascriptCopy code
// Adding elements to the end of an array
fruits.push('pear');
// Combining arrays
let moreFruits = ['mango', 'pineapple'];
let allFruits = fruits.concat(moreFruits);
Nested Arrays:
Arrays can contain other arrays as elements, allowing for the creation of multi-dimensional arrays.
javascriptCopy code
let matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
console.log(matrix[0][1]); // Output: 2
In JavaScript, when you work with variables that hold objects (including arrays and functions), you're
working with references rather than the actual values. Understanding references and reference parameters
is crucial for grasping how JavaScript handles complex data types. Here's a breakdown:
References:
• Primitive Types vs. Reference Types: In JavaScript, primitive types (like numbers, strings, booleans,
null, and undefined) are stored directly in memory, whereas objects (including arrays, functions, and
other objects) are stored by reference. This means that when you assign a primitive value to a
variable, you're actually copying the value itself, but when you assign an object to a variable, you're
copying a reference to the object in memory.
• Passing by Reference: When you pass an object (or an array, or a function) to a function as an
argument, you're passing its reference, not a copy of the object itself. Any changes made to the
object inside the function will affect the original object.
function changeName(object) {
object.name = 'Jane';
}
changeName(obj);
console.log(obj.name); // Output: 'Jane'
Reference Parameters:
• Function Arguments: When you pass an object (or an array, or a function) as an argument to a
function, you're essentially passing a reference to that object. This means that any changes made to
the object within the function will affect the original object.
function incrementAge(p) {
p.age++;
}
incrementAge(person);
console.log(person.age); // Output: 31
Modifying Objects: Since you're working with a reference to the object, you can directly
modify its properties within the function without needing to return any value.
function modifyArray(arr) {
arr.push(4);
}
Important Considerations:
• Immutable vs. Mutable: Primitive types are immutable (their values cannot be changed once
they're created), whereas objects are mutable (their properties can be changed).
• Cloning vs. Copying: If you need to create a new object or array with the same properties/values as
another object or array, you'll need to clone it. Simple assignment only copies the reference, which
means changes to the copied object will affect the original one.
Understanding references and reference parameters is crucial for writing efficient and reliable JavaScript
code, especially when dealing with complex data structures and functions.
• The JavaScript code starts from line 15 and ends at line 59.
• The start() function is called when the HTML document is loaded ( onload="start()").
• Inside start(), an array a is defined with some initial values.
• The outputArray() function (lines 40-44) outputs a header followed by the contents of the
array.
• The modifyArray() function (lines 46-51) doubles each element of the array passed to it.
• The modifyElement() function (lines 53-58) attempts to double the value passed to it, but it's
important to note that this doesn't modify the original value outside of the function
because JavaScript passes primitive values (like numbers) by value.
This code illustrates the difference between passing an entire array (which is passed by reference)
and passing individual array elements (which are passed by value) in JavaScript.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Passing Arrays and Individual Array Elements to Functions</title>
<script type="text/javascript">
function start() {
var a = [1, 2, 3, 4, 5];
modifyElement(a[3]);
Here, a is an array containing three arrays, each representing a row of the two-dimensional array.
Each inner array represents a row of the table, and each element within those arrays represents a
cell in the table.
To access an element in the array, you use two subscripts: one for the row and one for the column.
For example:
console.log(a[0][0]); // Outputs: 0
console.log(a[1][2]); // Outputs: 6
console.log(a[2][3]); // Outputs: 11
Initializing such arrays is straightforward. You can declare and initialize them as follows:
var b = [
[1, 2],
[3, 4]
];
<?xml version="1.0"?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Initializing Multidimensional Arrays</title>
<script type="text/javascript">
<!--
function start() {
var array1 = [
[1, 2, 3], // first row
var array2 = [
];
document.writeln("<br />");
document.writeln("</tt>");
}
// -->
</script>
</head>
<body onload="start()"></body>
</html>
Objects
1. JavaScript uses objects to handle data and actions in XHTML documents.
2. Objects like Array simplify data manipulation, akin to how we use cars without
understanding their mechanics.
3. Object-oriented programming in JavaScript hides complexities, allowing for standardized
program creation.
4. Objects represent real-world entities, encapsulating attributes and actions for easier
interaction.
Math Object
• The Math object in JavaScript provides methods for common mathematical calculations.
• To call a method of the Math object, you write the object's name followed by a dot (.) and the method
name, with arguments enclosed in parentheses.
• For example, to calculate and display the square root of a number, you would write Math.sqrt(number).
• Invoking a method of the Math object, like Math.sqrt(), is equivalent to sending a message to the Math
object to perform a specific calculation.
The Math object also defines several commonly used mathematical constants, summarized
String Object
In this section, we introduce JavaScript’s string- and character-processing capabilities. The
techniques discussed here are appropriate for processing names, addresses, credit card
information, etc.
String Object in JavaScript:
In JavaScript, a string is a sequence of characters, either wrapped in single (' ') or double (" ")
quotes. Strings are immutable, meaning once created, they cannot be changed. However, you can
perform various operations on strings using the String object's methods.
Fundamentals of Characters and Strings:
• Characters: A single character within a string. JavaScript treats strings as sequences of
Unicode characters.
• Strings: A sequence of characters wrapped in quotes.
Methods of the String Object:
1. charAt(index): Returns the character at the specified index in the string.
Example:
let str = "Hello";
console.log(str.charAt(1)); // Output: e
2. charCodeAt(index): Returns the Unicode value of the character at the specified index.
Example:
javascriptCopy code
let str = "Hello";
console.log(str.charCodeAt(0)); // Output: 72 (Unicode value for 'H')
3. fromCharCode(...unicodeValues): Static method that returns a string created by using the
specified sequence of Unicode values.
Example:
javascriptCopy code
console.log(String.fromCharCode(72, 101, 108, 108, 111)); // Output: Hello
4. toLowerCase(): Returns the string with all characters converted to lowercase.
5. toUpperCase(): Returns the string with all characters converted to uppercase.
Example:
javascriptCopy code
let str = "Hello";
console.log(str.toLowerCase()); // Output: hello
console.log(str.toUpperCase()); // Output: HELLO
Searching Methods:
1. indexOf(searchValue, startIndex): Returns the index of the first occurrence of the
specified search value within the string, starting the search at the specified index.
Example:
javascriptCopy code
let str = "Hello, World!";
console.log(str.indexOf("o")); // Output: 4
2. lastIndexOf(searchValue, startIndex): Returns the index of the last occurrence of the
specified search value within the string, starting the search at the specified index.
Example:
javascriptCopy code
let str = "Hello, World!";
console.log(str.lastIndexOf("o")); // Output: 8
VBScript:
• Designed for extending Microsoft Office apps like Excel, Word, and Access.
• Automates tasks, creates custom functions, and manipulates data within Office apps.
Features of VBScript:
Version History:
• Introduced with Internet Explorer 3.0 in 1996.
• Various versions added features like regular expressions and XML support.
• Last significant update was in 2009 with version 5.8.
1. Modern web technologies like HTML5 and JavaScript have reduced the need for VBScript.
2. Decreased browser support, mainly works with older versions of Internet Explorer.
3. Past security issues have raised concerns.
4. Microsoft is focusing on newer technologies like .NET and TypeScript.
5. Many are migrating to alternatives like PowerShell for better features and security.
In summary, VBScript's relevance has declined, mainly existing in legacy systems where migration
to newer technologies is challenging.
Advantages:
1. Easy Learning: VBScript has a straightforward syntax, making it accessible for beginners.
2. Windows Integration: Seamlessly automates tasks on Windows and interacts with system
components.
3. Rapid Prototyping: Ideal for quickly creating and testing small scripts.
4. Legacy Compatibility: Still supported in older systems, useful for maintaining legacy
applications.
5. Familiarity: Smooth transition for developers familiar with Visual Basic or Microsoft
technologies.
Disadvantages:
1. Limited Browser Support: Mostly outdated in modern web browsers, works primarily with
older versions of Internet Explorer.
2. Security Concerns: Past vulnerabilities make it less suitable for security-sensitive
applications.
3. Dependence on Windows: Tightly linked to the Windows environment, lacks portability.
4. Lack of Modern Features: Falls behind other languages in terms of modern capabilities
and libraries.
5. Limited Community and Resources: Smaller community and fewer resources compared to
other scripting languages, leading to challenges in finding support and information.
In VBScript, operators are symbols or keywords that are used to perform various
operations on data, such as mathematical calculations, comparisons, logical evaluations, string
concatenation, and bitwise manipulation. These operators help in manipulating and transforming
data within scripts. Here's a breakdown of the types of operators in VBScript:
1. *Arithmetic Operators*: Used for performing mathematical calculations like addition, subtraction,
multiplication, division, modulus (remainder), integer division, and exponentiation.
2. *Comparison Operators*: Used to compare two values and determine the relationship between
them, such as equal to, not equal to, greater than, greater than or equal to, less than, and less
than or equal to.
3. *Logical Operators*: Used to evaluate logical conditions and combine multiple conditions
together, including logical AND, logical OR, and logical NOT.
4. *Concatenation Operator*: Used to join strings together, allowing for the creation of longer
strings by combining smaller ones.
5. *Bitwise Operators*: Used for performing bitwise operations on binary data, including bitwise
AND, bitwise OR, bitwise NOT, bitwise XOR, left shift, and right shift.
6. *Assignment Operators*: Used to assign values to variables and update their values by
performing operations simultaneously, such as addition and assignment, subtraction and
assignment, multiplication and assignment, etc.
VBScript supports various operators for performing different types of operations, including
arithmetic, comparison, logical, concatenation, and bitwise operations. Here's an overview of the
operators in VBScript:
1. *Arithmetic Operators*:
- Addition: +
- Subtraction: -
- Multiplication: *
- Division: /
- Integer Division: \
- Exponentiation: ^
2. *Comparison Operators*:
- Equal to: =
- Logical OR: Or
4. *Concatenation Operator*:
5. *Bitwise Operators*:
- Bitwise OR: Or
6. *Assignment Operators*:
DATA TYPES
In VBScript, data types define the kind of information a variable can hold. Here's a simplified
overview of the main data types:
1. Variant: Versatile type that can hold various kinds of data like numbers, strings, dates, and
objects.
2. Numeric Types:
• Integer: Whole numbers from -32,768 to 32,767.
• Long: Larger whole numbers from -2,147,483,648 to 2,147,483,647.
• Single: Single-precision floating-point numbers with about 7 digits of precision.
• Double: Double-precision floating-point numbers with about 15 digits of precision.
• Byte: Unsigned whole numbers from 0 to 255.
3. String: Sequences of characters enclosed in double quotes.
4. Boolean: Logical values True or False.
5. Date: Represents dates and times.
6. Object: Reference to instances of objects, granting access to their properties and methods.
7. Array: Collection of values of the same data type, stored in a single variable. Can be one-
dimensional or multidimensional.
8. Null: Represents the absence of any value.
9. Error: Represents error conditions, generated by VBScript or COM objects.
These data types cater to various needs in VBScript, providing flexibility and versatility in handling
different kinds of data.
Control structures in VBScript are programming constructs used to manage the flow of
execution within scripts. They include conditional statements like If, loops such as For and Do, and
branching constructs like Select Case. These structures enable developers to create dynamic and responsive
scripts by controlling how code is executed based on specified conditions and iterations.
1. *If Statement*:
- The If statement is used to execute a block of code if a specified condition is true. If the condition is
false, the code block is skipped.
2. *If...Else Statement*:
- The If...Else statement is used to execute one block of code if a specified condition is true, and another
block of code if the condition is false.
3. *If...ElseIf...Else Statement*:
- The If...ElseIf...Else statement allows you to check multiple conditions and execute different blocks of
code based on which condition is true. If none of the conditions are true, an optional Else block is executed.
4. *Nested If Statements*:
- Nested If statements are If statements that are placed inside other If or Else blocks. They allow for more
complex conditional logic by checking multiple conditions within different levels of nesting.
5. *Select Statement*:
The Select Case statement, which allows you to compare a single expression to multiple values and
execute different blocks of code based on the matching value.
These conditional statements provide the ability to control the flow of execution in VBScript programs
based on different conditions, allowing for more dynamic and flexible behavior.
Certainly! Here's the syntax and an example for each of the specified conditional statements in VBScript:
1. *If Statement*:
- Syntax:
vbscript
If condition Then
' Code to execute if condition is True
End If
- Example:
vbscript
Dim num
num = 10
If num > 5 Then
MsgBox "Number is greater than 5"
End If
2. *If...Else Statement*:
- Syntax:
vbscript
If condition Then
' Code to execute if condition is True
Else
' Code to execute if condition is False
End If
- Example:
vbscript
Dim age
age = 20
If age >= 18 Then
MsgBox "You are an adult."
Else
MsgBox "You are a minor."
End If
3. *If...ElseIf...Else Statement*:
- Syntax:
vbscript
If condition1 Then
' Code to execute if condition1 is True
ElseIf condition2 Then
' Code to execute if condition2 is True
Else
' Code to execute if no condition is True
End If
- Example:
vbscript
Dim score
score = 85
If score >= 90 Then
MsgBox "Grade: A"
ElseIf score >= 80 Then
MsgBox "Grade: B"
ElseIf score >= 70 Then
MsgBox "Grade: C"
Else
MsgBox "Grade: F"
End If
4. *Nested If Statements*:
- Syntax:
vbscript
If condition1 Then
If condition2 Then
' Code to execute if both conditions are True
End If
End If
- Example:
vbscript
Dim num1, num2
num1 = 5
num2 = 10
If num1 < num2 Then
If num1 = 5 Then
MsgBox "Both conditions are True."
End If
End If
5. Certainly! Here's the syntax and an example for the Select Case statement in VBScript:
- Example:
vbscript
Dim day
day = "Monday"
Select Case day
Case "Monday"
MsgBox "It's Monday!"
Case "Tuesday"
MsgBox "It's Tuesday!"
Case Else
MsgBox "It's another day of the week."
End Select
Looping statement:
1. *For Loop*:
- The For loop is used to execute a block of code a specified number of times.
These looping statements provide different ways to control the flow of execution in VBScript programs,
allowing for flexibility in handling various situations and conditions.
Sure, here are the syntax and examples for each loop in VBScript:
1. *For Loop*:
- Syntax:
vbscript
For counter = start To end [Step step]
' Code to repeat
Next
- Example:
vbscript
For i = 1 To 5
MsgBox "Iteration " & i
Next
- Example:
vbscript
Dim fruits(2)
fruits(0) = "Apple"
fruits(1) = "Banana"
fruits(2) = "Orange"
For Each fruit In fruits
MsgBox "I like " & fruit
Next
3. *While...Wend Loop*:
- Syntax:
vbscript
While condition
' Code to repeat while condition is True
Wend
- Example:
vbscript
Dim num
num = 1
While num <= 5
MsgBox "Value of num: " & num
num = num + 1
Wend
- Example:
vbscript
Dim x
x=1
Do While x <= 5
MsgBox "Value of x: " & x
x=x+1
Loop
- Example:
vbscript
Dim y
y = 10
Do Until y = 0
MsgBox "Countdown: " & y
y=y-1
Loop
These loop structures allow you to repeat code blocks based on different conditions or for a specified
number of iterations, providing flexibility and control over the flow of your VBScript programs.
Loop control statements are used to change the flow of execution. These can be used if you wish
to skip an iteration or stop the execution.
2. *Exit Do Statement*:
- Description: The Exit Do statement is used to prematurely exit a Do loop based on a specified condition.
When the condition is met, the loop immediately terminates, and control is passed to the statement
following the Loop statement.
These exit statements provide a way to control the flow of execution within loops in VBScript, allowing for
more flexible and efficient looping behavior by exiting the loop prematurely based on certain conditions.
Sure, here's the syntax and an example for each exit statement in VBScript:
- Example:
vbscript
For i = 1 To 10
If i = 5 Then
Exit For
End If
MsgBox "Iteration " & i
Next
2. *Exit Do Statement*:
- Syntax:
vbscript
Exit Do
- Example:
vbscript
Dim num
num = 1
Do
If num = 5 Then
Exit Do
End If
MsgBox "Value of num: " & num
num = num + 1
Loop
- Example:
vbscript
Dim x
x=1
While x <= 10
If x = 5 Then
Exit While
End If
MsgBox "Value of x: " & x
x=x+1
Wend
These exit statements provide a way to prematurely exit loops in VBScript based on certain conditions,
improving the flexibility and efficiency of loop control within scripts.
In VBScript, functions are named blocks of code designed to perform specific tasks
and return values. They help in organizing code, making it easier to read and reuse. Below are the
simplified steps to create and use functions in VBScript, along with examples and common built-in
functions:
2. Return a Value:
• Use the function name to assign the value to be returned.
Example:
addNumbers = result
Dim sum
sum = addNumbers(5, 3)
These built-in functions offer a range of functionalities for common tasks like data conversion,
mathematical operations, string manipulation, date and time handling, and working with arrays,
making VBScript a versatile scripting language.
An array in VBScript is a data structure that stores a collection of elements of the same
data type, accessed by index.
1. Declaring Arrays: Use the Dim keyword to declare an array variable, specifying the number
of elements if known or leaving it empty for dynamic sizing.
2. Initializing Arrays: Initialize array elements either during declaration or later in the code by assigning
values to each element.
numbers(0) = 10
numbers(1) = 20
3. Accessing Array Elements: Access elements by their index (starting from 0).
Dim value
value = numbers(0) ' Accesses the first element of the array
5. Array Functions: VBScript provides functions like LBound and UBound to get the lower and upper bounds
of an array, respectively.
MsgBox LBound(numbers) ' Displays the lower bound of the array
MsgBox UBound(numbers) ' Displays the upper bound of the array
6. Iterating Over Arrays: Utilize loops like For or For Each to iterate over array elements.
Arrays in VBScript offer a straightforward means to manage and process data collections efficiently,
enabling tasks such as storing lists, processing batches, or representing multi-dimensional structures within
scripts.
```vbscript
Dim myArray(2, 2)
myArray(0, 0) = "Apple"
myArray(0, 1) = "Banana"
myArray(0, 2) = "Orange"
myArray(1, 0) = "Grapes"
myArray(1, 1) = "Pineapple"
myArray(1, 2) = "Mango"
myArray(2, 0) = "Strawberry"
myArray(2, 1) = "Watermelon"
myArray(2, 2) = "Kiwi"
```
This creates a 2-dimensional array with 3 rows and 3 columns, initialized with various fruit names.
2. **Array Methods**:
- `LBound` and `UBound`: These functions help determine the lower and upper bounds of an
array.
- `Split`: Splits a string into an array based on a specified delimiter.
- `Join`: Combines the elements of an array into a single string with a specified delimiter.
- `Filter`: Creates a new array containing elements from the original array based on a specified
condition.
- `IsArray`: Checks if a variable is an array.
- `Erase`: Clears all elements from an array.
These methods provide functionality for managing and manipulating array data efficiently.
Using these techniques, you can organize and manipulate data effectively within your VBScript
code, making it easier to work with collections of related information.
These functions are fundamental for tasks like extracting parts of strings, finding substrings, and
modifying string content. They make string manipulation tasks easier in VBScript.
1. Classes:
• In VBScript, a class is a blueprint or a template for creating objects.
• It defines the properties, methods, events, and other members that objects of the
class will have.
• Classes encapsulate data and behavior, providing a way to organize and structure
code.
• Classes are declared using the Class statement followed by the class name.
• Members of a class can be public, private, or hidden, controlling their accessibility
from outside the class.
• Here's a basic example of a class declaration in VBScript:
Class Person
Public Name
Public Age
2. Objects:
• An object is an instance of a class.
• It represents a specific entity with its own set of properties and behaviors defined by the
class.
• Objects are created using the Set statement followed by the New keyword and the class
name.
• Once an object is created, its properties and methods can be accessed using dot notation.
• Here's how you can create and use objects based on the Person class defined above:
Dim person1
Set person1 = New Person
person1.Name = "John"
person1.Age = 30
person1.SayHello()
Overall, classes and objects in VBScript provide a way to create modular, reusable code by encapsulating
data and behavior into objects that can be easily manipulated and interacted with in scripts.
Web Servers:
A web server is software that sends web content to users over the internet. It works by receiving
requests from web browsers, retrieving the requested content, and sending it back to the browser.
1. Apache HTTP Server: Known for flexibility and reliability, it's open-source and
customizable.
2. Nginx: Efficient in managing connections and speed, often used for high loads.
3. Microsoft Internet Information Services (IIS): Popular for hosting on Windows servers,
especially for Microsoft technologies.
4. LiteSpeed: Offers exceptional performance and security, though it's a commercial product.
1. Content Hosting: Store and deliver web content like pages and files.
2. Security: Protect against unauthorized access and attacks.
3. Load Balancing: Distribute traffic across servers for better performance.
4. Logging and Monitoring: Track server activity for troubleshooting and compliance.
5. Caching: Store frequently accessed content to improve speed.
Web servers are crucial for sharing online content efficiently and securely, whether it's a personal
blog or a complex e-commerce platform. Understanding their basics is vital for anyone involved in
the digital world.
Key Benefits:
Key Characteristics:
Advantages:
1. Integration with Windows: Works seamlessly with Windows systems, simplifying setup and
management.
2. Scalability and Performance: Optimized for handling high traffic and complex applications
efficiently.
3. Security Features: Offers robust security measures like encryption and authentication to safeguard
data.
4. Extensibility: Developers can customize and extend functionality using modules and extensions.
Disadvantages:
1. Limited Platform Compatibility: Primarily designed for Windows, limiting its use in non-
Windows environments.
2. Cost: Some advanced features may require additional licensing fees, increasing expenses.
3. Complexity: Configuring and managing IIS can be complex, requiring specialized skills.
4. Resource Consumption: May consume significant system resources, impacting server performance
under heavy loads.
In summary, IIS offers a powerful platform for hosting web applications on Windows servers, with
advantages in integration, scalability, and security, but it also presents challenges such as limited platform
compatibility, cost considerations, complexity, and resource consumption.
Key Features:
Functions:
1. Listening for Requests: Waits for incoming HTTP requests on designated ports.
2. Processing Requests: Evaluates requests using configured settings to determine handling.
3. Accessing Content: Retrieves requested content from the file system or generates dynamic content.
4. Sending Responses: Constructs HTTP responses containing requested content and necessary
headers.
5. Connection Management: Efficiently manages multiple client connections while maintaining
states.
6. Logging and Monitoring: Logs request details for monitoring, troubleshooting, and analysis.
Pros:
Cons:
In essence, Apache Web Server offers robust features and functionality but demands expertise for optimal
utilization.
The process of installing web server the Apache HTTP Server, also known as Apache,
on your system. Follow these steps:
That's it! You have successfully installed and configured the Apache HTTP Server on your system.
You can now start developing and serving web applications using Apache.
UNIT-5
ASP (Active Server Pages):
ASP (Active Server Pages) is a technology used to create dynamic web pages and web applications. It
combines HTML, scripts (like VBScript or JScript), and server-side components to generate content that
responds to user interactions or database queries. It's commonly used with Microsoft's Internet Information
Services (IIS) web server on Windows platforms.
Characteristics:
1. User Control: Allows creating reusable components called user controls for easy addition to
different web pages, enhancing reusability.
2. Custom Controls: Supports creation of powerful custom controls tailored to specific application
needs.
3. Rendering Techniques: Provides methods for dynamically generating HTML, CSS, and JavaScript
based on server-side logic and user input.
4. Code-Behind Model: Separates presentation logic (HTML markup) from application logic (code)
for better organization and maintenance.
ASP Objects:
1. Request Object: Retrieves information sent by the client, such as form data or query parameters.
2. Response Object: Sends output back to the client's browser, like HTML content or headers.
3. Session Object: Stores user-specific data across multiple requests, maintaining state between
interactions.
4. Server Object: Provides access to server-related functionality, such as file operations or server
configuration.
5. Application Object: Manages data shared among all users of the application, like configuration
settings or global variables.
Uses of ASP:
1. Dynamic Web Content: Creates dynamic web pages that change based on user input or database
queries.
2. Database Connectivity: Connects to databases for dynamic data retrieval and manipulation.
3. Form Processing: Handles form submissions, validating input data and processing it securely.
4. Session Management: Manages user sessions for features like persistent logins and personalized
experiences.
5. File Operations: Manages files on the server for tasks like file uploads and downloads.
6. Email Integration: Sends emails from web applications for notifications and communication.
7. Integration with Other Technologies: Integrates with JavaScript, CSS, and XML for enhanced
functionality.
1. SQL Injection: Attackers inject malicious SQL code through user input, compromising the
database.
2. Cross-Site Scripting (XSS): Attackers inject harmful scripts into web pages, stealing data or
performing unauthorized actions.
3. Cross-Site Request Forgery (CSRF): Users' browsers are tricked into making unauthorized
requests.
4. Session Management Issues: Weak session management allows hijacking or session fixation.
5. Authentication and Authorization Vulnerabilities: Weak authentication or improper authorization
checks lead to unauthorized access.
6. File Upload Vulnerabilities: Poor file upload handling enables arbitrary code execution or
uploading malicious files.
7. Sensitive Data Exposure: Improper handling exposes sensitive information.
Client-side scripting is code that runs in the user's web browser, typically written in JavaScript, to
make web pages interactive and dynamic. It handles tasks like form validation, updating content without
reloading the page, managing cookies, and enhancing the user interface.
Server-side scripting, on the other hand, runs on the web server before the page is sent to the
user's browser. It's often written in languages like PHP, ASP.NET, or Python and is responsible for generating
dynamic content, connecting to databases, managing user sessions, handling form submissions, and integrating
with external services.
A Server-Side ActiveX Component is like a toolbox for web servers. It's made
by Microsoft and helps websites do different tasks, like handling data or showing ads. These tools
are used with server-side scripting to improve what websites can do.
Benefits:
1. Cool Interface: ActiveX tools make websites more fun with buttons and pictures.
2. Save Time: They help developers reuse code in different projects, saving time.
3. Works with Microsoft: ActiveX fits well with Microsoft software, so it's good for Windows-
based websites.
4. Works Everywhere: It works on different computers, like Windows, Mac, or Linux.
5. Fancy Features: It offers cool features like videos or 3D graphics for making powerful
websites.
6. Keeps Safe: ActiveX has safety features to protect websites from bad things.
7. Easy Updates: It's simple to add or change ActiveX tools on websites.
ActiveX technology is like a magic box of tools from Microsoft for making cool stuff on websites.
Components:
1. Put Stuff Inside Stuff: You can put things from one program into another, like putting a
picture into a document.
2. Extra Tools: These are special tools that add cool stuff to websites or apps.
3. Making Things Work Together: This part makes sure all the tools can talk to each other
and work together.
4. Controlling Things: It lets you control tools with programs, like making a tool do
something when you click on it.
5. Works on the Web: These tools can be used on websites to make them more fun.
6. Keeping Safe: These tools have safety features to stop bad things from happening.
Tasks:
1. Get Data from Databases: It gets and manages information from databases on the web.
2. Show Ads: It shows different ads on websites, changing them now and then.
3. Change Content: It switches between different things, like articles or pictures, on websites.
4. Find out About Web Browsers: It checks what web browser people are using so the
website can work better for them.
5. Handle Files: It manages files on the web or on a network.
6. Link Things Together: It makes links between documents or web pages.
7. Get Emails and Appointments: It gets information like emails or appointments from web
servers.
8. Help Fix Problems: It gives info and tools to fix things that go wrong.
9. Count Visits: It counts how many times a web page is visited.
10. Check Permissions: It checks if people are allowed to see certain things on a website.
In simple terms, ActiveX components are like special tools that make websites more fun and useful.
ADO, or ActiveX Data Objects, is a tool from Microsoft that helps programs work
with data from different sources, like databases. It's like a set of tools that makes it easier for
developers to connect to databases, get data, and do things with it.
In simple terms, ADO is a handy tool for programs to talk to databases, and version 2.8 comes with
improvements to make it faster, safer, and easier to use.
File System Objects (FSO) are like a set of tools for server-side scripts, helping them
manage files and folders on the server. Here's what they do and why they're useful:
1. File Actions: FSO lets scripts create, read, write, and delete files on the server. This is handy
for things like storing data and processing files.
2. Folder Actions: It also helps scripts manage folders, like creating, moving, and deleting
them. This keeps things organized on the server.
3. File Info: FSO can gather info about files and folders, like their size and when they were last
modified. This helps with keeping track of things.
4. Text File Handling: It can read from and write to text files, making it easy to work with text-
based data.
5. Error Handling: FSO includes tools to deal with errors that might happen during file
operations, making scripts more reliable.
• File Uploads and Downloads: Useful for handling file uploads from users and serving files
for download.
• Data Processing: Helps with tasks like processing data stored in files and moving it around.
• Logging: Allows scripts to keep track of what's happening on the server by logging events.
• Configuration: Lets scripts read and change settings stored in files.
• Content Management: Helps manage files related to website content, like images and
stylesheets.
In short, FSO is a handy toolkit for server-side scripts to work with files and folders on the server,
making it easier to build powerful web applications.
Session tracking in web technology is like keeping tabs on a conversation between a website and
its visitor. It helps the website remember who you are and what you're doing, even as you move
around the site. Here's why it matters and how it's done:
1. Why it Matters:
• Remembering Your Actions: Websites need to remember what you've done, like
items you've added to your shopping cart.
• Verifying Your Identity: It's important for websites to know it's really you when you
log in.
• Personalizing Your Experience: Ever noticed how some sites remember your
preferences? That's thanks to session tracking.
• Keeping Shopping Carts Full: When you're shopping online, session tracking
ensures your cart stays full as you browse.
• Understanding User Behavior: It helps websites learn how visitors interact with
their site.
2. How it's Done:
• Cookies: Small files stored in your browser with a unique ID that help the server
recognize your session.
• Hidden Form Fields: Sometimes, session IDs are added as hidden info in web forms.
• URL Rewriting: Session IDs can be added to URLs as parameters.
• HTTP Session: Info about your session is stored on the server, and you get a unique
ID to link to your session.
These methods work together to give you a smooth, personalized experience on the web while
keeping things secure and private.
Environment Variables:
Advantages:
Disadvantages:
1. Performance Overhead: New processes for each request can slow performance.
2. Security Vulnerabilities: Prone to risks like code injection.
3. Scalability Challenges: Limits scalability in high-traffic environments.
4. Limited Resource Management: Scripts have limited control over server resources.
5. Complexity for Advanced Functionality: Implementing advanced features may require
extra effort.
Applications:
Perl is a versatile programming language known for its text-processing capabilities. Originally
designed for tasks like text manipulation and system administration, Perl is now used for web
development, automation, and various applications. It offers features like:
Advantages:
1. Text Processing Power: Excellent for parsing and processing text data.
2. Platform Independence: Works on different systems.
3. Rich Module Ecosystem: Offers many reusable modules.
4. Flexibility and Expressiveness: Allows concise and readable code.
5. Community and Documentation: Strong support from the Perl community.
Disadvantages:
String processing involves manipulating and analyzing text data within a computer program. It's
crucial for tasks like searching, replacing, splitting, concatenating, and extracting information from strings.
These methods are essential across various programming languages for efficiently handling string
manipulation tasks.
Regular expressions, or regex, are powerful tools for defining search patterns
within strings. They're commonly used in tasks like finding specific text patterns, validating input,
and extracting data.
These properties let developers customize how Regular Expression Validators look and behave to
match their needs and design choices.
ASP.NET( Server side includes) provides validation controls to ensure the accuracy and
integrity of user input in web forms. These controls can be categorized into client-side and server-
side validation controls:
These validation controls help developers build robust and user-friendly web applications by
ensuring data integrity and providing a seamless user experience.
Client-Side Validation Controls:
Why Learn Perl: Perl is a versatile programming language with several compelling reasons to learn:
• Cross-Platform Compatibility: Perl runs on various platforms, making it suitable for diverse
environments.
• Stability: Perl is a stable language with a long history of use in mission-critical projects.
• Open Source: Perl is open-source, ensuring accessibility and community-driven development.
• Text Processing Capabilities: Perl excels at text processing tasks, making it valuable for tasks like
log analysis and data transformation.
• Broad Applications: Perl finds applications in web development, system administration, database
programming, network programming, bioinformatics, and more.
• Mature Ecosystem: Perl has extensive documentation, resources, and a vibrant community,
facilitating learning and development.
Applications of Perl: Perl is widely used across various domains, including:
• Text Processing: Parsing log files, transforming text formats, and handling string manipulation.
• System Administration: Automating system management tasks like monitoring and network
administration.
• Web Development: Server-side scripting, dynamic web development, and database interaction.
• Database Programming: Connectivity, data manipulation, and reporting with various database
systems.
• Network Programming: Creating network clients, servers, and implementing protocols.
• Bioinformatics: Analyzing biological data like DNA sequences and protein structures.
• GUI Development: Building graphical user interfaces for desktop applications.
In summary, understanding cookies and learning Perl can empower developers with powerful tools for
building dynamic, personalized web applications and automating various system management tasks.
XML DTD stands for Document Type Definition. It is a markup declaration that defines the structure,
elements, and attributes that are allowed in an XML document. DTDs are used to ensure that XML
documents conform to a specific structure and can be validated against that structure. Here's an overview of
its meaning, features, types, syntax, advantages, and disadvantages:
Meaning:
A Document Type Definition (DTD) is a formal declaration of the XML document's structure. It specifies
the rules for the elements and attributes that can appear in an XML document.
Features:
1. Defines Structure: DTD defines the structure of an XML document, including elements, attributes,
and their relationships.
2. Validation: DTDs can be used to validate XML documents to ensure they conform to a specific
structure.
3. Reusability: DTDs can be reused across multiple XML documents to enforce consistency.
4. Modularity: DTDs support modularity, allowing different parts of the document structure to be
defined separately and then combined.
5. Parsing Efficiency: DTDs are simple and can be parsed efficiently by XML processors.
decla<!DOCTYPE rootElement [
Advantages:
1. Data Integrity: DTDs ensure that XML documents adhere to a specific structure, enhancing data
integrity.
2. Validation: XML documents can be validated against a DTD to detect errors and inconsistencies.
3. Interoperability: DTDs facilitate interoperability by providing a standardized way to define XML
document structures.
4. Modularity: DTDs support modularity, enabling the reuse of document structures across multiple
XML documents.
5. Parsing Efficiency: DTDs are lightweight and can be parsed efficiently by XML processors.
Disadvantages:
1. Limited Expressiveness: DTDs have limitations in expressing complex document structures
compared to other schema languages like XML Schema or Relax NG.
2. Lack of Data Types: DTDs lack support for specifying data types for elements and attributes.
3. Verbose Syntax: DTD syntax can be verbose and difficult to read, especially for large and complex
documents.
4. No Namespace Support: DTDs do not provide built-in support for XML namespaces, which can be
a limitation in certain scenarios.
5. Limited Error Reporting: DTD validation may provide limited error reporting compared to more
advanced schema languages.
Despite these disadvantages, DTDs remain widely used, especially in legacy systems and simpler XML
document structures. However, for more complex scenarios, other schema languages like XML Schema or
Relax NG may be preferred.
XML parsers interpret and process XML documents based on predefined rules. They extract
data and provide access to elements and attributes for further processing.
Types:
1. DOM Parser: Creates a tree representation in memory for the entire XML document,
suitable for small to medium files but can be memory-intensive for large documents.
2. SAX Parser: Parses XML sequentially, generating events as it encounters elements,
attributes, and text nodes. Memory-efficient and suitable for large files, but lacks random
access.
3. JDOM Parser: Provides a user-friendly API for XML document manipulation, simplifying
tasks with a Java-like interface.
4. StAX Parser: Offers pull-parsing, where the application controls the parsing process by
pulling events from the parser as needed. Balances memory efficiency and ease of use, ideal
for large XML documents.
5. XPath Parser: Evaluates XPath expressions to navigate and query XML documents, enabling
precise element or attribute selection based on criteria.
6. DOM4J Parser: Enhanced version of DOM for Java, offering additional features and
improvements for XML processing in Java applications.
XML Document:
XML Declaration:
XML Elements:
• Description: Building blocks representing data entities with start and end tags.
• Syntax: Start tag (<tagname>), optional attributes, content, end tag (</tagname>).
<element attribute="value">Content</element>
XML Content:
• Description: Data enclosed within XML elements, including text, nested elements, etc.
• Syntax: Text, nested elements, comments, processing instructions, CDATA sections, entity
references.
<element>Text Content</element>
Example:
<friend>
<name>Charlie</name>
<name>Steve</name>
</friend>
1. Embedding XML: Directly embed XML within HTML using the <xml> tag.
2. JavaScript and AJAX: Dynamically load XML data into HTML using JavaScript and AJAX
requests.
3. Server-Side Technologies: Generate HTML from XML using server-side technologies like PHP or
Node.js.
4. XSLT: Transform XML into HTML using XSLT, either client-side or server-side.
These methods seamlessly integrate XML data into HTML for display or manipulation.