Vous êtes sur la page 1sur 574

UNIT - 1

XHTML

• What is XHTML
– XHTML stands for EXtensible HyperText Markup
Language. It is a cross between HTML and XML
language.
– XHTML is almost identical to HTML but it is stricter
than HTML. XHTML is HTML defined as an XML
application. It is supported by all major browsers.
– Although XHTML is almost the same as HTML but It is
more important to create your code correctly, because
XHTML is stricter than HTML in syntax and case
sensitivity. XHTML documents are well-formed and
parsed using standard XML parsers, unlike HTML,
which requires a lenient HTML-specific parser.
• HTML Versions
• Since the early days of the web, there have
been many versions of HTML:
Why Use XHTML?

• XHTML was developed to make HTML more


extensible and increase interoperability with
other data formats. There are two main
reasons behind the creation of XHTML:
– It creates a stricter standard for making web
pages, reducing incompatibilities between
browsers. So it is compatible for all major
browsers.
– It creates a standard that can be used on a variety
of different devices without changes.
• <html>
• <head>
• <body>
• <h1> BAD HTML
• </body>
• The above HTML code doesn't follow the HTML rule
although it runs. Now a day, there are different
browser technologies. Some browsers run on
computers, and some browsers run on mobile phones
or other small devices. The main issue with the bad
HTML is that it can't be interpreted by smaller devices.
• So, XHTML is introduced to combine the strengths of
HTML and XML.
• XHTML is HTML redesigned as XML. It helps you to
create better formatted code on your site.
• XHTML doesn't facilitate you to make badly formed
code to be XHTML compatible. Unlike with HTML
(where simple errors (like missing out a closing tag) are
ignored by the browser), XHTML code must be exactly
how it is specified to be.
Basic Syntax
• Tags
– The <!DOCTYPE html> declaration defines this
document to be HTML5
– The <html> element is the root element of an HTML
page
– The <head> element contains meta information about
the document
– The <title> element specifies a title for the document
– The <body> element contains the visible page content
– The <h1> element defines a large heading
– The <p> element defines a paragraph
• <html>
• <head>
• <title>Page title</title>
• </head>
• <body>
• <h1>This is a heading</h1>
• <p>This is a paragraph.</p>
• <p>This is another paragraph.</p>
• </body>
• </html>
• You can easily maintain, edit, convert and format your
document in the long run.
• Since XHTML is an official standard of the W3C, your
website becomes more compatible with many
browsers and it is rendered more accurately.
• XHTML combines strength of HTML and XML. Also,
XHTML pages can be rendered by all XML enabled
browsers.
• XHTML defines quality standard for your webpages and
if you follow that, then your web pages are counted as
quality web pages. The W3C certifies those pages with
their quality stamp.
• Web Browsers
– The purpose of a web browser (Chrome, IE,
Firefox, Safari) is to read HTML documents and
display them.
– The browser does not display the HTML tags, but
uses them to determine how to display the
document:
Basic Understanding

• What is SGML?
– This is Standard Generalized Markup Language
(SGML) application conforming to International
Standard ISO 8879. HTML is widely regarded as the
standard publishing language of the World Wide Web.
– This is a language for describing markup languages,
particularly those used in electronic document
exchange, document management, and document
publishing. HTML is an example of a language defined
in SGML.
• What is XML?
– XML stands for EXtensible Markup Language. XML
is a markup language much like HTML and it was
designed to describe data. XML tags are not
predefined. You must define your own tags
according to your needs.
• XHTML
– XHTML syntax is very similar to HTML syntax and
almost all the valid HTML elements are valid in
XHTML as well. But when you write an XHTML
document, you need to pay a bit extra attention to
make your HTML document compliant to XHTML.
Basic Syntax
• converting existing HTML document into XHTML
document −
– Write a DOCTYPE declaration at the start of the
XHTML document.
– Write all XHTML tags and attributes in lower case only.
– Close all XHTML tags properly.
– Nest all the tags properly.
– Quote all the attribute values.
– Forbid Attribute minimization.
– Replace the name attribute with the id attribute.
– Deprecate the language attribute of the script tag.
• XHTML document must include four tags <html>,
<head>, <title>, and <body>
• Tags are fundamental syntactic unit of HTML.
• Tags are used to specify categories of content.
• Most tags appears in pairs: opening tag and
closing tag.
• The name of the closing tag is the name of its
corresponding opening tag with a slash attached
to the beginning. Whatever appears in between
these two tags is the content of the tag.
• The opening tag and the closing tag together
specify a container for the content they enclose.
• The container and its content together are called
an element.
• An XHTML document consists of two parts, the
head and the body.
• Head part provides information about the
document.
• Body parts provides the content of the document
, which itself includes tags and attributes.
• Comments :- browsers ignores the XHTML
comments.
• Comments in the program increase the
readability of the programs.
• E.g.
• <!– anything except two adjacent dashes 
DOCTYPE Declaration
• DTD stands for Document Type Definition.
• A DTD allows you to create rules for the elements within your
XHTML documents. Although XHTML itself has rules, the rules
defined in a DTD are specific to your own needs.
• All XHTML documents must have a DOCTYPE declaration at
the start.
• The XHTML standard defines three Document Type
Definitions (DTDs). The most commonly used and easy one is
the XHTML Transitional document.
• XHTML 1.0 document type definitions correspond to three
DTDs −
– Strict
– Transitional
– Frameset
• The basic syntax is:
<!DOCTYPE rootname [DTD]>
• ...where, rootname is the root element, and
[DTD] is the actual definition.
• Actually, there are slight variations depending
on whether your DTD is internal or external
(or both), public or private.
• <!DOCTYPE rootname PUBLIC identifier URL>
• The keyword PUBLIC indicates that it's a public DTD (for
public distribution).
• The presence of URL indicates that this is an external DTD
(the DTD is defined in a document located at the URL).
• The identifier indicates the formal public identifier and is
required when using a public DTD.
– E.g.
– <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-
transitional.dtd">
Standard XHTML Document Structure
• Every XHTML document must begin with an xml
declaration element that simply identifies the
document as being one based on XML.

<?xml version="1.0" encoding="UTF-8"?>

– First Attribute specifies the version number (still 1.0)


– Second attribute defines encoding used for the
document. (unicode encoding , utf-8)
Example
<!DOCTYPE html>
<html>
<body>

<h1>My First Heading</h1>

<p>My first paragraph.</p>

</body>
</html>
Basic Text Markup
• Paragraph
– Text is normally organized into paragraph in the
body of a document.
– XHTML standard does not allow text to be placed
directly in a document.
Example 1 Example 2
<!DOCTYPE html>
<!DOCTYPE html> <html>
<html>
<body>
<body>

<p> <p>This is a paragraph.


This paragraph <p>This is a paragraph.
contains a lot of lines <p>This is a paragraph.
in the source code,
but the browser
ignores it.
<p>Don't forget to close your HTML
tags!</p>
</p>

</body> </body>
</html> </html>
Line Breaks

• <br /> element defines a line break.


• Use <br /> if you want a line break (a new line)
without starting a new paragraph.
• < br /> the slash indicates that the tag is both
an opening and closing tag.
• eg.
<p>This is<br / >a paragraph<br />with
line breaks.</p>
Preserving whitespace
• The text inside a <pre> element preserves
both spaces and line breaks.
Headings
• In XHTML there are six levels of headings,
specified by the tags <h1>, <h2>, <h3>,
<h4>,<h5> and <h6>.
• <h1>, <h2>, <h3> uses font sizes that are
larger than that of the default size of text.
• <h4> uses the default size and
• <h5> and <h6> use smaller size.
Block Quotation
• A block of text to be set off from the normal
flow of text in a document.
<!DOCTYPE html>
<html>
<body>

<p>Browsers usually indent blockquote elements.</p>

<blockquote >
“For 50 years, WWF has been protecting the future of nature.
The world's leading conservation organization,
WWF works in 100 countries and is supported by
1.2 million members in the United States and
close to 5 million globally.”
</blockquote>

</body>
</html>
Font styles and sizes
• Content – based style tags – tags indicates the
particular kind of text that appears in their
content.
– Emphasis tag <em>- special text content. Mostly
highlighted by italic font.
– Strong tag <strong> - more than emphasis tag.
Mostly highlighted by bold font.
– Code tag <code> - used to specify a monospace
font, usually used for program code.
• Non content – based style tags-
– <sub> subscript character
– <sup> superscript character
XHTML tags are categorized in block or inline.
Inline tag :- content appears on the current line.
Inline tag does not implicitly include line break .
Exception is br. E.g <em>, <strong>
Block tag :- breaks the current line so that its
content appears on a new line.
The heading and block quote tags are block tag.
Character Entities
• The special character are defined as entities
which are names for the character by the
browser.
Horizontal Rules
• Places the horizontal lines in between the
document to make it easy for reading.
• It is represented by <hr />.
• The browser chose the thickness, length and
horizontal placement of line.
The Meta Element
Meta element :- provide additional information about a
document.
• It has no content and all the provided information is
through attribute.
• Two attributes are name and content.

e.g. <meta name = “keyword” content = “binary trees,


linked list, stacks” />
Web search use the information provided with the meta
element to categorize web document in their indices.
Images
• Image : - the image is stored in a file which is
specified by an XHTML request. The image is
inserted into the display of the document by the
browser.
• Image formats:-
– GIF (Graphic Inter-change format): developed by
compuserve network service provider for the specific
purpose of moving images. It uses 8 bit color
representation for pixels. Images use the .gif or .GIF
extension. Supports transparency.
– JPEG (Joint photographic expert group) :uses 24 bit
color for representation for pixels. It uses .jpg or .JPG
or .jpeg extension. The compression algorithm used
by JPEG is better at shrinking an image than the one
used by GIF. Size of JPEG is smaller than GIF but it
does not support transparency.
– PNG (Portable Network Graphics).: provides good
replacement for both GIF and JPEG because it has best
characteristics of both.
– But PNG file requires more space as its compression
algorithm does not compromise picture clarity.
• The <img /> tag :- it is a inline tag , specifies an
image that is to appear in a document.
• It includes two attributes: src and alt
– Src :- specifies the file containing the image.
– alt :- specifies text to be displayed when it is not
possible to display the image.
• Two optional attributes of img width and height
can be included to specify the size of the
rectangle for the image.
• E.g.
<img src = “c210.jpg” alt = “ picture of a Cessna 210” />
XHTML Document Validation
• XHTML Document Validation: the W3C provides a
convenient Web-based way to validate XHTML
document against its standard.
• The URL of the service is http://validator.w3.org/
file-upload.html
• The XHTML validation system is a valuable tool
for producing documents that adhere to W3C
standards.
• The specific std against which the document is
checked is given in the DOCTYPE command.
Hypertext Links
• A hypertext link in an XHTML document, called as a link,
acts as a pointer to some resource.
Links :- A link that points to a different document specifies the
address of that document.
– Such an address might be a filename, a directory path and a
filename, or a complete URL.
– Links are specified in an attribute of an anchor tag (<a>), which
is a inline tag.
– The anchor tag that specified a link is called the source of that
link.
– The document whose address is specified in a link is called the
target of that link.
– For creating link href( hypertext reference ) attribute is required.
– The value assigned to href specifies the target of the link.
– the content of an anchor tag, which becomes the clickable
link the user sees, is restricted to text , line break, images
and headings.
– Links are usually implicitly rendered in a different color
than the surrounding and most of the time underlined.
– When the mouse cursor is placed over the anchor-tag
content and the left mouse button is pressed, the link is
taken by the browser.
– If the target is a different document, that document is
loaded and displayed, replacing the currently displayed
document.
• If the target is in the current document, the
document is scrolled by the browser to display
the target of the link.
<!DOCTYPE html>
<html>
<head>
<title>Hyperlink Example</title>
</head>
<body> <p>Click following link</p>
<a href = “link.html">Link file</a>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Hyperlink Example</title>
</head>
<body> <p>Click following link</p>
<a href = “link.html“><img src = “flower.jpg” alt = “
flower image”/ >
Link info </a>
</body>
</html>
Targets within Document
• Links are used to allow readers to jump to
specific parts of a Web page.
• Links can be useful if your webpage is very
long.
• To make a bookmark, you must first create the
bookmark, and then add a link to it.
• When the link is clicked, the page will scroll to
the location with the bookmark.
• Example
• First, create a bookmark with the id attribute:
– <h2 id="C4">Chapter 4</h2>
• Then, add a link to the bookmark ("Jump to
Chapter 4"), from within the same page:
– <a href="#C4">Jump to Chapter 4</a>
• Or, add a link to the bookmark ("Jump to
Chapter 4"), from another page:
<!DOCTYPE html>
<html>
<body>

<p><a href="#C4">Jump to Chapter 4</a></p>

<h2>Chapter 1</h2>
<p>This chapter explains ba bla bla</p>

<h2>Chapter 2</h2>
<p>This chapter explains ba bla bla</p>

<h2>Chapter 3</h2>
<p>This chapter explains ba bla bla</p>

<h2 id="C4">Chapter 4</h2>


<p>This chapter explains ba bla bla</p>

<h2>Chapter 5</h2>
<p>This chapter explains ba bla bla</p>

<h2>Chapter 6</h2>
<p>This chapter explains ba bla bla</p>
</body>
</html>
• Jump to Chapter 4
• Chapter 1
• This chapter explains ba bla bla
• Chapter 2
• This chapter explains ba bla bla
• Chapter 3
• This chapter explains ba bla bla
• Chapter 4
• This chapter explains ba bla bla
• Chapter 5
• This chapter explains ba bla bla
• Chapter 6
• This chapter explains ba bla bla
Lists
• HTML offers web authors three ways for
specifying lists of information. All lists must
contain one or more list elements. Lists may
contain −
– <ul> − An unordered list. This will list items using plain
bullets.
– <ol> − An ordered list. This will use different schemes
of numbers to list your items.
– <dl> − A definition list. This arranges your items in the
same way as they are arranged in a dictionary.
• Unordered Lists
– An unordered list is a collection of related items
that have no special order or sequence.
– This list is created by using block tag <ul> tag.
– Item of a list is specified with an <li> tag(li-list
item)
– Each item in the list is marked with a bullet.
<!DOCTYPE html>
<html>
<head>
<title>HTML Unordered List</title>
</head>
<body>
<ul>
<li>Beetroot</li>
<li>Ginger</li>
<li>Potato</li>
<li>Radish</li>
</ul>
</body>
</html>
• This will produce the following result −
• Beetroot
• Ginger
• Potato
• Radish
• Ordered Lists
– If you are required to put your items in a
numbered list instead of bulleted, then HTML
ordered list will be used.
– This list is created by using <ol> tag.
– The numbering starts at one and is incremented
by one for each successive ordered list element
tagged with <li>.
<!DOCTYPE html>
<html>
<head>
<title>HTML Ordered List</title>
</head>
<body>
<ol>
<li>Beetroot</li>
<li>Ginger</li>
<li>Potato</li>
<li>Radish</li>
</ol>
</body>
</html>
• This will produce the following result −
1. Beetroot
2. Ginger
3. Potato
4. Radish
• Definition Lists : HTML and XHTML supports a list
style which is called definition lists where entries
are listed like in a dictionary or encyclopedia.
– The definition list is the ideal way to present a
glossary, list of terms, or other name/value list.
• Definition List makes use of following three tags.
– <dl> − Defines the start of the list
– <dt> − A term
– <dd> − Term definition
– </dl> − Defines the end of the list
<!DOCTYPE html>
<html>
<head>
<title>HTML Definition List</title>
</head>
<body>
<dl>
<dt> <b>HTML</b> </dt>
<dd>This stands for Hyper Text Markup Language</dd>
<dt> <b>HTTP</b> </dt>
<dd>This stands for Hyper Text Transfer Protocol</dd>
</dl>
</body>
</html>
• This will produce the following result −

HTML
This stands for Hyper Text Markup Language
HTTP
This stands for Hyper Text Transfer Protocol
Table
• The XHTML tables allow web authors to arrange data like
text, images, links, other tables, etc. into rows and columns
of cells.
• The XHTML tables are created using the block tag <table> .
• The most common attribute for the <table> tag is border.
• There are two kinds of lines in tables
– Border : the line around the outside of the whole table.
– Rules : the line that separate the cell from each other.
– The browser has default widths for table border and rules which
is assigned by the value “border” to border attribute.
Otherwise, a number can be given as border’s value.
– <caption> tag - used for the table title which can
immediately follow the opening <table> tag.
– <tr> tag - is used to create table rows.
– <td> tag - is used to create data cells.
• The elements under <td> are regular and left
aligned by default
<!DOCTYPE html>
<html>

<head>
<title>HTML Table Header</title>
</head>

<body>
<table border = "border">
<caption> Employee Database </caption>
<tr>
<th>Name</th>
<th>Salary</th>
</tr>
<tr>
<td>Ramesh Raman</td>
<td>5000</td>
</tr>

<tr>
<td>Shabbir Hussein</td>
<td>7000</td>
</tr>
</table>
</body>

</html>
• This will produce the following result −
• The rowspan and colspan attributes
– In many cases tables have multiple levels of row or
column labels in which one label covers two or
more secondary labels.
– The colspan attributes specification in a table
header or table data tag tells the browser to make
the cell as wide as the specified number of rows
below it in the table.
<!DOCTYPE html>
<html>
<head>
<table border = “border”>
<caption> Report </caption>
</head>
<body>
<table>
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
<tr>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td>February</td>
<td>$80</td>
</tr>
<tr>
<td colspan="2">Sum: $180</td>
</tr>
</table>
</body>
</html>
<table>
<tr>
<th>Month</th>
<th>Savings</th>
<th>Savings for holiday!</th>
</tr>
<tr>
<td>January</td>
<td>$100</td>
<td rowspan="2">$50</td>
</tr>
<tr>
<td>February</td>
<td>$80</td>
</tr>
</table>
• The align and valign attributes
– The placement of the content within a table cell can be
specified with the align and valign attributes in the <tr>,
<th>, and <td> tag.
– The align attribute has the possible values left, right and
center for horizontal placement of the content within a
cell.
– The default alignment for th cell is center and for td it is
left .
– If align is specified in a <tr> tag , it applies to all of the cells
in the row.
– If it is included in a <th> or <td> tag, it only applies to that
cell.
• The valign attribute of the <th> and <td> tags
has the possible value top and bottom.
• The default vertical alignment for both
headings and data is center.
• Because valign applies only to a single cell,
there is never any point in specifying center.
<table border = “border”>
<caption> the align and valign </caption>
<tr align = “center”>
<th> </th>
<th> column Lable 1</th>
<th> column Lable 2</th>
<th> column Lable 3</th>
</tr>
<tr>
<th> align</th>
<td align = “left”>left</td>
<td align = “center”>center</td>
<td align = “right”>right</td>
</tr>
<tr>
<th></br>valign<br /><br /></th>
<td valign = “top”>top</td>
<td valign = “bottom”>bottom</td>
</tr>
</table>
The cellpadding and cellspacing
• The table tag has two attributes that can be used
to specify the spacing between the content of a
table cell and the cell’s edge and spacing
between adjacent cells.
• The cellpadding :
– attribute specifies the space, in pixels, between the
cell wall and the cell content.
– This prevent text from being too close to the edge of
the cell.
<table cellpadding="pixels">
• The cellspacing attribute is used to specifies
the distance between cells in a table.

<table cellspacing="pixels">
<table border = "5" cellspacing = 10 cellpadding = 30>
<caption> Employee Database </caption>
</tr>
<tr>
<th>Name</th>
<th>Salary</th>
<th>address</th>
</tr>
<tr>
<td align = "left">Ramesh </td>
<td>5000</td>
<td>whitefield</td>
</tr>
<tr>
<td align = "right">Shabbir </td>
<td>7000</td>
<td>kundanahalli</td>
</tr>
</table>
Table Section
• Tables naturally occur in two and sometimes three parts:
header, body and footer.
• These three parts can be denoted in XHTML with the thead,
tbody and tfoot elements.
• The header includes the column labels.
• The body includes the data of the table, including the row
labels.
• The footer, when it appears, sometimes has the column
label repeated after the body.
• In some table, the footer contains total for the columns of
data.
• The table can have multiple body sections, in which case
the browser may delimit them with thicker horizontal lines.
Forms
• Most common way for a user to communicate information
from a web browser server is through a form.
• XHTML provides tags to generate the commonly used
objects on a screen form.
• These objects are called controls or widgets.
• There are controls for single-line and multiple-line text
collection, checkboxes, radio buttons, and menus, among
other.
• All control line tags are inline tags.
• Text or button selection gather information from the user.
• Together the value of all the controls in a form are called
the form data.
• Every form requires a submit button which is
used to encode and send the form data to the
Web server for processing.
• The <form> tag
– The XHTML <form> tag which is a block tag defines a
form that is used to collect user input.
– This tag can have several attributes ,only one of which
action is required.
– The action attribute specifies the URL of the
application on the Web server that is to be called
when the user click the Submit button.
• The method attribute of <form> specifies one
of the two techniques , get or post used to
pass the form data to the server.
– Get – it is default method, so if no method
attribute is given in the <form> tag, get will be
used.
– Post – the alternative technique is post.
– In both techniques, the form data is coded into a
text string when the user clicks the Submit button.
• The <input> tag
– Many of the commonly used controls are specified with the
inline tag<input> which is used for text, password, checkboxes,
radio buttons and the action buttons Reset, Submit, and Plain.
– The <input> tag can be displayed in several ways, depending on
the type attribute .
• Here are some examples:
Type Description
<input type="text"> Defines a one-line text input field
<input type="radio"> Defines a radio button (for selecting one of
many choices)
<input type="submit"> Defines a submit button (for submitting the
form)
<html>
<body>

<h2>Text Input</h2>

<form>
First name:<br>
<input type="text" name="firstname">
<br>
Last name:<br>
<input type="text" name="lastname">
</form>

<p>Note that the form itself is not visible.</p>

<p>Also note that the default width of a text input field is 20 characters.</p>

</body>
</html>
• A text control :- refers to as text box, creates a horizontal box into
which the user can type a line of text.
• Default size is 20 character, but size can vary among browser.
• Size of text can be specified by using size attribute of <input>.
• If text is very long then the box is scrolled.
• You can avoid scrolling by fixing maximum number of character by
using maxlength attribute.
• E.g.
<form action = “ ”>
<p>
<input type = “text” name = “name” size = “25”>
</p>
</form>
• Alfred paul von frickenburger
• output
– Ed paul von frickenburger
– The text box would collect the whole string but the string would be
scrolled to the right
• E.g.
<form action = “ ”>
<p>
<input type = “text” name = “name” size = “25”
maxlength = “25” />
</p>
</form>

Input: Alfred paul von frickenburger


Output : Alfred paul von frickenbu
• Password :- if the content of a text box should
not be displayed when it is entered by the
user, a password control can be used.
<input type = “password” name = “mypassword”
size = “10” maxlength = “10” />
• Text boxes as well as most other control
elements, should be labeled. Labeling could be
done by simply inserting text into the
approximate places in the form.
Phone: <input type = “ text” name = “phone”>
• There is no connection between the label and the
control.
• Control and the label can be connected by
putting the control and its label in the content of
a label element.
• <label> phone: <input type = “text” name = “phone”/>
</label>
• Now, the text box and its label are encapsulated
together.
• Benefits of labeling :
– Browser often render the text content of a label element
differently to make it stand out.
– If the text content of a label element is selected, the
cursor is implicitly moved to the control.
– the text content of a label element can be rendered by a
speech synthesizer on the client machine when selected.
This can be a great aid to a user with a visual disability.
• Checkbox and radio controls : used to collect multiple-
choice input from the user.
– A checkbox control is a single button that is either on or
off.
– If a checkbox button is on, the value associated with the
name of the button is the string assigned to its value
attribute.
– A checkbox button does not contribute to the form data if
it is off.
– Every checkbox button require a name attribute and a
value attribute in its <input> tag.
– For form processing on the server, the name identifies the
button and the value is its value (if it is checked).
<!DOCTYPE html>
<html>
<body>
<h1>Show checkboxes:</h1>
<form action="/action_page.php">
<input type="checkbox" name="vehicle1" value="Bike"> I
have a bike<br>
<input type="checkbox" name="vehicle2" value="Car"> I
have a car<br>
<input type="checkbox" name="vehicle3" value="Boat"
checked> I have a boat<br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
• Radio button :- similar to checkbox.
– The difference between a group of radio buttons
and a group of checkboxes is that only one radio
button can be on or pressed at any time.
– Every time a radio button is pressed, the button in
the group that was previously on is turned off.
– The type value for radio buttons is radio.
– All radio buttons in a group must have the name
attribute set in the <input> tag, and all radio
buttons in a group have the same name.
• A radio button definition may specify which
button is to be initially in the pressed, or on
state.
• This is indicated by including the checked
attribute, set to the value checked, in the
<input> of the button’s definition.
• If no radio button in a group is specified as
being checked, the browser usually checks the
first button in the group.
• <html>
• <body>

• <h2>Radio Buttons</h2>

• <form>
• <input type="radio" name="gender" value="male"
checked> Male<br>
• <input type="radio" name="gender" value="female">
Female<br>
• <input type="radio" name="gender" value="other"> Other
• </form>

• </body>
• </html>
• The <select> tag :-
– Menu is used to display large choices.
– A menu is specified with a <select> tag.
– There are two kind of menus: only one menu item can
be selected at time and multiple item can be selected
at a time.
– The default option is one related to radio button.
– The other option can be specified by adding the
multiple attribute, which takes the value “multiple” to
the <select> tag.
– The size attribute can be included in the <select> tag.
– Size specifies the number of menu items that are to
be displayed for the user.
– If no size attribute is specified, the value 1 is used.
• <!DOCTYPE html>
• <html>
• <body>

• <select>
• <option value="volvo">Volvo</option>
• <option value="saab">Saab</option>
• <option value="opel">Opel</option>
• <option value="audi">Audi</option>
• </select>

• </body>
• </html>
• Select tag with size:-
– The size attribute specifies the number of visible
options in a drop-down list.
– If the value of the size attribute is greater than 1,
but lower than the total number of options in the
list, the browser will add a scroll bar to indicate
that there are more options to view.
<!DOCTYPE html>
<html>
<body>

<select size="3">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>

</body>
</html>
• The <Textarea> tag :-
– The <textarea> tag defines a multi-line text input
control.
– A text typed into the area created by <textarea> is
not limited in length and there is implicit scrolling
when needed, both vertically and horizontally.
– The default size of visible area is too small so the
rows and clos attributes should be included in the
text area.
<!DOCTYPE html>
<html>
<head>
<title>HTML textarea Tag</title>
</head>
<body> <form action = “handler">
Fill the Detail:
<br /> <textarea name = "description“ rows = "5"
cols = "50“ >
Enter your name </textarea>
</body>
</html>
• The action buttons :-
– 1. reset :- clears all of the controls in the form to their
initial state.
– 2. submit :- it has two actions
• First , the form data is encoded and sent to the server.
• Second, the server is requested to execute the server-
resident program specified in the action attribute of the
<form> tag.
• The purpose of such a server resident program is to process
the form data and return some response to the user.
• Every form requires a Submit button.
The submit and reset button are created with the <input> tag.
<!DOCTYPE html>
<html>
<body>

<form action="/action_page.php" method="get">


First name: <input type="text" name="fname"><br />
Last name: <input type="text" name="lname"><br/>
<button type="submit" value="Submit">Submit</button>
<button type="reset" value="Reset">Reset</button>
</form>

</body>
</html>
<!DOCTYPE html>
<html>
<body>

<h2>HTML Forms</h2>

<form action="/action_page.php">
First name:<br>
<input type="text" name="firstname" value="Mickey">
<br>
Last name:<br>
<input type="text" name="lastname" value="Mouse">
<br><br>
<input type="submit" value="Submit">
</form>

<p>If you click the "Submit" button, the form-data will be sent to a page called
"/action_page.php".</p>

</body>
</html>
Assignment 1
• Print the squares of the numbers 1 - 20. Each number should be on
a separate line, next to it the number 2 superscripted, an equal sign
and the result. (Example: 102 = 100)
• Print two paragraphs that are both indented using the &nbsp;
command.
• Print two lists with any information you want. One list should be an
ordered list, the other list should be an unordered list.
• Prints an h1 level heading followed by a horizontal line whose width
is 100%. Below the horizontal line print a paragraph relating to the
text in the heading.
• Print some preformatted text of your choosing. (hint: use the <pre>
tag)
• Print a long quote and a short quote. Cite the author of each quote.
UNIT - 2
Introduction
• What is CSS?
– CSS stands for Cascading Style Sheets
– CSS describes how HTML elements are to be
displayed on screen, paper, or in other media
– CSS saves a lot of work. It can control the layout
of multiple web pages all at once
– External stylesheets are stored in CSS files
• Why Use CSS?
– CSS is used to define styles for your web pages,
including the design, layout and variations in
display for different devices and screen sizes.
• CSS Solved a Big Problem
– HTML was NEVER intended to contain tags for formatting a
web page!
– HTML was created to describe the content of a web page,
like:
• <h1>This is a heading</h1>
• <p>This is a paragraph.</p>
– When tags like <font>, and color attributes were added to
the HTML 3.2 specification, it started a nightmare for web
developers. Development of large websites, where fonts
and color information were added to every single page,
became a long and expensive process.
– To solve this problem, the World Wide Web Consortium
(W3C) created CSS.
– CSS removed the style formatting from the HTML page!
Levels of Style Sheet
• The three levels of style sheet are
– Inline :- apply to the content of a single element.
– Document level :- style sheet apply to the whole
body of the document.
– External :- style sheet can apply to the bodies of
any number of documents.
Inline style sheet have precedence over document
style sheet, which have precedence over external
style sheet.
• Inline CSS
– An inline CSS is used to apply a unique style to a
single HTML element.
– An inline CSS uses the style attribute of an HTML
element.
– This example sets the text color of
the <h1> element to blue:
<!DOCTYPE html>
<html>
<body>

<h1 style="color:blue;">This is a Blue Heading</h1>

</body>
</html>
• Internal/ document level CSS
– An internal CSS is used to define a style for a single
document page.
– An internal CSS is defined in the <head> section of
an HTML page, within a <style> element:
<!DOCTYPE html>
<html>
<head>
<style>
body {background-color: powderblue;}
h1 {color: blue;}
p {color: red;}
</style>
</head>
<body>

<h1>This is a heading</h1>
<p>This is a paragraph.</p>

</body>
</html>
• External CSS
– An external style sheet is used to define the style
for many HTML pages.
– With an external style sheet, you can change the
look of an entire web site, by changing one file!
– To use an external style sheet, add a link to it in
the <head> section of the HTML page:
– An external style sheet can be written in any text
editor. The file must not contain any HTML code,
and must be saved with a .css extension.
<!DOCTYPE html> Css file
<html>
<head> body {
<link rel="stylesheet" background-
href="styles.css"> color: powderblue;
</head> }
h1 {
<body> color: blue;
}
<h1>This is a heading</h1> p{
<p>This is a paragraph.</p> color: red;
}
</body>
</html>
Selector Forms
• In CSS, selectors are patterns used to select the
element(s) you want to style.
• Simple selector forms
– The simplest selector form is a single element name, such
as h1.
– In this case, the property values in the rule apply to all
occurrences of the named element.
– The selector could be a list of elements names, separated
by commas, in which case the property values apply to all
occurrences of all the named elements.
– h1 {font-size: 24pt;}
– h2, h3 {font-size: 20pt;}
• Contextual/descendent selector
– Style can only apply to elements in certain
positions in the document.
– This is done by listing the element hierarchy in the
selector, with only whitespace separating the
element names.
• Body b em {font-size: 14pt;}
• Class selectors
– Class selector specifies different occurrences of
the same tag to use different style specifications.
P.normal {property-value list}
P.warning {property-value list}

<p class = “normal”> -----------</p>


<p class = “warning”>-----------</p>
• Generic selectors
– Class of style specifications that applies to the content
of more than one kind of tag.
– The generic class is defined without a tag name.
– It starts with period.
.sale { property – value list}

Body of the document


<h3 class = “sale”> weekend sale </h3>
…..
<p class = “sale”>

</p>
• Id selector
– An id selector allows the application of a style to
one specific element.
– The general form of id selector is
– #specific-id {property-value list}
– E.g.
• #section14 {font-size: 20}

• <h2 id = “section14”> 1.4 claico cats </h2>


• Universal Selector:-
– The universal selector denoted by an asterisk (*)
applies its style to all elements in the document.
* {color: red;}
– Makes all elements in the document red.
– Not often useful.
• What are Pseudo-classes?
– CSS pseudo-classes are used to add special effects
to some selectors.
– You do not need to use JavaScript or any other
script to use those effects. For example, it can be
used to:
• Style an element when a user mouses over it
• Style visited and unvisited links differently
• Style an element when it gets focus
– A simple syntax of pseudo-classes is as follows −

selector:pseudo-class {property: value}


• The most commonly used pseudo-classes are
as follows −
Value Description
:link Use this class to add special style to an unvisited link.
:visited Use this class to add special style to a visited link.
:hover Use this class to add special style to an element when you mouse
over it.
:active Use this class to add special style to an active element.
:focus Use this class to add special style to an element while the
element has focus.
:first-child Use this class to add special style to an element that is the first
child of some other element.
:lang Use this class to specify a language to use in a specified element.
• While defining pseudo-classes in a
<style>...</style> block, following points
should be noted −
– a:hover MUST come after a:link and a:visited in
the CSS definition in order to be effective.
– a:active MUST come after a:hover in the CSS
definition in order to be effective.
– Pseudo-class names are not case-sensitive.
– Pseudo-class are different from CSS classes but
they can be combined.
<!DOCTYPE html>
<html>
<head>
<style>
/* unvisited link */
a:link {
color: red;
}

/* visited link */
a:visited {
color: green;
}

/* mouse over link */


a:hover {
color: hotpink;
}

/* selected link */
a:active {
color: blue;
}
</style>
</head>
<body>

<p><b><a href="default.asp" target="_blank">This is a link</a></b></p>


<p><b>Note:</b> a:hover MUST come after a:link and a:visited in the CSS definition in order to be effective.</p>
<p><b>Note:</b> a:active MUST come after a:hover in the CSS definition in order to be effective.</p>

</body>
</html>
Property value Forms
• CSS1 includes 60 different properties in seven
categories:
– Font
– Lists
– Alignment of text
– Margins
– colors
– Backgrounds
– borders
• Property values can appear in a variety of forms.
• Keyword property value :- used when there are
only few possible values and they are predefined.
E.g small, large and medium.
• Number values:- used when no meaningful units
can be attached to a numeric property value.
• Length value
• Percentage value
• URL value
• Color
Font Properties
• The font-family property is used to change the face of
a font.
• The font-style property is used to make a font italic or
oblique.
• The font-variant property is used to create a small-caps
effect.
• The font-weight property is used to increase or
decrease how bold or light a font appears.
• The font-size property is used to increase or decrease
the size of a font.
• The font property is used as shorthand to specify a
number of other font properties.
• Set the Font Family
– Following is the example, which demonstrates
how to set the font family of an element. Possible
value could be any font family name.
• <html>
• <head>
• </head>
• <body> <p style="font
family:georgia,garamond,serif;"> This text is
rendered in either georgia, garamond, or the
default serif font depending on which font you
have at your system. </p>
• </body>
• </html>
• It will produce the following result −

This text is rendered in either georgia, garamond, or the


default serif font depending on which font you have at your
system.
• Set the Font Style
– Following is the example, which demonstrates
how to set the font style of an element. Possible
values are normal, italic and oblique.
<html>
<head>
</head>
<body>
<p style="font-style:italic;"> This text will
be rendered in italic style </p>
</body>
</html>

It will produce the following result −

This text will be rendered in italic style


• Set the Font Variant
– The following example demonstrates how to set
the font variant of an element. Possible values
are normal and small-caps.
<html>
<head>
</head>
<body> <p style="font-variant:small-caps;">
This text will be rendered as small caps </p>
</body>
</html>

It will produce the following result −

This text will be rendered as small caps


• Set the Font Weight
– The following example demonstrates how to set
the font weight of an element. The font-weight
property provides the functionality to specify how
bold a font is. Possible values could be normal,
bold, bolder, lighter, 100, 200, 300, 400, 500, 600,
700, 800, 900.

<html>
<head>
</head>
<body> <p style="font-weight:bold;">This
font is bold.</p>
<p style="font-weight:bolder;">This font is
bolder.</p>
<p style="font-weight:500;">This font is 500
weight.</p>
</body>
</html>

It will produce the following result −


• This font is bold.
• This font is bolder.
• This font is 500 weight.
• Set the Font Size
• The following example demonstrates how to
set the font size of an element. The font-size
property is used to control the size of fonts.
Possible values could be xx-small, x-small,
small, medium, large, x-large, xx-large,
smaller, larger, size in pixels or in %.
<html>
<head>
</head>
<body>
<p style="font-size:20px;">This font
size is 20 pixels</p>
<p style="font-size:small;">This font
size is small</p>
<p style="font-size:large;">This font
size is large</p>
</body>
</html>
• It will produce the following result

• This font size is 20 pixels


• This font size is small
• This font size is large
• Set the Font Size Adjust
– The following example demonstrates how to set
the font size adjust of an element. This property
enables you to adjust the x-height to make fonts
more legible. Possible value could be any number.
<html>
<head>
</head>
<body>
<p style="font-size-adjust:0.61;"> This text is
using a font-size-adjust value. </p>
</body>
</html>

It will produce the following result −

This text is using a font-size-adjust value.


• Set the Font Stretch
– The following example demonstrates how to set
the font stretch of an element. This property relies
on the user's computer to have an expanded or
condensed version of the font being used.
– Possible values could be normal, wider, narrower,
ultra-condensed, extra-condensed, condensed,
semi-condensed, semi-expanded, expanded, extra-
expanded, ultra-expanded.
<html>
<head>
</head>
<body>
<p style="font-stretch:ultra-expanded;"> If
this doesn't appear to work, it is likely that your
computer doesn't have a condensed or expanded
version of the font being used. </p>
</body>
</html>
• It will produce the following result −
If this doesn't appear to work, it is likely that
your computer doesn't have a condensed or
expanded version of the font being used.
• Shorthand Property
– You can use the font property to set all the font
properties at once. For example −
<html>
<head>
</head>
<body>
<p style="font:italic small-caps bold 15px
georgia;"> Applying all the properties on
the text at once. </p>
</body>
</html>
• It will produce the following result −

Applying all the properties on the text at


once.
• Text Decoration :- The text decoration property is used
specify some special features of text.
• Possible Values
– none − No decoration should be added to the inline text.
– underline − An underline is drawn beneath the inline text.
– overline − An overline is drawn above the inline text.
– line-through − A line should be drawn through the middle
of the inline text.
– blink − The inline text should blink on and off, analogous to
the BLINK element introduced by Netscape.
<!DOCTYPE html>
<html>
<head>
<style>
h1 { text-decoration: overline;}
h2 { text-decoration: line-through;}
h3 { text-decoration: underline;}
h4 { text-decoration: underline overline;}
h5 { text-decoration: none;}
</style>
</head>
<body>
<h1>This is heading 1</h1>
<h2>This is heading 2</h2>
<h3>This is heading 3</h3>
<h4>This is heading 4</h4>
<h5>This is heading 5</h5>

</body>
</html>
• The letter-spacing property :- increases or
decreases the space between characters in a
text.
<!DOCTYPE html>
<html>
<head>
<style>
h1 { letter-spacing: 3px;}
h2 { letter-spacing: 2px;}
h3 { letter-spacing: -1px;}
</style>
</head>
<body>

<h1>This is heading 1</h1>


<h2>This is heading 2</h2>
<h3>This is heading 3</h3>
</body>
</html>
List properties
• Lists are very helpful in conveying a set of
either numbered or bullet points.
• The CSS list properties allow you to:
– Set different list item markers for ordered lists
– Set different list item markers for unordered lists
– Set an image as the list item marker
• We have the following CSS properties, which
can be used to control lists:
• The list-style-type allows you to control the
shape or appearance of the marker.
• The list-style-image specifies an image for the
marker rather than a bullet point or number.
• The list-style-type property allows you to
control the shape or style of bullet point in the
case of unordered lists and the style of
numbering characters in ordered lists.
<!DOCTYPE html>
<html>
<head>
<style>
ul.a { list-style-type: circle;}

ul.b { list-style-type: square;}

</style>
</head>
<body>

<p>Example of unordered lists:</p>


<ul class="a">
<li>Coffee</li>
<li>Tea</li>
<li>Coca Cola</li>
</ul>

<ul class="b">
<li>Coffee</li>
<li>Tea</li>
<li>Coca Cola</li>
</ul>

</body>
</html>
<!DOCTYPE html>
<html>
<head>
<style>

ol.c { list-style-type: upper-roman;}


ol.d { ist-style-type: lower-alpha;}
</style>
</head>
<body>
<p>Example of ordered lists:</p>
<ol class="c">
<li>Coffee</li>
<li>Tea</li>
<li>Coca Cola</li>
</ol>
<ol class="d">
<li>Coffee</li>
<li>Tea</li>
<li>Coca Cola</li>
</ol>
</body>
</html>
• The list-style-image property
– The list-style-image allows you to specify an image
so that you can use your own bullet style.
<style type = “text/css”>
li.image{list-style-image:url(img1.gif)}
</style>
<li class = “image”> image of plane </li>
<!DOCTYPE html>
<html>
<head>
<style>
ul {
list-style-image: url('sqpurple.gif');
}
</style>
</head>
<body>

<ul>
<li>Coffee</li>
<li>Tea</li>
<li>Coca Cola</li>
</ul>

</body>
</html>
Alignment of text
• The first line of a paragraph can be indented using the
text – indent property.
• This property takes either a length or a percentage
value.
<style type = “text/css ”>
p.Indent {text- indent: 0.5in}
</style>

<p class = “indent”> The first line of a paragraph can be


indented using the text – indent property. This
property takes either a length or a percentage value.
</p>
• The text-align property , for which the
possible keyword values are left, right and
justify is used to arrange text horizontally.
<!DOCTYPE html>
<html>
<head>
<style>
h1 { text-align: center;}
p.date { text-align: right;}
p.main {text-align: justify;}
</style>
</head>
<body>
<h1>CSS text-align Example</h1>
<p class="date">May, 2014</p>
<p class="main">In my younger and more vulnerable years my father gave me some
advice that I've been turning over in my mind ever since. 'Whenever you feel like
criticizing anyone,' he told me, 'just remember that all the people in this world
haven't had the advantages that you've had.'</p>
<p><b>Note:</b> Resize the browser window to see how the value "justify"
works.</p>
</body>
</html>
• Float property :- it is used to specify that text
should flow around some element.
• The possible values for float are left, right and
none which is the default.
<!DOCTYPE html>
<html>
<head>
<style>
img {
float: right;
}
</style>
</head>
<body>
<h1>The float Property</h1>

<p>In this example, the image will float to the right in the text, and the text in the paragraph will
wrap around the image.</p>

<p><img src="pineapple.jpg" alt="Pineapple" style="width:170px;height:170px;margin-


left:15px;">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum
interdum, nisi lorem egestas odio, vitae scelerisque enim ligula venenatis dolor.</p>
</body>
</html>
Color
• Color group :-
– Three levels of collections of colors might be used by
an XHTML document.
– The smallest useful set of colors includes only those
that have standard names and are guaranteed to be
correctly displayable by all browsers on all color
monitors.
– This collection of sixteen colors is called the named
colors.
– A larger set of color, called the Web palette, includes
216 colors
• Color properties:-
– The color property is used to specify the
foreground color of XHTML elements.
!DOCTYPE html>
<html>
<head>
<style>
body {color: red;}

h1 { color: #00ff00;}

p.ex { color: rgb(0,0,255);}


</style>
</head>
<body>

<h1>This is heading 1</h1>

<p>This is an ordinary paragraph. Notice that this text is red. The default text-color for a page is
defined in the body selector.</p>

<p class="ex">This is a paragraph with class="ex". This text is blue.</p>

</body>
</html>
• The background-color property is used to set
the background color of an element where the
element could be the whole body of the
document.
<!DOCTYPE html>
<html>
<head>
<style>
body {
background-color: coral;
}
</style>
</head>
<body>

<h1>The background-color Property</h1>

<p>The background color can be specified with a color name.</p>

</body>
</html>
• The <div> and <span> Tags:-
– The <div> tag defines a division or a section in an
HTML document.
– The <div> element is often used as a container for
other HTML elements to style them with CSS or to
perform certain tasks with JavaScript.
<!DOCTYPE html>
<html>
<body>

<p>This is some text.</p>

<div style="background-color:lightblue">
<h3>This is a heading in a div element</h3>
<p>This is some text in a div element.</p>
</div>

<p>This is some text.</p>

</body>
</html>
• <span> :- provides special font properties to
some part of the paragraph.
• It can give different font size and color to word
or phase in a line.
<!DOCTYPE html>
<html>
<body>

<p>My mother has <span style="color:blue;font-


weight:bold">blue</span> eyes and my father has
<span style="color:darkolivegreen;font-
weight:bold">dark green</span> eyes.</p>

</body>
</html>
The Box Model
• Virtually all the documents can have borders.
• These borders have various styles such as color and width.
• The amount of space between the content of an element
and its border known as padding.
• The space between the border and an adjacent element
known as the margin.
• Explanation of the different parts:
– Content - The content of the box, where text and images appear
– Padding - Clears an area around the content. The padding is
transparent
– Border - A border that goes around the padding and content
– Margin - Clears an area outside the border. The margin is
transparent
<head>
<style>
div {
background-color: lightgrey;
width: 300px;
border: 25px solid green;
padding: 25px;
margin: 25px;
}
</style>
</head>
<body>

<h2>Demonstrating the Box Model</h2>

<p>The CSS box model is essentially a box that wraps around every HTML element. It consists of:
borders, padding, margins, and the actual content.</p>

<div>This text is the actual content of the box. We have added a 25px padding, 25px margin and a 25px
green border. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex
ea commodo consequat. </div>

</body>
</html>
UNIT - 3
The basic of JavaScript
Overview of JavaScript
• JavaScript was first known as LiveScript, but Netscape changed its
name to JavaScript, possibly because of the excitement being
generated by Java.
• JavaScript made its first appearance in Netscape 2.0 in 1995 with
the name LiveScript. The general-purpose core of the language has
been embedded in Netscape, Internet Explorer, and other web
browsers.
• The ECMA-262 Specification defined a standard version of the core
JavaScript language.
– JavaScript is a lightweight, interpreted programming language.
– Designed for creating network-centric applications.
– Complementary to and integrated with Java.
– Complementary to and integrated with HTML.
– Open and cross-platform
• Javascript can be divided into three parts
– The core - it is the heart of the language,
including its operators, expressions, statements
and subprograms.
– Client-side javascript :- is a collection of object
that support control of a browser and interactions
with users.
– Server side :- it is a collection of objects that make
the language useful on a web server.
Advantages of JavaScript
• The merits of using JavaScript are −
– Less server interaction − You can validate user input before
sending the page off to the server. This saves server traffic,
which means less load on your server.
– Immediate feedback to the visitors − They don't have to wait
for a page reload to see if they have forgotten to enter
something.
– Increased interactivity − You can create interfaces that react
when the user hovers over them with a mouse or activates
them via the keyboard.
– Richer interfaces − You can use JavaScript to include such items
as drag-and-drop components and sliders to give a Rich
Interface to your site visitors.
Limitations of JavaScript
• We cannot treat JavaScript as a full-fledged
programming language. It lacks the following
important features −
– Client-side JavaScript does not allow the reading or writing
of files. This has been kept for security reason.
– JavaScript cannot be used for networking applications
because there is no such support available.
– JavaScript doesn't have any multithreading or
multiprocessor capabilities.
– Once again, JavaScript is a lightweight, interpreted
programming language that allows you to build
interactivity into otherwise static HTML pages.
• JavaScript can be implemented using JavaScript statements
that are placed within the <script>... </script>.
• You can place the <script> tags, containing your JavaScript,
anywhere within your web page, but it is normally
recommended that you should keep it within
the <head> tags.
• The <script> tag alerts the browser program to start
interpreting all the text between these tags as a script. A
simple syntax of your JavaScript will appear as follows.
– Type − This attribute is what is now recommended to indicate
the scripting language in use and its value should be set to
"text/javascript".
<html>
<body>
<script language="javascript“
type="text/javascript">
<!-- document.write("Hello World!") //-->
</script>
</body>
</html>
• The java script has two types of comments
• // :- two adjacent slashes appears on a line ,
the rest of the line is considered a comment.
• /* --------*/ :- both single line and multiple-line
comment can be written using /* */ to
terminate.
• There are two issues regarding embedding
JavaScript in XHTML document.
1. There are some browsers still in use that
recognize the <script> tag but do not have
JavaScript interpreters. These browsers simply
ignores the contents of the script element and
cause no problem.
2. Some old browsers do not recognize the <script>
tag. Such a browser would display the contents
of the script element as if it were just text.
• It has been customary to enclose the content
of all script elements in XHTML comments to
avoid this problem.
• The XHTML validator also has a problem with
embedded JavaScript.
• When the embedded JavaScript happens to
include recognizable tags (e.g. <br /> ) tags in
the output of the JavaScript they often cause
the validation error.
• The XHTML comment introduction (<! --)
works prelude to JavaScript code.

<!- -
---JavaScript Script
// -- >
Primitive, operations and expressions
• Primitive types :- A primitive data value is a single simple
data value with no additional properties and methods.
• JavaScript has five primitive types: Number, string,
Boolean, Undefined and Null.
• Wrapper objects :- pre defined object closely related to the
Number, Boolean and string types named number, string
and Boolean.
• Each contains a property that stores a value of the
corresponding primitive type.
• The purpose of the wrapper object is to provide properties
and methods that are convenient for use with values of the
primitive types.
• In the case of number, the properties are
more useful.
• In the case of string, the methods are more
useful.
• Number :- JavaScript has only one type of
numbers.
• Numbers can be written with, or without
decimals:
• All numeric literals are values of type Number.
• E.g
• 72, 7.2, .72,72., 7E2,7e2,.7e2,7.e2,7.2E-2
<!DOCTYPE html> JavaScript Numbers
<html> Numbers can be written with, or without
<body> decimals:
34
<h2>JavaScript Numbers</h2> 34
3.14
<p>Numbers can be written with, or
without decimals:</p>

<script>
var x1 = 34.00;
var x2 = 34;
var x3 = 3.14;

document.write(x1 + "<br>" + x2 +
"<br>" + x3);
</script>

</body>
</html>
• String: A string (or a text string) is a series of
characters like "John Doe".
• Strings are written with quotes. You can use
single or double quotes.
• All string literals are primitive values.
<!DOCTYPE html> • JavaScript Strings
<html> Strings are written with quotes. You can
<body> use single or double quotes:
Volvo XC60
<h2>JavaScript Strings</h2> Volvo XC60

<p>Strings are written with quotes. You


can use single or double quotes:</p>

<script>
var carName1 = "Volvo XC60";
var carName2 = 'Volvo XC60';

document.write(
carName1 + "<br>" + carName2);
</script>

</body>
</html>
• Booleans :- Booleans can only have two
values: true or false.
<!DOCTYPE html> JavaScript Booleans
<html> Booleans can have two values: true or false:
<body> True
false
<h2>JavaScript Booleans</h2>

<p>Booleans can have two values: true


or false:</p>

<script>
var x = 5;
var y = 5;
var z = 6;
document.write(
(x == y) + "<br>" + (x == z));
</script>

</body>
</html>
• Undefined
– In JavaScript, a variable without a value, has the
value undefined. The typeof is also undefined.
– There is no reserve word undefined. If a variable
has been explicitly declared, but not assigned a
value , it has the value undefined.
– If the value of an undefined variable is displayed,
the word “undefined” is displayed .
<!DOCTYPE html> JavaScript
<html> The value (and the data type) of a
<body> variable with no value is undefined.
undefined
<h2>JavaScript</h2>

<p>The value (and the data type)


of a variable with no value is
<b>undefined</b>.</p>

<script>
var car;
document.write(car);
</script>

</body>
</html>
• Null:- Null indicate no value. A variable is null
if it has not been explicitly declared or
assigned a value.
• If an attempt is made to use the value of a
variable whose value is null, it will cause a
runtime error.
• Declaring Variables :-
– Like many other programming languages, JavaScript has
variables. Variables can be thought of as named containers. You
can place data into these containers and then refer to the data
simply by naming the container.
– Variable can be used for anything. Variables are not typed,
values are.
– A variable can have the value of any primitive type, or it can be
a reference to any object.
– The type of the value of a particular appearance of a variable in
a program is determined by the interpreter.
– Before you use a variable in a JavaScript program, you must
declare it. Variables are declared with the var keyword as
follows.
<script type="text/javascript">
<!–
var money;
var name;
//-->
</script>
• You can also declare multiple variables with
the same var keyword as follows
<script type="text/javascript">
<!--
var money, name;
//-->
</script>
• Storing a value in a variable is called variable
initialization. You can do variable initialization at
the time of variable creation or at a later point in
time when you need that variable.
<script type="text/javascript">
<!--
var name = "Ali";
var money;
//-->
</script>
operator
• Let us take a simple expression 4 + 5 is equal to 9.
Here 4 and 5 are called operands and ‘+’ is called
the operator. JavaScript supports the following
types of operators.
– Arithmetic Operators
– Comparison Operators
– Logical (or Relational) Operators
– Assignment Operators
– Conditional (or ternary) Operators
• Binary operator:-
– + for addition
– - for subtraction
– * for multiplication
– / for division
– % for modulus.
• Unary operators :-
– + plus
– - negate
– -- decrement
– ++ increment
– E.g. If a = 7
• (++a)*3 = 24
• Where as (a++)* 3 = 21
• In both cases a is set to 8.
• The math object:- The Math object provides a
collection of properties of Number objects
and methods that operate on Number
Objects.
<!DOCTYPE html> JavaScript Math.PI
<html> Math.PI returns the ratio of a
<body> circle's circumference to its
diameter:
<h2>JavaScript Math.PI</h2> 3.141592653589793
<p>Math.PI returns the ratio
of a circle's circumference
to its diameter:</p>

<script>
document.write( Math.PI);
</script>

</body>
</html>
• Math.round() :- Math.round(x) returns the value of x
rounded to its nearest integer
• Math.pow():- Math.pow(x, y) returns the value of x to the
power of y
• Math.sqrt() :-Math.sqrt(x) returns the square root of x
• Math.abs() :- Math.abs(x) returns the absolute (positive)
value of x
• Math.ceil() :- Math.ceil(x) returns the value of x
rounded up to its nearest integer
• Math.floor() :- Math.floor(x) returns the value of x
rounded down to its nearest integer
• Math.sin() :- Math.sin(x) returns the sine (a value between -
1 and 1) of the angle x (given in radians).
• Math.cos() :- Math.cos(x) returns the cosine (a
value between -1 and 1) of the angle x (given
in radians).
• Math.min() and Math.max() :- Math.min() and
Math.max() can be used to find the lowest or
highest value in a list of arguments
• Math.random() :- Math.random() returns a
random number between 0 (inclusive), and 1
(exclusive)
• The Number object :- the number object
includes a collection of useful properties that
have constant values.
Property Description
constructor Returns the function that created
JavaScript's Number prototype
MAX_VALUE Returns the largest number possible in
JavaScript
MIN_VALUE Returns the smallest number possible in
JavaScript
NEGATIVE_INFINITY Represents negative infinity (returned on
overflow)
NaN Represents a "Not-a-Number" value
POSITIVE_INFINITY Represents infinity (returned on overflow)
prototype Allows you to add properties and methods
to an object
• NaN(not a number) :- any arithmetic operation
that results in an error or that produces a value
that cannot be represented as a double-precision
floating-point number, such as one that is too
large (overflow), returns the value NaN.
• If NaN is compared for equality against any
number, the comparison fails.
• To determine whether a variable has the NaN
value, the predefined function isNaN() must be
used.
<!DOCTYPE html> false: 123
<html> true: 0 / 0
<body>

<script>
{
document.write( Number.isNaN(123) +
": 123<br>");
document.write(Number.isNaN(0 / 0) +
": 0 / 0<br>");

}
</script>

</body>
</html>
• The toString() :-method converts a number to
a string.
• The String Catenation operator :- JavaScript
string are not stored or treated as array of
characters rather they are unit scalar values.
• The + operator can also be used to add
(concatenate) strings.
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Operators</h2>
JavaScript Operators
<p>The + operator concatenates The + operator concatenates
(adds) strings.</p> (adds) strings.
John Doe
<script>
var txt1 = "John";
var txt2 = "Doe";
document.write(txt1 + " " + txt2);
</script>

</body>
</html>
• Implicit Type conversions :-
– The JavaScript interpreter performs several
different implicit type conversions called as
coercions.
– When value of one type is used in a position that
requires a value of a different , JavaScript attempts
to convert the value to the type that is required.
• Adding two numbers, will return the
sum, but adding a number and a
string will return a string

<!DOCTYPE html>
<html> • JavaScript Operators
<body> Adding a number and a string, returns a
<h2>JavaScript Operators</h2> string.
<p>Adding a number and a string, 10
returns a string.</p> 55
Hello5
<script>
var x = 5 + 5;
var y = "5" + 5;
var z = "Hello" + 5;
document.write(x + "<br>" + y + "<br>" +
z);
</script>

</body>
</html>
• Explicit type conversions :- there are several
different ways to force type conversions,
primarily between string and numbers. String
that contain numbers can be converted to
numbers with the string constructor, as in the
following :
– var str_value = string(value)
– This conversion can also be done with the toString
method, which has the advantage that it can be given
a parameter to specify the base of the resulting
number.
• For eg.
– Var num = 6;
– Var str_value = num.toString();
– Var str_value_binary = num.toString(2);

– In the first conversion , the result is 6.


– In the second conversion , the result is 110
– A number also converted to a string by
concatenating it with the empty string.
• String can be explicitly converted to number in
a variety of ways.
• The number constructor can be used as in the
following :
– Var number = Number(aString);
– The same conversion could be specified by
subtracting zero from the string as in the
following:
– Var number = aString – 0;
• Both of these conversions has following
restriction:
– The number in the string cannot be followed by
any character except a space.
JavaScript has two predefined string functions that
do not have this problem
These two , parseInt and parseFloat are not string
methods, so they are not called through String
objects; however, they operate on the string given
as parameters.
1. parseInt :- this function searches the string
for an integer literals.
– If one is found at the beginning of the string, it is
converted to a number and returned.
– If string does not begin with a valid integer
literal, NaN is returned.
<!DOCTYPE html>
<html>
<body>
<script>
{
var a = parseInt("10") + "<br>"; • 10
var b = parseInt("10.00") + "<br>"; 10
var c = parseInt("10.33") + "<br>"; 10
34
var d = parseInt("34 45 66") + "<br>"; 60
var e = parseInt(" 60 ") + "<br>"; 40
var f = parseInt("40 years") + "<br>"; NaN
var g = parseInt("He was 40") + "<br>";

var n = a + b + c + d + e + f + g ;
document.write(n);
}
</script>

</body>
</html>
• ParseFloat : similar to parseInt but it searches
for a floating point literal, which could have a
decimal point or an exponent or both.
<html>
<body>
<script>
{
var a = parseFloat("10") + "<br>";
var b = parseFloat("10.00") + "<br>"; • 10
10
var c = parseFloat("10.33") + "<br>"; 10.33
var d = parseFloat("34 45 66") + 34
"<br>"; 60
var e = parseFloat(" 60 ") + "<br>"; 40
var f = parseFloat("40 years") + "<br>"; NaN
var g = parseFloat("He was 40") +
"<br>";

var n = a + b + c + d + e + f + g;
document.write(n);
}
</script>
</body>
</html>
• String properties and methods :
– The String object includes property, length, and
large collection of methods.
– String methods can always be used through String
primitive values.
String Length :-
The length property returns the length of a string.
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript String JavaScript String Properties


Properties</h2> The length property returns the
length of a string:
<p>The length property returns the 26
length of a string:</p>

<script>
var txt =
"ABCDEFGHIJKLMNOPQRSTUVWX
YZ";
document.write(txt.length);
</script>

</body>
</html>
• Finding a String in a String
– The indexOf() method returns the index of (the
position of) the first occurrence of a specified text
in a string.
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript String Methods</h2>


• JavaScript String Methods
<p>The indexOf() method returns the The indexOf() method returns the
position of the first occurrence of a position of the first occurrence of a
specified text:</p> specified text:
7
<script>
var str = "Please locate where 'locate'
occurs!";
var pos = str.indexOf("locate");
document.write(pos);
</script>

</body>
</html>
• The substring() Method :- extracts a part of a
string and returns the extracted part in a new
string.
• The method takes 2 parameters: the starting
index (position), and the ending index (position).
• The substring() cannot accept negative indexes.
• Syntax :- substring(start, end)
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript String Methods</h2> • JavaScript String Methods


The substr() method extract a part of
<p>The substr() method extract a a string and returns the extracted
part of a string parts in a new string:
and returns the extracted parts in a Banana
new string:</p>

<script>
var str = "Apple, Banana, Kiwi";
var res = str.substring(7,13);
document.write(res);
</script>

</body>
</html>
• A string is converted to upper case
with toUpperCase()
• A string is converted to lower case
with toLowerCase()
<!DOCTYPE html> Convert string to upper case:
<html> hello world :- HELLO WORLD
<body>

<p>Convert string to upper case:</p>

<script>
{
var text1 = "hello world";
var text2 = text1.toUpperCase();
document.write(text1 + " :- " + text2);

}
</script>

</body>
</html>
• The charAt() Method
– The charAt() method returns the character at a
specified index (position) in a string
<!DOCTYPE html> JavaScript String Methods
<html> The charAt() method returns the
<body> character at a given position in a
string:
<h2>JavaScript String Methods</h2> H

<p>The charAt() method returns the


character at a given position in a
string:</p>
<script>
var str = "HELLO WORLD";
var str1 = str.charAt(0);
document.write(str1);
</script>
</body>
</html>
• The typeof operator
– It returns the type of its single operand.
– typeof evaluates to “number”, “string”, or
“boolean” if operand is of primitive type Number,
String or respectively.
– If the operand is an object or null, typeof evalutes
to “object”.
– If operand is a variable that has not been assigned
a value typeof evaluates to “undefined”.
Primitive

<!DOCTYPE html>
<html>
<body>
• JavaScript typeof
The typeof operator returns the type of a
<h2>JavaScript typeof</h2> variable or an expression.
<p>The typeof operator returns the type
of a variable or an expression.</p>
string
number
<script> boolean
document.write( boolean
typeof "john" + "<br>" + undefined
typeof 3.14 + "<br>" +
typeof true + "<br>" +
typeof false + "<br>" +
typeof x);
</script>

</body>
</html>
Object and Function

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript typeof</h2> JavaScript typeof


<p>The typeof operator returns object for both The typeof operator returns object for both
objects, arrays, and null.</p> objects, arrays, and null.
<p>The typeof operator does not return object The typeof operator does not return object for
for functions.</p> functions.

<script>
document.write( object
object
typeof {name:'john', age:34} + "<br>" + object
typeof [1,2,3,4] + "<br>" + function
typeof null + "<br>" +
typeof function myFunc(){});
</script>

</body>
</html>
• Assignment statements :-
– Similar to other programming languages.
– It is denoted by =
– A host of compound assignment operators such as
+= and /=.
– Eg. a +=7; means a = a + 7
The Date Object
• The Date object :- use to represent the specific
date and time and manipulate them.
• It is a rich collection of methods.
• The Date object is created, naturally with the new
operator and the Date constructor, which has
several forms.
• E.g. var today = new Date();
• The Date and time properties of a Date object are
in two forms, local and Coordinated Universal
Time (UTC, which was formerly named
Greenwich Mean Time).
• Method of the Date object :-
– toLocaleString :- A string of the Date information.
– getDate :- the day of the month
– getMonth :- the month of the year, as a number in the range of
0 to 11.
– getDay :- the day of the week, as a number in the range of 0 to
6.
– getFullYear :- the year
– getTime :- the number of milliseconds since January 1, 1970.
– getHours :- the number of the hour, as a number in the range of
0 to 23.
– getMinutes :- the number of the minute, as a number in the
range of 0 to 59.
– getSeconds :- the number of the second, as a number in the
range of 0 to 59.
– getMilliseconds :- the number of the millisecond, as a number in
the range of 0 to 59.
<!DOCTYPE html>
<html>
<body>
JavaScript new Date()
<h2>JavaScript new Tue Sep 25 2018 12:09:28
Date()</h2> GMT-0400 (Eastern
Daylight Time)
<script>
var d = new Date();
document.write( d );
</script>

</body>
</html>
Screen output and keyboard Input

• JavaScript models the XHTML document with


the Document object.
• The window in which the browser displays an
XHTML document is modeled with the
Window object.
• The Window object includes two properties,
document and Window.
• The document object has several properties
and methods.
• document.write():- used to create a script output.
• alert() :- open a dialog window and display its parameter in that
window. It also displays an OK button.
– The parameter string to alert is not XHTML code. It is a plain text.
– Therefore , the string parameter to alert may include \n but never
include <br />.
<!DOCTYPE html>
<html>
<body>
<h2>My First Web Page</h2>
<p>My first paragraph.</p>
<script>
alert(5 + 6);
</script>
</body>
</html>
• confirm() Method :-
– The confirm() method displays a dialog box with a
specified message, along with an OK and a Cancel
button.
– A confirm box is often used if you want the user to
verify or accept something.
– The confirm() method returns true if the user
clicked "OK", and false otherwise.
<!DOCTYPE html>
<html>
<body>

<p>Click the button to display a confirm


box.</p>

<script>

confirm("Press a button!");

</script>

</body>
</html>
• The prompt() method displays a dialog box that
prompts the user for input.
• A prompt box is often used if you want the user
to input a value before entering a page.
• When a prompt box pops up, the user will have
to click either "OK" or "Cancel" to proceed after
entering an input value.
• The prompt() method returns the input value if
the user clicks "OK". If the user clicks "cancel" the
method returns null.
<!DOCTYPE html>
<html>
<body>

<script>
var person = prompt("Please
enter your name", "Harry
Potter");

</script>

</body>
</html>
• alert, prompt, and confirm cause the browser
to wait for a user response.
• In case of alert, the OK button must pressed
for the JavaScript interpreter to continue.
• The prompt and confirm method wait for
either OK or Cancel to be pressed.
Control Statements
• Control expressions
• Selection Statements :- Use if to specify a block of code to be
executed, if a specified condition is true
<!DOCTYPE html>
<html>
<body>
<script>
var a = 10;
var b = 5;
if (a > b)
document.write(a);
</script>
</body>
</html>

Output :- 10
• The else Statement :- Use the else statement to specify a block of code to
be executed if the condition is false.

<!DOCTYPE html>
<html>
<body>
<script>
var a = 5;
var b = 55;
if (a > b)
document.write(a);
else
document.write(b);
</script>

</body>
</html>
• Output :- 55
Use the switch statement to select one of many
code blocks to be executed.
<!DOCTYPE html> Wednesday
<html>
<body>

<script>
var day;
switch (new Date().getDay()) {
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
}
document.write(day);
</script>

</body>
</html>
• The For Loop
– The for loop has the following syntax:
for (statement 1; statement 2; statement 3) {
code block to be executed }

• Statement 1 is executed (one time) before the


execution of the code block.
• Statement 2 defines the condition for executing the
code block.
• Statement 3 is executed (every time) after the code
block has been executed.
<!DOCTYPE html> BMW
<html> Volvo
<body> Saab
Ford
<script>
var cars = ["BMW", "Volvo", "Saab", "Ford"];

var i = 0;
var len = cars.length;
var text = "";

for (; i < len; ) {


text += cars[i] + "<br>";
i++;
}
document.write(text);
</script>

</body>
</html>
• The While Loop :- The while loop loops <!DOCTYPE html>
through a block of code as long as a specified <html>
condition is true. <body>

<h2>JavaScript while</h2>
• Output <script>
JavaScript while var text = "";
The number is 0 var i = 0;
The number is 1 while (i < 10) {
The number is 2 text += "<br>The number is " + i;
The number is 3 i++;
The number is 4 }
The number is 5
The number is 6 document.write(text);
The number is 7 </script>
The number is 8
The number is 9 </body>
</html>
• The Do/While Loop <!DOCTYPE html>
<html>
• The do/while loop is a <body>
variant of the while loop.
This loop will execute the <h2>JavaScript do ... while</h2>
code block once, before
checking if the condition is <script>
true, then it will repeat the var text = ""
var i = 0;
loop as long as the
condition is true. do {
text += "<br>The number is " + i;
i++;
• Output
}
JavaScript do ... while
while (i < 10);
The number is 0
The number is 1
The number is 2 document.write(text);
The number is 3
The number is 4 </script>
The number is 5
The number is 6
The number is 7
The number is 8 </body>
The number is 9
</html>
Object Creation and Modification
• Object are often created with a new
expression, which must include a call to a
constructor method.
• In JavaScript, the new operator creates a blank
object, or one with no properties.
• JavaScript object do not have type.
• The constructor both creates and initialized
the properties.
• The following statement creates an object that initially
has no properties.
– var my_object = new object();
– The properties of an object are accessed using dot
notation, in which the first word is the object name and
the second is the property name.
– Properties are not actually variables – they are just the
names of values.
– The number of properties in a JavaScript object is dynamic.
– At any time during interpretation, properties can be added
to or deleted from an object.
– A property for an object is created by assigning a value to
that property.
– var my_car = new object();
• Create and initialize the make property
– My_car.make = “Ford”;
• Create and initialize model
– my_car.model = “Countour SVT”;
• This code creates a new object, my_car, with
two properties, make and model.
<!DOCTYPE html> • Output
<html> John is 50 years old.
<body>

<script>
var person = new Object();
person.firstName = "John";
person.lastName = "Doe";
person.age = 50;
person.eyeColor = "blue";

document.write(person.firstName + " is " +


person.age + " years old.");
</script>

</body>
</html>
• Another way to create object and its <!DOCTYPE html>
properties: <html>
• Object Literal <body>
eg.
<p>Creating a JavaScript Object.</p>
var my_car = {make: “ford”, model:
“coutourSVT”} <script>
var person = {firstName:"John", lastName:"Doe",
age:50, eyeColor:"blue"};

• OUTPUT document.write(
person.firstName + " is " + person.age + " years
Creating a JavaScript Object. old.");
John is 50 years old. </script>

</body>
</html>
• Nested object:

– my_car.engine = new object();


– my_car.engine.config = “v6”;
– my_car.engine.hp = 200;

• Created new object that has properties of


my_car with properties of its own.
• JavaScript Properties
– Properties are the values associated with a JavaScript
object.
– A JavaScript object is a collection of unordered properties.
– Properties can usually be changed, added, and deleted,
but some are read only.
• Accessing JavaScript Properties
– The syntax for accessing the property of an object is:
– objectName.property // person.age
or
– objectName["property"] // person["age"]
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Object Properties</h2>

<p>There are two different ways to access an


object property:</p> JavaScript Object Properties
<p>You can use .property or ["property"].</p> There are two different ways to access an object
property:
<script> You can use .property or ["property"].
var person = { John is 50 years old.
firstname:"John",
lastname:"Doe",
age:50,
eyecolor:"blue"
};
document.write(
person["firstname"] + " is " + person.age + " years
old.");
</script>

</body>
</html>
<!DOCTYPE html>
• JavaScript for...in Loop <html>
– JavaScript has a loop <body>
statement , for ….in , <h2>JavaScript Object Properties</h2>
that is perfect for listing
the properties of an <script>
object. var person = {fname:"John", lname:"Doe",
age:25};
– The format of for-in is as for (var x in person) {
follows: document.write("Name:", x," ", "value :" ,
– for(identifier in object) person[x], "<br />");
}
Statement or </script>
compound statement
</body>
</html>

OUTPUT:
• JavaScript Object Properties
Name:fname value :John
Name:lname value :Doe
Name:age value :25
• Deleting Properties <!DOCTYPE html>
<html>
– The delete keyword <body>

deletes a property from <h2>JavaScript Object Properties</h2>


an object: <p>You can delete object properties.</p>
• OUTPUT <script>
JavaScript Object Properties var person = {
firstname:"John",
You can delete object lastname:"Doe",
age:50,
properties. eyecolor:"blue"
};
John is undefined years old. delete person.age;
document.write(person.firstname + " is " +
person.age + " years old.");
</script>
• If an attempt is made to
access a property of an </body>
</html>
object that does not exist,
the value undefined is used.
Array
• In JavaScript , arrays are objects .
• An array is a special variable, which can hold
more than one value at a time.
• An array can hold many values under a single
name, and you can access the values by referring
to an index number.
• Array elements can be primitive values or
references to other objects, including other array.
• JavaScript array have dynamic length.
Array object creation
• Array can be created in two distinct ways.
1. Using a array literal array is a easiest way to
create a JavaScript Array.
Eg. Var my_list_2 = {1, 2, “three”, “four”};
2. Create an object with the new operator and a
call to a constructor
var my_list = new Array (1, 2, “three”,
“four”);
Array
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Arrays</h2>
<!DOCTYPE html>
<html>
<script>
<body>
var cars = new Array("Saab", "Volvo", "BMW");
<h2>JavaScript Arrays</h2>
document.write(cars);
<script>
</script>
var cars = ["Saab", "Volvo", "BMW"];
document.write(cars);
</body>
</script>
</html>
</body>
</html>
OUTPUT
JavaScript Arrays
Saab,Volvo,BMW
• Output

JavaScript Arrays
Saab,Volvo,BMW
• Characteristics of Array object: <!DOCTYPE html>
– You access an array element by referring to the index <html>
number.
– Array indexes start with 0.
<body>
– [0] is the first element. [1] is the second element.
<h2>JavaScript Arrays</h2>

<p>JavaScript array elements are accessed using numeric


indexes (starting from 0).</p>

<script>
var cars = ["Saab", "Volvo", "BMW"];
document.write(cars[0]);
</script>

</body>
</html>

Output:
• JavaScript Arrays
• JavaScript array elements are accessed using
numeric indexes (starting from 0).
• Saab
Array Properties and Methods
<!DOCTYPE html>
<html>
<body>

• The real strength of <h2>JavaScript Arrays</h2>


JavaScript arrays are the <p>The length property returns the length of an array.</p>

built-in array properties and <script>


var fruits = ["Banana", "Orange", "Apple", "Mango"];
methods: document.write(fruits.length + "<br/>");

• The length Property var first = fruits[0];


document.write(first + "<br/>");
– The length property of var last = fruits[fruits.length-1];
an array returns the document.write(last);
</script>
length of an array (the
number of array </body>
</html>
elements). OUTPUT
– The length property is JavaScript Arrays
The length property returns the length of an array.
always one more than 4
Banana
the highest array index. Mango
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Array Methods</h2>


• Converting Arrays to Strings
– The JavaScript <h2>toString()</h2>
method toString() converts an array to
a string of (comma separated) array
values. <p>The toString() method returns an
array as a comma separated
string:</p>

• Output <script>
JavaScript Array Methods var fruits = ["Banana", "Orange",
"Apple", "Mango"];
toString()
document.write( fruits.toString());
The toString() method returns an array as
a comma separated string: </script>
Banana,Orange,Apple,Mango
</body>
</html>
• The join() method also joins all
array elements into a string.
• It behaves just like toString(), but
in addition you can specify the
separator. <!DOCTYPE html>
<html>
<body>
• OUTPUT
<h2>JavaScript Array Methods</h2>
JavaScript Array Methods
<h2>join()</h2>
join()
The join() method joins array <p>The join() method joins array elements into a string.</p>

elements into a string. <p>It this example we have used " * " as a separator between the
elements:</p>
It this example we have used " * " as
a separator between the <script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
elements: document.write(fruits.join(" * "));
</script>
Banana * Orange * Apple * Mango
</body>
</html>
• Popping and Pushing
– When you work with arrays, it is easy to remove elements and
add new elements.
– This is what popping and pushing is:
– Popping items out of an array, or pushing items into an array.
• Popping
– The pop() method removes the last element from an array:
– The pop() method returns the value that was "popped out":
• Pushing
– The push() method adds a new element to an array (at the end):
– The push() method returns the new array length:
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Array Methods</h2>

<h2>pop() and push</h2> • JavaScript Array Methods


• pop() and push()
<p>The pop() method removes the last element • The pop() method removes the last element
from an array.</p> from an array.
• Banana,Orange,Apple,Mango
Banana,Orange,Apple
<script> 4
var fruits = ["Banana", "Orange", "Apple", Banana,Orange,Apple,Kiwi
"Mango"];
document.write(fruits + "<br />");
fruits.pop();
document.write(fruits + "<br />");

document.write(fruits.push("Kiwi") + "<br />");


document.write(fruits);

</script>

</body>
</html>
• Shifting Elements
– Shifting is equivalent to popping, working on the first
element instead of the last.
– The shift() method removes the first array element and
"shifts" all other elements to a lower index.
• The unshift() method adds a new element to an array
(at the beginning), and "unshifts" older elements:
• The unshift() method returns the new array length.
• Deleting Elements
– Since JavaScript arrays are objects, elements can be
deleted by using the JavaScript operator delete
• Splicing an Array
– The splice() method can be used to add new items to an array
– The first parameter (2) defines the position where new elements should
be added (spliced in).
– The second parameter (0) defines how many elements should be removed.
– The rest of the parameters ("Lemon" , "Kiwi") define the new elements to
be added.
• Using splice() to Remove Elements
– With clever parameter setting, you can use splice() to remove elements
without leaving "holes" in the array:
– The first parameter (0) defines the position where new elements should
be added (spliced in).
– The second parameter (1) defines how many elements should be removed.
– The rest of the parameters are omitted. No new elements will be added.
• Sorting an Array
– The sort() method sorts an array alphabetically:
• Functions :
– A function definition consists of the function’s
header and a compound statement that describes
its actions.
– This compound statement is called body of the
function. A function header consists of the
reserved word function, the function’s name, and
a parenthesized list of parameters.
• Function syntax
function name(parameter1, parameter2,
parameter3)
{
code to be executed
}
• Function parameters are listed inside the parentheses
() in the function definition.
• Function arguments are the values received by the
function when it is invoked.
• Inside the function, the arguments (the parameters)
behave as local variables.
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Functions</h2>

• Local Variables <p>This example calls a function which performs a


calculation and returns the result:</p>

– Variables declared <script>


within a JavaScript var x = myFunction(4, 3);
document.write(x);
function,
become LOCAL to the function myFunction(a, b) {
return a * b;
function. }
– Local variables can only </script>

be accessed from within </body>


the function. </html>

OUTPUT
• JavaScript Functions
• This example calls a function which performs a
calculation and returns the result:
• 12
Constructors
• JavaScript constructors are special methods that create and
initialize the properties for newly created objects.
• Every new expression must include a call to a constructor,
whose name is the same as the object being created.
• A constructor must be able to reference the object on
which it is to operate.
• JavaScript has a predefined reference variable for this
purpose, named this.
• When the constructor is called, this is a reference to the
newly created object.
• The this variable is used to construct and initialize the
properties of the object.
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Object Constructors</h2>

<p id="demo"></p>
• JavaScript Object Constructors
<script> • My father is 50. My mother is 48.

// Constructor function for Person objects


function Person(first, last, age, eye) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
}

// Create two Person objects


var myFather = new Person("John", "Doe", 50, "blue");
var myMother = new Person("Sally", "Rally", 48, "green");

// Display age
document.getElementById("demo").innerHTML =
"My father is " + myFather.age + ". My mother is " + myMother.age
+ ".";

</script>

</body>
</html>
Pattern matching using regular
expressions
• There are two approaches to pattern matching in
javaScript:
– Based on the RegExp object
– Based on methods of the String object.
• In JavaScript, regular expressions are often used with
the two string methods: search() and replace().
• The search() method uses an expression to search for a
match, and returns the position of the match. If there
is no match, search returns -1.
• The replace() method returns a modified string where
the pattern is replaced.
!DOCTYPE html> • JavaScript String Methods
<html> • Search a string for "W3Schools", and display
the position of the match:
<body> • 6

<h2>JavaScript String Methods</h2>

<p>Search a string for "W3Schools", and display


the position of the match:</p>

<script>
var str = "Visit W3Schools!";
var n = str.search("W3Schools");
document.write(n);
</script>

</body>
</html>
• Metacharacters can themselves be matched by being immediately
preceded by a backslash. Followings are the metacharacters:
\|( )[ ] { } ^$*+?.
• A period matches any character except newline.
Eg. /snow./
Matches with snowy snowe snowd .
• Matching classes of character
[abc], [a-h]
• Circumflex character (^) is the first character in a class, it inverts the
specified set.
e.g. [^aeiou]
Character class matches any character except the letter a,e,i,o,u.
• Predefine character classes
• \d [0-9] A digit
• \D [^0-9] not a digit
• \w [A-Z a-z_0-9] A word character
• \W [^A-Z a-z 0-9] Not a word character
• \s [ \r\t\n\f] A whitespace character
• \S [^ \r\t\n\f] Not a whitespace character
Change the color of all <p> elements
to "red".
This is a Heading
This is a paragraph.
This is another paragraph.
Change the color of all <p> elements to "red".

<!DOCTYPE html>
<html>
<head>
<style>
p{
color: red;
}
</style>
</head>
<body>

<h1>This is a Heading</h1>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>

</body>
</html>
Change the color of the element with
id="para1", to "red".
Change the color of the element with
id="para1", to "red".
<!DOCTYPE html>
<html>
<head>
<style>
#para1 {
color: red;
}
</style>
</head>
<body>

<h1>This is a Heading</h1>
<p id="para1">This is a paragraph.</p>
<p>This is another paragraph.</p>

</body>
</html>
Change the color of all elements with
the class "colortext", to "red".
Change the color of all elements with
the class "colortext", to "red".
<!DOCTYPE html>
<html>
<head>
<style>
.colortext {
color: red;
}
</style>
</head>
<body>

<h1>This is a Heading</h1>
<p>This is a paragraph.</p>
<p class="colortext">This is another paragraph.</p>
<p class="colortext">This is also a paragraph.</p>

</body>
</html>
Change the color of all <p> and <h1>
elements, to "red". Group the
selectors to minimize code.
<!DOCTYPE html>
<html>
<head>
<style>
p,h1,h2 {color:red}
</style>
</head>
<body>

<h1>This is a heading</h1>
<h2>This is a smaller heading</h2>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>

</body>
</html>
Add an external style sheet with the
URL: "mystyle.css".
Add an external style sheet with the
URL: "mystyle.css".
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
</head>
<body>

<h1>This is a Heading</h1>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>

</body>
</html>
Set "background-color: linen" for the
page, using an internal style sheet.
<!DOCTYPE html>
<html>
<head>
<style>
body {
background-color: linen;
}
</style>
</head>
<body>

<h1>This is a Heading</h1>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>

</body>
</html>
Set "background-color: linen" for the
page, using an inline style.
<!DOCTYPE html>
<html>
<head>
</head>
<body style="background-color: linen">

<h1>This is a Heading</h1>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>

</body>
</html>
UNIT - 5

Introduction to PHP
• Origin and uses of PHP
– Developed by Rasmus Lerdorf, a member of
Apache Group
– Initially called as Personal Home Page
– later changed to Hypertext preprocessor
– As a server side scripting language, PHP is
naturally used for form handling and database
access.
• Overview of PHP
– PHP is server-side, XHTML embedded scripting language.
– When browser request an XHTML document that includes
PHP script, the Web server that provides the document call
the PHP processor.
– File name extension for PHP script documents are .php,
.php3, or .phtml
– The PHP processor has two modes of operation, copy
mode and interpret mode.
– It takes a PHP document file as input and produces an
XHTML document file.
– When the PHP processor finds XHTML code in the input
file, it simply copies it to the output file.
• When it encounters PHP script in the input
file, it interprets it and sends any output of
the script to the output file.
• This implies that the output from a PHP script
must be XHTML or embedded client – side
script.
• This new file is sent to the requesting browser.
General syntactic characteristics
• PHP scripts are either embedded in XHTML document or
are in files that are referenced by XHTML documents.
• PHP code is embedded in XHTML document by enclosing it
between the <?PHP ?> tags.
• If PHP script is stored in different file , it can be brought into
a document with the include construct, which takes the
filename as its parameter.
• The include statement takes all the text/code/markup that
exists in the specified file and copies it into the file that
uses the include statement.

• Eg. Include(“table2.inc”);
• This constructor causes the contents of the file
table2.inc to be copied into the document where the
call appears.
• The PHP interpreter changes from interpreter to copy
mode when an include is encountered.
• All variable names in PHP begin with dollar signs ($).
• PHP variable names are case sensitive.
• PHP allows comment in three different ways
– Single line comment :- # or //
– Multiple line comment :- /* */
• PHP statements terminated with semicolons.
• Braces are used to form compound
statements for control structures.
• PHP Reserve words.
– And else global require virtual break elseif if
return xor case…………………………
• Primitives, operation and expressions
– PHP has four scalar types:- Boolean, integer,
double and string.
– Two compound types :- array and objects
– Two special types :- resources and NULL
• Variables :-
– PHP is dynamically typed, it has no type declaration.
– There is no need to declare the type of a variable.
– The type of the variable is set every time it is assigned
a value.
– An unassigned variable, called an unbound variable,
has the value NULL.
– If the context specifies a number, NULL is coerced to 0,
if the context specifies a string, NULL is coerced to the
empty string.
• Isset() function is used to check whether
variable is NULL or non- null.
• E.g. Isset($fruit) returns TRUE if $fruit
currently has a non-NULL value, FALSE
otherwise .
• unset :- set the variable to unassigned state.
• Error_reporting:- function used to informed
when unbound variable is referenced.
• Integer type :- PHP has a single integer type.
– This type corresponds to the long type of C.

• Double type :- corresponds to the double type


of C.
– Double literals can include a decimal point, an
exponent, or both.
• the exponent has the usual form of an E or
an e possibly signed integer literal.
• String type :- character in PHP are single bytes.
– There is no character type.
– A single character data is represented as a string of length
1.
– String literals are defined with either single (‘) or double
quotes (“) delimiters.
– In single-quoted string literals, escape sequences, such as
\n, are not recognized as anything special, and the values
of embedded variables are not substituted. This is called
interpolation.
– In double-quoted string literals, escape sequence are
recognized, and embedded variables are replaced by their
current values.
• Eg :- ‘The sum is : $sum.’
• Is typed as it is
• “ The sum is : $sum” where sum = 10.2
• The sum is : 10.2
• Boolean type :- only two possible values TRUE
or FALSE.
• Arithmetic operators and expressions: -usual
collection of arithmetic operators.
• String operations :-
– The only string operator is the catenation operator, specified with a
period (.).
– String variables can be treated like array for access to individual
characters.
Commonly used string function
– strlen() :- returns the length of a string.
– strcmp():- compares two strings.
– strpos() :- finds the position of the first occurrence of a string inside
another string.
– substr() :- returns a part of a string.
– chop() :- removes whitespaces or other predefined characters from
the right end of a string.
– trim() :- Removes whitespace or other characters from both sides of a
string
– ltrim() :- Removes whitespace or other characters from the left side of
a string
– strtolower() :- Converts a string to lowercase letters
– strtoupper() :- Converts a string to uppercase letters
• Scalar type conversions
• Scalar type declaration has two options −
– coercive - coercive is default mode and need not
to be specified.
• strict - strict mode has to explicitly hinted.
• Explicit type conversions : - can be specified in three
different ways.
1. Using syntax of C, an expression can be cast to a
different type.
– E.g. (int)$sum
– If the value of $sum = 4.777 the following produces 4.
2. Another way is to use one of the functions interval,
doubleval, or strval.
– Eg. Interval($sum)
3. Use of settype function, which takes two parameters: a
variable and a string that specifies a type name.
– E.g. settype($sum, interger)
• Assignment operators
– PHP has same set of assignment operator as its
predecessor languages C and perl, including the
compound assignment operators such as += and
/=.
• Output :-
– In PHP there are two basic ways to get
output: echo and print.
– echo and print are more or less the same. They are both
used to output data to the screen.
– The differences are small: echo has no return value
while print has a return value of 1 so it can be used in
expressions. echo can take multiple parameters (although
such usage is rare) while print can take one
argument. echo is marginally faster than print.
• The PHP echo Statement • Program 2
– The echo statement can be used with or • <!DOCTYPE html>
without parentheses: echo or echo(). <html>
<body>
Program 1
<!DOCTYPE html> <?php
<html> $txt1 = "Learn PHP";
<body>
$txt2 = "W3Schools.com";
<?php $x = 5;
echo "<h2>PHP is Fun!</h2>"; $y = 4;
echo "Hello world!<br>";
echo "I'm about to learn PHP!<br>"; echo "<h2>" . $txt1 . "</h2>";
echo "This ", "string ", "was ", "made
", "with multiple parameters."; echo "Study PHP at " . $txt2 . "<br>";
?> echo $x + $y;
?>
</body>
</html> </body>
Output: </html>
• PHP is Fun!
• Hello world! • Output
I'm about to learn PHP! – Learn PHP
This string was made with multiple – Study PHP at W3Schools.com
parameters. 9
• The PHP print Statement
– The print statement can be used with
or without
parentheses: print or print().
• <!DOCTYPE html>
– Program 1 <html>
<body>
<!DOCTYPE html>
<html> <?php
<body> $txt1 = "Learn PHP";
$txt2 = "W3Schools.com";
$x = 5;
<?php $y = 4;
print "<h2>PHP is Fun!</h2>";
print "<h2>" . $txt1 . "</h2>";
print "Hello world!<br>"; print "Study PHP at " . $txt2 . "<br>";
print "I'm about to learn PHP!"; print $x + $y;
?> ?>
</body>
</body> </html>
</html>
Output: • Output
– Learn PHP
– PHP is Fun!
– Study PHP at W3Schools.com
– Hello world! 9
I'm about to learn PHP!
Control statements
• Relational operators :-
– The PHP comparison operators are used to
compare two values (number or string)
Operator Name Example Result

== Equal $x == $y Returns true if $x is equal to $y

=== Identical $x === $y Returns true if $x is equal to $y, and they are of the same type

!= Not equal $x != $y Returns true if $x is not equal to $y

<> Not equal $x <> $y Returns true if $x is not equal to $y

!== Not identical $x !== $y Returns true if $x is not equal to $y, or they are not of the same type

> Greater than $x > $y Returns true if $x is greater than $y

< Less than $x < $y Returns true if $x is less than $y

>= Greater than or $x >= $y Returns true if $x is greater than or equal to $y


equal to

<= Less than or equal $x <= $y Returns true if $x is less than or equal to $y
to
• Boolean operators:- The PHP logical operators
are used to combine conditional statements.
Operator Name Example Result
and And $x and $y True if both $x and $y are true
or Or $x or $y True if either $x or $y is true
xor Xor $x xor $y True if either $x or $y is true,
but not both
&& And $x && $y True if both $x and $y are true
|| Or $x || $y True if either $x or $y is true
! Not !$x True if $x is not true
PHP Conditional Statements
• PHP - The if...else Statement :-
• PHP - The if Statement :- The if statement The if....else statement executes some code if
executes some code if one condition is true. a condition is true and another code if that
• Syntax condition is false.
– if (condition) { • Syntax
code to be executed if condition is true; – if (condition) {
} code to be executed if condition is true;
• Program } else {
– <!DOCTYPE html> code to be executed if condition is false;
<html> }
<body> • Program
– <!DOCTYPE html>
<?php <html>
$t = date("H"); <body>
if ($t < "20") { <?php
echo "Have a good day!"; $t = date("H");
}
?> if ($t < "20") {
echo "Have a good day!";
</body> } else {
</html> echo "Have a good night!";
• Output }
– Have a good day! ?>
</body>
</html>
• Output
– Have a good day!
• The PHP switch Statement :- Use <!DOCTYPE html>
the switch statement to select one of many <html>
blocks of code to be executed. <body>

• Syntax <?php
$favcolor = "red";
– switch (n) {
case label1:
code to be executed if n=label1; switch ($favcolor) {
break; case "red":
case label2: echo "Your favorite color is red!";
code to be executed if n=label2; break;
break; case "blue":
case label3: echo "Your favorite color is blue!";
code to be executed if n=label3;
break; break;
... case "green":
default: echo "Your favorite color is green!";
code to be executed if n is different from break;
all labels; default:
} echo "Your favorite color is neither red,
blue, nor green!";
}
?>
</body>
</html>
Output :-
Your favorite color is red!
Loop statements
• The PHP while Loop :-The while loop <!DOCTYPE html>
executes a block of code as long as the <html>
specified condition is true. <body>

• Syntax <?php
$x = 1;
– while (condition is true) {
code to be executed;
} while($x <= 5) {
echo "The number is: $x <br>";
$x++;
}
?>
</body>
</html>

Output :-
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5
• The PHP do...while Loop • <!DOCTYPE html>
– The do...while loop will always execute the <html>
block of code once, it will then check the <body>
condition, and repeat the loop while the
specified condition is true. <?php
• Syntax $x = 1;
– do {
code to be executed; do {
} while (condition is true); echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>
</body>
</html>
• OUTPUT
– The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5
• <!DOCTYPE html>
<html>
<body>
<?php
• The PHP for Loop for ($x = 0; $x <= 10; $x++) {
– The for loop is used when you echo "The number is: $x <br>";
know in advance how many times }
the script should run. ?>
• Syntax </body>
– for (init counter; test counter; </html>
increment counter) { • Output
code to be executed; – The number is: 0
} The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5
The number is: 6
The number is: 7
The number is: 8
The number is: 9
The number is: 10
• The PHP foreach Loop • <!DOCTYPE html>
– The foreach loop works only on arrays, <html>
and is used to loop through each <body>
key/value pair in an array.
• Syntax <?php
– foreach ($array as $value) { $colors
code to be executed; = array("red", "green", "blue", "yello
} w");
foreach ($colors as $value) {
echo "$value <br>";
}
?>
</body>
</html>
• OUTPUT
– red
green
blue
yellow
• Create an Array in PHP
– In PHP, the array() function is used to create an array:
– array();
• In PHP, there are three types of arrays:
– Indexed arrays - Arrays with a numeric index
– Associative arrays - Arrays with named keys
– Multidimensional arrays - Arrays containing one or
more arrays

• <!DOCTYPE html>
<html>
<body>
• PHP Indexed Arrays <?php
– There are two ways to create $cars
indexed arrays: = array("Volvo", "BMW", "To
– The index can be assigned yota");
automatically (index always echo "I like " . $cars[0] . ", " .
starts at 0), like this:
• $cars = array("Volvo", "BMW",
$cars[1] . " and " . $cars[2]
"Toyota"); . ".";
• or the index can be assigned ?>
manually:
</body>
$cars[0] = "Volvo"; </html>
$cars[1] = "BMW";
$cars[2] = "Toyota";
• OUTPUT
– I like Volvo, BMW and Toyota.
• PHP Associative Arrays • <!DOCTYPE html>
– Associative arrays are arrays that <html>
use named keys that you assign to <body>
them.
• There are two ways to create an <?php
associative array: $age
– $age = array("Peter"=>"35", = array("Peter"=>"35", "Ben"=>"3
"Ben"=>"37", "Joe"=>"43"); 7", "Joe"=>"43");
• or: echo "Peter is " . $age['Peter'] . "
– $age['Peter'] = "35"; years old.";
$age['Ben'] = "37"; ?>
$age['Joe'] = "43";
</body>
</html>

• OUTPUT
– Peter is 35 years old.
• Accessing Array Elements:-
– Individual array elements can be accessed by subscripting.
– The value in the subscript, which is enclosed in brackets, is
the key of the value being referenced.
– The same brackets are used regardless of whether the key
is a number or a string.
– E.g. $age[‘Mary’] = 29
– Where $age is an array, Mary is a key and 29 is a value set
to key.
– Multiple elements of an array can be assigned to scalar
variables in one statements using list construct.
– Eg. $trees = array(“oak”, “pine”, ”binary”);
– list($hardwood, $softwood,$data_structure) = $trees;
– $hardwood, $softwood, and $data_structure are set to
“oak”, “pine”, ”binary” respectively.
• Functions for dealing with array:-
• unset – used to delete whole array or individual elements
of an array.
– E.g. $list = array(2,4,6,8);
– unset($list[2]);
• array_keys :- takes an array as its parameter and returns an
array of the keys of the given array.
• Array_values :- takes an array as its parameter and returns
an array of the values of the given array.
– E.g. $highs = array(“Mon” => 74, “Tue” => 70, “Wed” => 67,
“Thu” => 65, “Fri” => 62 );
– $days = array_keys($highs);
– $temps = array_values($highs);
• The array_key_exists() function • <!DOCTYPE html>
checks an array for a specified <html>
key, and returns true if the key <body>
exists and false if the key does
not exist. <?php
• if you skip the key when you $a=array("Volvo"=>"XC90","BMW
specify an array, an integer key is "=>"X5");
generated, starting at 0 and if (array_key_exists("Volvo",$a))
increases by 1 for each value. {
• Is_array :- it takes variable as its echo "Key exists!";
parameter and returns TRUE if }
the variable is an array, else else
returns FALSE. {
echo "Key does not exist!";
• In_array :- searches an array for a }
specific value ?>
• Sizeof :- the number of elements
in an array can be determine with </body>
the sizeof function. </html>
• OUTPUT
– Key exists!
• Explode :- function explodes • The implode function does
a string into substrings and the inverse of explode.
returns them in an array. • Given a separator character
• The deilmiters of the and an array, it
substring are defined by the concatenates the elements
first parameter to explode, of the array together, using
which is a string. the given separator string
• The second parameter is between the elements, and
the string to be converted. returns the result as a
string.
• E.g. $str = “Aprill in Paris,
Texas is nice”; • $words= array(“Aprill”, “in “,
“Paris, “ , “Texas “, “is “,
• $words = explode(“ “,$str); “nice”);
• Now $words contains • $str = imlode (“ “,$words);
(“Aprill”, “in “, “Paris, “ ,
“Texas “, “is “, “nice”). • Now $str has “Aprill in
Paris, Texas is nice”;
Logical internal structure of array in
PHP
• Internally, the elements of an array are stored in a
linked list of cells, where each cell includes both the
key and the value of the element.
• The cells themselves are stored in memory through a
key-hashing function so that they are randomly
distributed in a reserved block of storage.
• Accesses to elements through string keys are
implemented through the hashing function.
• However, the elements all have links that connect them
in the order in which they were created, allowing them
to be accessed in that order if the keys are strings and
in the order of their keys if the keys are numbers.
Sorting Array
• The elements in an array can be sorted in alphabetical or numerical
order, descending or ascending.
• PHP array sort functions:
– sort() - sort arrays in ascending order
– rsort() - sort arrays in descending order
– asort() - sort associative arrays in ascending order, according to the
value
– ksort() - sort associative arrays in ascending order, according to the key
– arsort() - sort associative arrays in descending order, according to the
value
– krsort() - sort associative arrays in descending order, according to the
key

• Sort Array in Ascending Order - sort() • <!DOCTYPE html>
• The following example sorts the <html>
elements of the $cars array in <body>
ascending alphabetical order:
<!DOCTYPE html> <?php
<html> $numbers = array(4, 6, 2, 22, 11);
<body> sort($numbers);
<?php $arrlength = count($numbers);
$cars
= array("Volvo", "BMW", "Toyota"); for($x = 0; $x < $arrlength; $x++) {
sort($cars); echo $numbers[$x];
echo "<br>";
$clength = count($cars); }
for($x = 0; $x < $clength; $x++) { ?>
echo $cars[$x];
echo "<br>";
} </body>
?> </html>
</body>
</html> • Output
2
4
• Output 6
BMW 11
Toyota 22
Volvo
• PHP User Defined Functions
– Besides the built-in PHP functions, we can create
our own functions.
– A function is a block of statements that can be
used repeatedly in a program.
– A function will not execute immediately when a
page loads.
– A function will be executed by a call to the
function.
• Create a User Defined Function in PHP
– A user-defined function declaration starts with the
word function:
– Syntax
• function functionName() {
code to be executed;
}
• PHP Function Arguments • <!DOCTYPE html>
– Information can be passed to functions <html>
through arguments. An argument is just <body>
like a variable.
– Arguments are specified after the <?php
function name, inside the parentheses. function familyName($fname) {
You can add as many arguments as you
want, just separate them with a comma. echo "$fname Refsnes.<br>";
– <!DOCTYPE html> }
<html>
<body> familyName("Jani");
familyName("Hege");
<?php familyName("Stale");
function writeMsg() {
echo "Hello world!"; familyName("Kai Jim");
} familyName("Borge");
?>
writeMsg();
?> </body>
</body> </html>
</html> • OUTPUT
– OUTPUT • Jani Refsnes.
Hello world! Hege Refsnes.
Stale Refsnes.
Kai Jim Refsnes.
Borge Refsnes
• PHP Default Argument Value • PHP Functions - Returning values
– The following example shows how to use a
default parameter. If we call the function • To let a function return a value, use
setHeight() without arguments it takes the the return statement:
default value as argument: – <!DOCTYPE html>
– <!DOCTYPE html> <html>
<html> <body>
<body>
<?php
<?php function sum($x, $y) {
function setHeight($minheight = 50) { $z = $x + $y;
echo "The height is : $minheight <br>"; return $z;
} }

setHeight(350); echo "5 + 10 = " . sum(5,10) . "<br>";


setHeight(); echo "7 + 13 = " . sum(7,13) . "<br>";
setHeight(135); echo "2 + 4 = " . sum(2,4);
setHeight(80); ?>
?>
</body>
</body> </html>
</html>
• OUTPUT
• OUTPUT – 5 + 10 = 15
• The height is : 350 7 + 13 = 20
The height is : 50 2+4=6
The height is : 135
The height is : 80
• Pattern Matching
– PHP includes two different kinds of string pattern matching
using regular expressions: one that is based on POSIX regular
expressions and one that is based on Perl regular expressions.
– The POSIX regular expressions are compiled into PHP.
– The Perl-Compatible Regular Expression (PCRE) library must be
compiled before Perl regular expressions.
– The preg_match function takes two parameters, the first of
which is the Perl-style regular expression as a string.
– The second parameter is the string to be searched.
• If (preg_match(“/^PHP/”, $str))
• Print “\$str begins with PHP <br />”;
• Else
• Print “\$str does not begin with PHP <br />”;
• The preg_split function operates on string but
returns an array and uses patterns.
• It takes two parameters, the first of which is a
Perl-style pattern as a string, the second
parameter is the string to be split.
– $fruit_string =n”apple : orange : banana”;
– $fruits = preg_split(“/ : /”, $fruit_string);
– The array $fruit now has (“apple”, “orange”,
“banana”).
• Form Handling
– The PHP superglobals $_GET and
$_POST are used to collect form-data.
– When the user fills out the form above
and clicks the submit button, the form
data is sent for processing to a PHP file
named "welcome.php". The form data
is sent with the HTTP POST method.

– <!DOCTYPE HTML>
<html>
<body>
<form action="welcome.php" method=
"post">
Name: <input type="text" name="name
"><br>
E-
mail: <input type="text" name="email"
><br>
<input type="submit">
</form>
</body>
</html>
• GET vs. POST
• Both GET and POST create an array (e.g. array( key => value, key2 =>
value2, key3 => value3, ...)). This array holds key/value pairs, where
keys are the names of the form controls and values are the input
data from the user.
• Both GET and POST are treated as $_GET and $_POST. These are
superglobals, which means that they are always accessible,
regardless of scope - and you can access them from any function,
class or file without having to do anything special.
• $_GET is an array of variables passed to the current script via the
URL parameters.
• $_POST is an array of variables passed to the current script via the
HTTP POST method.
• When to use GET? • When to use POST?
– Information sent from a form – Information sent from a form
with the GET method is visible with the POST method
to everyone (all variable names is invisible to others (all
and values are displayed in the names/values are embedded
URL). GET also has limits on the within the body of the HTTP
amount of information to send. request) and has no limits on
The limitation is about 2000 the amount of information to
characters. However, because send.
the variables are displayed in – Moreover POST supports
the URL, it is possible to advanced functionality such as
bookmark the page. This can be support for multi-part binary
useful in some cases. input while uploading files to
– GET may be used for sending server.
non-sensitive data. – However, because the variables
are not displayed in the URL, it
is not possible to bookmark the
page.
• Files
• PHP file is a server-side technology, it is able
to create, read, and write files on the server
system.
• PHP can deal with files residing on any server
system on the Internet, using both HTTP and
FTP protocols.
• Opening and closing Files:- • <!DOCTYPE html>
– PHP Open File - fopen() <html>
– A better method to open files is with <body>
the fopen() function.
– The first parameter of fopen() contains <?php
the name of the file to be opened and $myfile =
the second parameter specifies in which fopen("webdictionary.txt", "r") or die
mode the file should be opened.
("Unable to open file!");
echo fread($myfile,filesize("webdicti
onary.txt"));
fclose($myfile);
?>
</body>
</html>
• OUTPUT
• AJAX = Asynchronous JavaScript and
XML CSS = Cascading Style Sheets
HTML = Hyper Text Markup Language
PHP = PHP Hypertext Preprocessor
SQL = Structured Query Language
SVG = Scalable Vector Graphics XML =
EXtensible Markup Language
Modes Description
r Open a file for read only. File pointer starts at the beginning of the file
w Open a file for write only. Erases the contents of the file or creates a
new file if it doesn't exist. File pointer starts at the beginning of the file
a Open a file for write only. The existing data in file is preserved. File
pointer starts at the end of the file. Creates a new file if the file doesn't
exist
x Creates a new file for write only. Returns FALSE and an error if file
already exists
r+ Open a file for read/write. File pointer starts at the beginning of the file
w+ Open a file for read/write. Erases the contents of the file or creates a
new file if it doesn't exist. File pointer starts at the beginning of the file
a+ Open a file for read/write. The existing data in file is preserved. File
pointer starts at the end of the file. Creates a new file if the file doesn't
exist
x+ Creates a new file for read/write. Returns FALSE and an error if file
already exists
• PHP Close File - fclose()
– The fclose() function is used to close an open file.
– The fclose() requires the name of the file (or a
variable that holds the filename) we want to
close:
<?php
$myfile = fopen("webdictionary.txt", "r");
// some code to be executed....
fclose($myfile);
?>
• Reading from file:-
– The fread() function reads from an open file.
– The first parameter of fread() contains the name
of the file to read from and the second parameter
specifies the maximum number of bytes to read.
– The following PHP code reads the
"webdictionary.txt" file to the end:
• fread($myfile,filesize("webdictionary.txt"));
• File :- alternative to fread is file which takes a filename as its
parameter and return an array of all of the lines of the file.
• Advantage is no need of file open and close operations.
– e.g. $file_lines = file(“testdata.dat”);

• File_get_contents:- reads entire content of the file. It doesn’t


required fopen function.
• E.g. #file_string = file_get_contents(“testdata.dat”);
• Fgets:- a single line of a file can be read with fgets, which takes two
parameters: the file variable and a imit on the length of the line to
be read.
• $line = fgets($file_var, 100);
• Writing to a File :-
– Takes to parameters : a file variable and the string
to be written to the file.
– $bytes_written = fwrite($file_var, $out_data);

– File_put_contents(“savedata.dat”,$str);
– It writes the value of its second parameter, a string
, to the file specified in its first parameter.
• Locking Files:-
– It prevents file from more than one script to
access at the same time.
– Flock function takes two parameters : the file
variable of the file and an integer that specifies
the particular operations.
Chapter 1

Fundamentals
World Wide Web
A Brief Introduction to the Internet

Internet History
Internet Protocol
Internet History
• Origins

– ARPAnet (DoD, funded by ARPA)


• late 1960s and early 1970s

– BITNET ( Because it’s Time network)


– CSNET (Computer Science network)
• late 1970s & early 1980s

–NSFnet (funded by National Science Foundation)


• 1986
• By 1990, it had replaced ARPAnet for non-military uses
• Soon became the network for all (by the early 1990s)

• NSFnet eventually became known as the Internet


Internet
• Inter-Network or Inter connected network.

• Internet is a network of networks.

• A huge collection of computers connected in a network and


communicate with each other through TCP/IP protocol

• TCP/IP provides the low level interface. TCP/IP hides the differences
among devices connected to the Internet. Allows the program on
one computer to talk to the one on another computer.

• But a higher level protocol runs on top of TCP/IP (Telnet, FTP, Usenet,
mailto,http )
Internet Protocol Address
• Every machine connected to the network (internet) is
uniquely identified by a numeric address called as IP Address

• IP Address :
• 32-bit number written as four 8 bit numbers . Eg 191.57.126.0
• Each number can be from 0 to 255
• The combination of the four IP address parts provides 4.2 billion
possible addresses (256 x 256 x 256 x 256).
• New standard, IPv6, has 128 bits (1998)

• Organizations are assigned blocks of IPs for their computers.


191.57.126.0 to 191.57.126.255
Domain Names
• It is difficult for people to remember IP Address. Hence the machines on
internet have been given textual names called as Domain names.

• Most web browsers do not use the IP address to locate Web sites and
individual pages. They use domain name addressing.

• A domain name is a unique name associated with a specific IP address by a


program that runs on an Internet host computer.

• Domain names : www.google.com


– can be used as http://209.87.113.93
– Eg vtu.ac.in

– Domain names can include any number of parts separated by periods, however most
domain names currently in use have only three or four parts.

– Domain names follow hierarchical model that you can follow from top to bottom if
you read the name from the right to the left.
Domain Names
– Names begin with name of the Host machine followed by progressively larger collection of machines
called domains.
– The 1st domain name is the domain name of which the host is a part

Eg. www.movies.comedy.marxbros.com

Host Name movies local domain contains comedy domain Largest Domain

– The last domain name identifies the type of organization in which the host resides. It is called the Top
Level Domain.
edu - extension for educational institutions
com specifies a company
gov is used for the U.S. government
org is used for many other kinds of organizations.
in : India us : United States of America
ca : Canada uk : United Kingdom

– the domain name gsb.uchicago.edu


is the computer connected to the Internet at the Graduate School of Business (gsb), which is an
academic unit of the University of Chicago (uchicago), which is an educational institution (edu).

• Fully qualified domain name - the host name + all the domain names
Domain Name Conversion

Name Servers implement


Domain Name system
Domain Name Server(DNS)
• Domain Names are registered in Domain Name System

• The fully qualified domain name is unique and needs to be converted to the IP address

• This program, which coordinates the IP addresses and domain names conversion for all
computers attached to it, is called DNS (Domain Name System ) software.

• The host computer that runs this software is called a domain name server.

• These conversions are done by the Name Servers (which implements Domain Name
System )

• All Requests from browsers are routed to the nearest Name Server

• The Name Servers converts the domain name to IP address. If it cannot do so, it sends
the request to the nearest name server.
World Wide Web

Tim Berners & Robert Calliliau


The World-Wide Web
• Origin
– Tim Berners-Lee at CERN proposed the Web in 1989
– Purpose: to allow scientists to have access to many databases of scientific
work through their own computers

• Web is designed to allow the users anywhere on the internet to search for and
retrieve documents from databases on any number of systems. It is a system of
interlinked hypertext documents accessed by internet

• Hypertext : Text with hyperlinks


• Hypermedia : more than just text – images, sound, etc.
• Unit of information on the web is called as Pages, Documents or Resources
Uniform/Universal Resource Locator
(URL)
• The IP address and the domain name each
identify a particular computer on the Internet.

• However, they do not indicate where a Web


page’s HTML document resides on that computer.

• To identify a Web pages exact location, Web


browsers rely on Uniform Resource Locator (URL).

• URL is used to identify documents(resources ) on


the internet
Uniform/Universal Resource Locator (URL)

• URL has 4 parts – Protocol, Domain Name, Path name, File name

Port No Actual HTML Page


protocol
• http://www.yahoo.com:80/finance/infosys.html

Domain name
Path to Document
Uniform/Universal Resource Locator (URL)

• General form:
scheme://object-address

• Scheme is often communications protocol eg. http, telnet , file or ftp


• Object-address :
 For the http protocol
http: //fully-qualified-domain-name : port no /path to document
Port No : 80 is default
 For the file protocol
file ://document-path

• URLs can never have embedded spaces, or any of the special characters,
including semicolons, colons, and ampersands (&)
Multipurpose Internet Mail Extensions (MIME)
• Used to specify to the browser the form of a file/document is returned by the
server (attached by the server at the beginning of the document)

• Example :
<a href="http://www.w3schools.com" type="text/html"> W3Schools </a>

• MIME specifications has the following form : type/subtype


Common MIME types subtypes
text plain , html
image gif , jpg, tif
video mp4, quicktime,x-flv(flash)
audio mp4,mpeg
Example:
content-type : text/plain, text/html,
content-type : image/gif, image/jpg
Client and Server

• Clients and Servers are programs that communicate with


each other over the Internet .

• A Client will send a message to a Server requesting the service


provided by that server

• A Server runs continuously, waiting to be contacted by a Client


– Each Server provides certain services
– Services include providing web pages
Web Browsers
Web Browsers
• Browsers are programs running on client machine.
– A browser is a client on the Web. They are called browsers because they
allow the user to browse the resources available on servers.
– Browsers always initiate the communication with a server by sending URL
• URL can specify one of the two things :
– Address of the data file stored on the server
http://www.microsoft.com/……./finance.html
– A program stored on the server that has to be executed with the
output returned to the browser
http://……/abc.php

– Server waits for a request from the client before doing anything.
– Browser-server connection is now maintained through more than one
request-response cycle
• Most commonly used browsers :
– Microsoft Internet Explorer (IE), Firefox, Netscape Navigator, Opera and
Apple’s Safari.
Web Server
Web Server Operations
Web Server Characteristics
Web Server Operation
• Web Servers are programs that provide documents to requesting
browsers. They are slave programs that act only when requests are made.
• All communications between browsers and servers use HTTP (Hypertext
Transfer Protocol )
Web server operations :
1. Web server informs OS that it is ready to accept incoming network
connections through a specific port on the machine
2. In running state, Web servers run as background processes in the OS
3. Browser opens a network connection to a web server by sending the
URL, sends the request, receives the response, closes the connection
4. Primary task of a Web server is to monitor a communications port on its
host machine, accept HTTP commands through that port, and perform
the operations specified by the commands.
• HTTP commands include URL which is translated into file name or a
program name.
– If file, it is returned to the browser
– If it is a program name, the program is executed and output returned.
General Server Characteristics

The File structure of the Web Server has 2 separate directories

1. Document Root
– This directory contains all the Web documents which are
accessed by the client.
– Clients do not access the document root directly in URLs
– Server maps the requested URLs to the Document root
whose location is not known to the client.

2. Server Root
– This directory stores the server and its support software
General Server Characterstics
(Document Root Access)
Website : www.petunia.com
• Document Root : topdocs
Stored in the : /admin/web directory
Address of document root : /admin/web/topdocs

• URL : http://www.petunia.com/petunias.html
Server will search : /admin/web/topdocs/petunias.html

• http://www.petunia.com/bulbs/tulips.html
• Server will search /admin/web/topdocs/bulbs/tulips.html
General Server Characteristics (Contd…)
• Virtual Document Trees –
• Servers allow files to be stored in secondary areas outside the directory of document
root.
• The secondary area from which document can be served are called as Virtual
Document trees

• Virtual hosts –
• Virtual hosting is a method of hosting multiple domain names on a single server.
• A server could be receiving requests for two domains,
www.example.com and
www.example.net
both of which resolve to the same IP address.

• Proxy servers –
• Some servers serve the document which are in document root of other machines on
the web. These servers called Proxy Servers.
• A proxy server can act as an intermediary between the user's computer and the
Internet to prevent from attack and unexpected access.
• To hide the IP address of the client computer so that it can surf anonymous, this is
mostly for security reasons.
Proxy Server
Main Web Servers

Apache
Microsoft IIS
(Internet Information Services)
Apache Web Server
• Began as the NCSA httpd server with some added features. It serves more than 100
million websites
• Name came from the ‘patchy’ version of httpd server. It is a set of software patches.

• Apache is the most widely used Web server because:


– It is both fast and reliable.
– It is open-source software, which means that it is free and is managed by a
large team of volunteers, a process that efficiently and effectively maintains
the system.
– It is one of the best available servers for Unix-based systems, which are most
popular for Web servers.

• Apache 2.0 was released in 2002, offering an updated execution environment .This
version also presented efficient support for a wider range of platforms, including
Unix, Linux, Windows and Mac OS X.

• Three Configuration Files in an Apache server:


httpd.conf
srm.conf
access.conf
IIS (Internet Information Services) Web Server

• Microsoft IIS server is supplied as part of Windows


• It only runs on windows and is optimized for windows. Most
Windows-based Web servers use IIS
• IIS-Operation is maintained through a window based
management program with a GUI
• It is a reasonably good server
Differences - IIS & Apache
Apache IIS
1. Apache is an open-source software. Hence 1. IIS is supplied as part of windows. It was
it is free designed for Microsoft’s Active Server
Pages
2. Supported by a large team of volunteers 2. IIS has a dedicated staff to answer most
problems
3. Apache is controlled by a configuration file
3. With IIS, server behavior is modified by
(httpd.conf) that is edited by the manager window-based management program
to change Apache’s behavior which allows the site manager to set
parameters for the server.
4. Apache can run on almost any OS including
4. IIS only runs on Windows and is optimized
UNIX, Apple’s OS X, and on most Linux for windows
Distributions.

5. Apache is a popular server because it is fast 5. IIS is a reasonably good server. Since the
and reliable and is the best available server Windows OS is prone to security risks , so is
the server
for Unix systems
HTTP (Request & Response)
The Hyper Text Transfer Protocol (HTTP)
• The protocol used by all Web communications
• Version 1.1 is used

• 2 phases of HTTP
– Request Header + Body
– Response

Header : contains information about the communication


Body : contains the data of the communication
Request Phase
• HTML Page
Coffee Survey
Enter the colour of coffee dark

What is the coffee taste malty

Submit

URL : Query String in the Request Line


http://www.coffee.com/info/coffee.html ? colour = dark & taste = malty

HTTP Request :
GET www.coffee.com/info/coffee.html ?
colour = dark & taste=malty HTTP/1.1
Request Phase
• General Form of request :

1. HTTP method Domain part of the URL HTTP version


GET www.coffee.com/info/coffee.html ? colour = dark & taste=malty HTTP/1.1

2. Header fields
Accept: text/html
Accept: text/plain
Accept-Language : en-us

3. Blank line

4. Message body – Not present in GET, HEAD and DELETE


Http Request Methods
Http Request Methods (Contd….)
• GET and POST are the most common methods used by the requests
• GET, HEAD and DELETE do not have a Body
• POST and PUT have a body
Example :
POST /coffee.html HTTP/1.1

// Header of the Request


Accept-Language : en-us
Accept: text/plain or text/html
Cookie:name1=value1
Date : Sun, 06 Nov 2014 1994 08:49:37 GMT

// Body of the request


colour = dark & taste=malty
HTTP Response

• Form:
1. Status line
2. Response header fields
3. Blank line
4. Response body

• Status line format:


HTTP version, status code, explanation of the status code

Example: HTTP/1.1 200 OK

• Common header Fields


content-length: 488
content-type: text/html
Different Status Codes
Status code is a three-digit number; first digit specifies the general status

100 Continue
200 Success GET,PUT,DELETE Successful Operation
201 Created POST Successful Creation of resource
202 Accepted POST,PUT,DELETE Request was received
204 No Content GET,PUT,DELETE Success, but no response body
301 Moved Permanently XHTML with link Resource has moved
400 Bad Request Client Error
401 Unauthorized Request Client Error
404 Not found
500 Server Error

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Important Return Codes :


200 : Success
404 : Not Found
500 : Server Error; Request not fulfilled
HTTP Headers
• Four categories of header fields:
 general (for general information like date)
Date: Thu, 13 Jul 2000 05:46:53 GMT

 request (for request headers)


Accept: text/plain ,text/html
Accept-Language : en-us

 response( included in response headers)


content-type: text/html
content-length: 488

 entity
 Used in both request and response.
 A wildcard character , the asterisk (*) can be used to specify that part of
MIME type . Eg accept:text/html and accept:text/plain can be
represented as accept : text / *
Request/Response Headers Examples
Common request field:
Accept: text/plain or text/html
Accept: text/*
Host: localhost
If-Modified since: date
Connection: Keep-Alive

Common response fields:


Server: Microsoft-IIS/5.0
Date: Thu, 13 Jul 2000 05:46:53 GMT
content-length: 2291
content-type: text/html
The Web Programmer’s Toolbox
• Document languages and programming languages that are the
building blocks of the web and web programming

–XHTML (Markup language)


–XML (Meta markup language)
–Javascript , Java, PHP, Ruby , Perl (Programming language)
–JSF, ASP.NET, and Rails ( development frameworks for
Web-based systems)
–Flash ( a technology for creating and displaying
graphics and animation in XHTML documents)
– Ajax (Web Technology that uses Javascript and XML)
–Plug-ins and Filters
Recent Versions of HTML

• HTML is defined with the use of the Standard Generalized Markup Language
(SGML)

• SGML is an ISO standard notation for describing text-formatting languages.

• Versions of HTML
– HTML (Initial Version) - 1994 (Tim Berners Lee)
– HTML 2.0 – 1995 (Followed W3C Standards )
– HTML 4.0 – 1997 (New features added & old ones removed)
– HTML 4.01 - 1999 (A cleanup of 4.0)
– XHTML 1.0 – 2000 (Just 4.01 defined using XML, instead of SGML)
– XHTML 1.1 – 2001 (Modularized 1.0, and drops frames)
– HTML 5.0
XHTML (eXtensible Hypertext Markup Language)
• XHTML has been defined using XML instead of SGML

• Used to describe the general form and layout of documents to be displayed


on browser

• An XHTML document is a mix of content and controls

•Controls are tags and their attributes

•Tags specify how the content should be arranged in the document

•Attributes provide additional information about the content of a tag.


Eg <image src=“photo.jpg”/>

• Tags and their content together are called an element.


Tools for Creating XHTML documents

• Basic Text Editors


- Notepad, Wordpad etc

• XHTML editors - make document creation easier


– Provide shortcuts to typing tag names
– spell-checker, thesaurus, syntax checker
– They color code the XHTML in the display to make it easier to read and edit.
– Adobe goLive , textMate , Geany , Brackets, Sublime

• WYSIWYG XHTML editors


– allow the user to create XHTML-described documents without requiring the user to know
XHTML.
– the writer can see the formatted XHTML document while he or she is writing the XHTML code.
– Microsoft FrontPage and Adobe Dreamweaver.
Difficulties using Wysiwyg editors
• These editors sometimes produce poor-quality XHTML.

• In some cases, they create tags that some browsers will not recognize.
Some cannot handle all of the tags of XHTML

• What you see may be what most visitors get, but it is not guaranteed to be
what everyone gets.

• Different browsers and applications will render the same markup


differently.

• A significant proportion of the page would need re-coding to suit the


requirements
Plug-ins and Filters
Converters for creating XHTML Documents.
• Plug-ins
– Are programs that are integrated into tools like word processors,
effectively converting them to WYSIWYG XHTML editors
– Provides new capabilities to the word processor such as toolbar buttons
and menu elements
• Filters
– Convert documents in other formats, to XHTML. Eg LaTex
– They are never a part of the editor, so they can be platform independent.
Word-Perfect user working on a Macintosh computer can use a filter
running on a UNIX platform, that can provide a document that can be
converted into XHTML
– Disadvantage is that it’s a two step process.
Plugins and Filters: Advantages and Disadvantages
• Advantages of both filters and plug-ins:
– Existing documents produced with other tools can be
converted to XHTML documents
- XHTML knowledge is not required.
– Use a tool you already know to produce XHTML
• Disadvantages of both filters and plug-ins:
– XHTML output of both is not perfect - must be fine tuned
– XHTML may be non-standard
– You have two versions of the document, which are
difficult to synchronize. Leads to version problems.
XML (Extensible Markup Language)

• A meta-markup language , which defines markup languages.


• SGML was one of the meta markup languages which created HTML
• Because of the deficiencies of HTML, XML was developed.
• In XML, the meaningful tags are designed for a specific area. User is not
restricted to use only particular tags.
• No restriction on the arrangement and order of tags.
• A simple and universal way of representing data of any text kind
<ad>
<year> 1977 </year>
<model> skyhawk </model>
<price> 23,495 </price>
</ad>
JavaScript
<body>
<script type = “text/javascript”>
var num;
document.write(“<h1> Hello World </h1>”);
</script>
</body>
• A client-side XHTML-embedded scripting language. Interpreted by an interpreter on
the browser on the client machine
• Primary uses in Web programming are to validate form data and to create dynamic
XHTML documents.
• Only related to Java through syntax
• Dynamically typed unlike programming languages
• Object based and not Object-oriented
• Provides a way to access elements of HTML documents and dynamically change them
PHP
• A server-side scripting language
• Similarity with Javascript :
 Embedded in XHTML but code is interpreted on server before
XHTML document is delivered to client. Browser never sees
embedded code. This is not so in Javascript.
 Similar in syntactic appearance and dynamic nature of
strings and arrays
 Both use dynamic data typing
• Form processing is easy
• Provides support for many different database systems
Java

•General purpose object-oriented programming


language
•Based on C++, but simpler and safer
•Our focus is on Applets, Servlets, and JSP
Perl
• Provides server-side computation for XHTML documents, through CGI.
This was before applets and embedded scripts were developed

• CGI (Common Gateway Interface) is a standard way in which a browser


and server communicate with each other, to run a program on server

• Perl is good for CGI programming because:


– Highly portable
– Direct access to operating systems functions
– Access to database systems
– Powerful character string pattern-matching operations
• It is compiled to an intermediate code and then interpreted
Ruby
• Developed as replacement for Perl and Python

• Pure Object-Oriented interpreted scripting language where every data


value is an object which use methods for operation

• All classes user defined or predefined, can have sub-classes

• Both classes and objects are Dynamic. So they can have different sets of
methods at different times

• Dynamic Typing is used so no need to declare variables.

• Rails is most common use of Ruby


Rails
• A development framework for Web-based applications that
access databases.

• A framework is a system where more or less standard


software parts are furnished by the framework. Famous
framework is ASP.NET and JSF

• Written in Ruby and uses Ruby as its primary user language

• Rails is based on Model-View-Controller(MVC) – divides


applications into : presentation , data model and program
logic

• Rails applications are tightly bound to Relational Databases


Ajax
• Asynchronous JavaScript + XML

• Much faster for Web applications that have extensive


user/server interactions because :
– Browser uses asynchronous requests to the server. (Browser need not
wait for the server to respond)
– Server sends only a small part of the displayed document, so it takes
less time to be transmitted and rendered , resulting in much faster
responses

Advantages
• Technologies used are supported by nearly all browsers
• Doesn’t require learning of new tool and language. Its just
requires a new way of thinking about web interactions.
XHTML
Origins and Evolution of HTML
• HTML was defined with SGML (Standard General markup
Language)
• Original intent of HTML:
General layout of documents that could be displayed by a wide
variety of computers

• Recent versions:
– HTML 4.0 – 1997
• Introduced many new features and deprecated many older features
– HTML 4.01 - 1999 - A cleanup of 4.0
– XHTML 1.0 - 2000
• Just 4.01 defined using XML, instead of SGML
– XHTML 1.1 – 2001
• Modularized 1.0, and drops frames
• We‟ll stick to 1.1, except for frames
Origins and Evolution of HTML
• Reasons to use XHTML, rather than HTML:
1. HTML has lax syntax rules, leading to sloppy and
sometime ambiguous documents
– XHTML syntax is much more strict, leading to clean and
clear documents in a standard form
2. HTML processors do not even enforce the few syntax rule
that do exist in HTML
3. The syntactic correctness of XHTML documents can be
validated
Syntactic Differences between HTML & XHTML

• Case sensitivity
• Closing tags
• Quoted attribute values
• Explicit attribute values
• id and name attributes
• Element nesting
All these rules in XHTML can be checked by xhtml validator
http://validator.w3.org/file-upload.html
3 steps
1)Any page you design can be uploaded
2)all errors can be listed
3) finally you can correct them
Basic Syntax
Basic Syntax
• Elements are defined by tags (markers)
– Tag format: <html> ..……. </html>
• Opening tag: <name>
• Closing tag: </name>
– The opening tag and its closing tag together specify a container for
the content they enclose
• Not all tags have content
– If a tag has no content, its form is <name />

• The container and its content together are called an element


• If a tag has attributes, they appear between its name and the right
bracket of the opening tag Eg <image src = “photo.jpg” />
Basic Syntax (continued)
• Comment form: <!-- … -->
• <!—

• -->

• Browsers ignore comments,


unrecognizable tags, line breaks, multiple
spaces, and tabs
• Tags are suggestions to the browser, even
if they are recognized by the browser
XHTML Document Structure
• Every XHTML document must begin with:
<?xml version = ″1.0″?>
<!DOCTYPE html PUBLIC ″-//w3c//DTD XHTML 1.1//EN″
http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd>
• <html>, <head>, <title>, and <body> are required in every
document
• The whole document must have <html> as its root
• html must have the xmlns attribute:
<html xmlns = ″http://www.w3.org/1999/xhtml″
• A document consists of a head and a body
• The <title> tag is used to give the document a title, which is normally
displayed in the browser‟s window title bar (at the top of the display)
Basic Text Markup
• Text is normally placed in paragraph elements
• Paragraph Elements
– The <p> tag breaks the current line and inserts a blank line - the new line gets the
beginning of the content of the paragraph
– The browser puts as many words of the paragraph‟s content as will fit in each line
<?xml version = ″1.0″?>
<!DOCTYPE html PUBLIC ″-//w3c//DTD XHTML 1.1//EN″
http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd>
<!-- greet.hmtl
A trivial document
-->
<html xmlns = ″http://www.w3.org/1999/xhtml″>
<head> <title> Our first document </title>
</head>
<body>
<p>
Greetings from your Webmaster!
</p>
</body>
</html>
Basic Text Markup (continued)
• W3C HTML Validation Service
http://validator.w3.org/file-upload.html
This is provided to validate XHTML documents against its
standards
• Line breaks <br/> tag
– The effect of the <br /> tag is the same as that of <p>, except for the blank line
• No closing tag!
• Example of paragraphs and line breaks
On the plains of hesitation <p> bleach the
bones of countless millions </p> <br />
who, at the dawn of victory <br /> sat down
to wait, and waiting, died.

• Typical display of this text:


On the plains of hesitation

bleach the bones of countless millions


who, at the dawn of victory
sat down to wait, and waiting, died.
Document Validation
Validation Output
Basic Text Markup (continued)
• Headings
– Six sizes, 1 - 6, specified with <h1> to
<h6>
– 1, 2, and 3 use font sizes that are larger
than the default font size
– 4 uses the default size
– 5 and 6 use smaller font sizes

<!-- headings.html
An example to illustrate headings
-->
<html xmlns = ″http://www.w3.org/1999/xhtml″>
<head> <title> Headings </title>
</head>
<body>
<h1> Aidan’s Airplanes (h1) </h1>
<h2> The best in used airplanes(h2)</h2>
<h3> "We’ve got them by the
hangarful"(h3) </h3>
<h4> We’re the guys to see for a good used
airplane (h4) </h4>
<h5> We offer great prices on great planes
(h5) </h5>
<h6> No returns, no guarantees, no refunds,
all sales are final (h6) </h6>
</body>
</html>
Basic Text Markup (continued)
Font Styles and Sizes (can be nested)
Boldface - <b>
Italics - <i>
Larger - <big>
Smaller - <small>
Monospace - <tt>

<p>This text is normal.</p>


<p><big>This text is bigger.</big></p>
This text is normal.
This text is bigger.
The <big> sleet <big> in <big> <i> Crete
</i><br /> lies </big> completely </big>
in </big> the street

in Crete
The sleet

lies completely in the street


Blockquotes To set a block of text off from the normal flow and
appearance of text
<blockquote>………</blockquote>
Blockquote
Basic Text Markup (continued)

• Superscripts and subscripts


• Subscripts with <sub>
• Superscripts with <sup>
Example : x<sub>2</sub><sup>3</sup> + y<sub>1</sub><sup>2</sup>

• Inline versus block tags


– The content of an inline tag appears on the current line.
• <em> and <strong> are inline tags.
– A block tag breaks the current line so that its content appears on a new line.
• Heading and <blockquote> tag is block tag
– Block elements CANNOT be nested in inline elements
Usage of Character Entity
<html>
<head><title>Character Entities</title></head>
<body>
<p> An&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;example of
character&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;entity</p>
</body>
</html>
Output on Browser
An example of character entity
Explanation:
& means beginning of special character
; means end of special character
‘< ‘and ‘>’ are also special because they may be confused with the markup
tags
Basic Text Markup (continued)
• Entities: are used to implement reserved characters or to express characters that cannot be
entered with the keyboard. These characters are needed in the document but cannot be typed
as themselves
In some cases characters do not appear on the keyboard. Eg Degree ()
• Character Entities
Char. Entity Meaning
& &amp; Ampersand
< &lt; Less than
> &gt; Greater than
” &quot; Double quote
’ &apos; Single quote
¼ &frac14; One quarter
½ &frac12; One half
¾ &frac34; Three quarters
 &deg; Degree
(space) &nbsp; Non-breaking space

• Horizontal rules
– <hr /> draws a line across the display, after a line break
The meta element
• The meta element is used to provide
additional information about a document.
• Meta tag has no content. All the information


is specified through the attributes only.
Two attributes used for providing
Example
information are:
name and content.
• User makes up a name for name attribute
and provides information about that name in
content.
• Eg.
• <meta name=“keywords” content=“binary
trees, linked lists, stacks” />
• Web search engines use the information in
content to categorize Web documents in
their indices.
Images
• GIF (Graphic Interchange Format)
– 8-bit color (256 different colors)
• JPEG (Joint Photographic Experts Group)
– 24-bit color (16 million different colors)
• Both use compression, but JPEG compression is better
• Images are inserted into a document with the <img /> tag with the src
attribute
<img src = "comets.jpg“ alt = "Picture of comets" />
• Value of alt is displayed when image cannot be displayed by the browser

• The <img> tag has 30 different attributes, including width and height (in pixels)
– The alt attribute is required by XHTML.
• Purposes:
1. Non-graphical browsers
2. Browsers with images turned off

• Portable Network Graphics (PNG)


– Relatively new
– Should eventually replace both gif and jpeg
Images (continued)
<!-- image.html
An example to illustrate an image -->
<html xmlns =
“http://www.w3.org/1999/xhtml″>
<head> <title> Images </title>
</head>
<body>
<h1> Aidan's Airplanes </h1>
<h2> The best in used airplanes </h2>
<h3> "We've got them by the hangarful"
</h3>
<h2> Special of the month </h2>
<p>
1960 Cessna 210 <br />
577 hours since major engine overhaul
<br />
1022 hours since prop overhaul
<br /><br />
<img src = "c210new.jpg"
alt = "Picture of a Cessna 210"/>
<br />
Buy this fine airplane today at a
remarkably low price <br />
Call 999-555-1111 today!
</p>
</body>
</html>
Hypertext Links (Anchor tag)
<!-- link.html
An example to illustrate a link
-->
<html xmlns =
″http://www.w3.org/1999/xhtml″>
<head> <title> Links </title>
</head>
<body>
<h1> Aidan's Airplanes </h1>
<h2> The best in used airplanes </h2>
<h3> "We've got them by the hangarful"
</h3>
<h2> Special of the month </h2>
<p>
1960 Cessna 210 <br />
<a href = "C210data.html">
Information on the Cessna 210
</a>
</p>
</body>
</html>
Hypertext Links (continued)
• Links can have images:
<a href = "c210data.html“>
<img src = "smallplane.jpg"
alt = "Small picture of an airplane " />
Info on C210 </a>
Image of the plane is the link

• If the target is not at the beginning of the document, the target spot must be
marked
• Target labels can be defined in many different tags with the id attribute, as in
<h1 id = "baskets"> Baskets </h1>
• The link to an id must be preceded by a pound sign (#); If the id is in the same
document, this target could be
<a href = "#baskets"> Jump to baskets </a>
• If the target is in a different document, the document reference must be included
<a href = "myAd.html#baskets”> Baskets </a>
• Style note: a link should blend in with the surrounding text, so reading it without
taking the link should not be made less pleasant
LIST
1. Unordered List
2. Ordered List
3. Nested List
4. Definition List
Unordered Lists
• Unordered lists uses <ul> tag
• List elements are the content of the <li> tag

<h3> Some Common Single-Engine Aircraft </h3>


<ul>
<li> Cessna Skyhawk </li>
<li> Beechcraft Bonanza </li>
<li> Piper Cherokee </li>
</ul>
Ordered lists
• Ordered lists <ol> tag
• Each item in the display is preceded by a sequence value
<h3> Cessna 210 Engine Starting Instructions </h3>
<ol>
<li> Set mixture to rich </li>
<li> Set propeller to high RPM </li>
<li> Set ignition switch to "BOTH" </li>
<li> Set auxiliary fuel pump switch to
"LOW PRIME" </li>
<li> When fuel pressure reaches 2 to 2.5
PSI, push starter button </li>
</ol>
Lists (continued)
• Nested lists

• Any type list can be nested inside any type list


• The nested list must be in a list item
Definition Lists
• Definition lists (for glossaries, etc.)
– List is the content of the <dl> tag
– Terms being defined : <dt> tag
– The definitions themselves : <dd> tag

<h3> Single-Engine Cessna Airplanes </h3>


<dl >
<dt> 152 </dt>
<dd> Two-place trainer </dd>
<dt> 172 </dt>
<dd> Smaller four-place airplane </dd>
<dt> 182 </dt>
<dd> Larger four-place airplane </dd>
<dt> 210 </dt>
<dd> Six-place airplane - high performance
</dd>
</dl>
TABLES
Tables
• A table is a matrix of cells, each possibly having content
• The cells can include almost any element
• Some cells have row or column labels and some have data
• A table is specified as the content of a <table> tag
• A border attribute in the <table> tag specifies a border between the cells
• If border is set to "border", the browser’s default width border is used
• The border attribute can be set to a number, which will be the border width
• Without the border attribute, the table will have no lines!
• Tables are given titles with the <caption> tag, which can immediately follow
<table>
Tables (continued)
• Each row of a table is specified as the content of a <tr> tag
• The row headings are specified as the content of a <th> tag
• The contents of a data cell is specified as the content of a <td> tag
<table border = "border">
<caption> Fruit Juice Drinks </caption>
<tr>
<th> </th>
<th> Apple </th>
<th> Orange </th>
<th> Screwdriver </th>
</tr>
<tr>
<th> Breakfast </th>
<td> 0 </td>
<td> 1 </td>
<td> 0 </td>
</tr>
<tr>
<th> Lunch </th>
<td> 1 </td>
<td> 0 </td>
<td> 0 </td>
</tr>
</table>
Tables (continued)
• A table can have two levels of column labels
– If so, the colspan attribute must be set in the <th> tag to specify
that the label must span some number of columns
<tr>
<th colspan = "3"> Fruit Juice Drinks </th>
</tr>
<tr>
<th> Orange </th>
<th> Apple </th>
<th> Screwdriver </th>
</tr>
Tables (continued)

• If the table has two levels of column labels and also has row labels , the upper
left corner must be made larger, using rowspan and colspan
<table border = "border">
<caption> Fruit Juice Drinks and Meals </caption>
<tr>
<td rowspan = "2"> </td>
<th colspan = "3"> Fruit Juice Drinks </th>
</tr>
<tr>
<th> Apple </th>
<th> Orange </th>
<th> Screwdriver </th>
</tr>
<tr>
<th> Breakfast </th>
<td> 0 </td>
<td> 1 </td>
<td> 0 </td>
</tr>
………
</table>
Tables (continued)
• The align attribute controls the horizontal placement of the
contents in a table cell
– Values are left, right, and center (default)
– align is an attribute of <tr>, <th>, and <td> elements
• The valign attribute controls the vertical placement of the
contents of a table cell
– Values are top, bottom, and center (default)
– valign is an attribute of <th> and <td> elements
 SHOW cell_align.html and display it
• The cellspacing attribute of <table> is used to specify the
distance between cells in a table
• The cellpadding attribute of <table> is used to specify the spacing
between the content of a cell and the inner walls of the cell
Align and Valign Attributes
<table border = "border">
<caption> The align and valign attributes </caption>
<tr align = "center">
<th> </th>
<th> Column Label </th>
<th> Another One </th>
<th> Still Another One </th>
</tr>
<tr>
<th> align </th>
<td align = "left"> Left </td>
<td align = "center"> Center </td>
<td align = "right"> Right </td>
</tr>
<tr>
<th> valign </th>
<td> Default </td>
<td valign = "top"> Top </td>
<td valign = "bottom"> Bottom </td>
</tr>
</table>
Cell Padding and Cell Spacing

Cell Spacing

Cell Padding
Tables (continued)
<table cellspacing = "50">
<tr>
<td> Colorado is a state of …
</td>
<td> South Dakota is somewhat…
</td>
</tr>
</table>
Forms-Towards Interactivity
• A form is the way of getting information from a browser to a
server and simplify navigation

• Forms are used to add interactivity to a website.

• HTML has tags to create a collection of objects that implement this


information gathering from the forms.
– The objects are called widgets (e.g., radio buttons and checkboxes)

• When the Submit button of a form is clicked, the form’s values


are sent to the server

• <form> and </form> tags


Forms (continued)

• <form> tag is used to define forms


Attributes in <form> tag :
1. action : which specifies the URL of the application that is to be called when the
Submit button is clicked
<form action =http://www.cs.ucp.edu/survey.pl>

2. method (GET and POST) : specifies techniques of transferring the form data to
the server
<form action =http://www.cs.ucp.edu/survey.pl
method=“GET”>
– If the form has no action, the value of action is the empty string
eg. <form action = “ “ >
Widgets
– Widgets are created with the <input> tag

<input type = “button" name =“button1“ value = “b1" />


• The type attribute of <input> specifies the kind of widget
being created

1. TextBox ( type=“text” )
2. Reset and Submit Button ( type=“reset” and type=“submit”)
3. TextArea (<textarea> tag )
4. Checkboxes ( type=“checkbox” )
5. Radio Button ( type=“radio” )
6. Menus ( <select> tag )
Forms (continued)
1. Text
• Creates a horizontal box for text input
• Default size is 20; it can be changed with the size attribute
• If more characters are entered than will fit, the box is scrolled (shifted) left
<input type = “text" name =“name” size=“25” maxlength=“25” />

2. Checkboxes - to collect multiple choice input


– Every checkbox requires a value attribute, which is the widget‟s value in
the form data when the checkbox is „checked‟
– By default, no checkbox is initially „checked‟
– To initialize a checkbox to „checked‟, the checked attribute must be set
to "checked“
<input type = "checkbox" name ="groceries“ value = "milk" checked = checked”/>
Widgets
Grocery Checklist
<form action = "">
<p>
<label><input type = "checkbox" name ="groceries"
value = "milk" checked = "checked“/> Milk </ label>
<label><input type = "checkbox" name ="groceries“
value = "bread“/> Bread </label>
<label><input type = "checkbox" name = "groceries"
value= "eggs“/> Eggs </label>
</p>
</form>
Forms – Radio Buttons
3. Radio Buttons
collections of checkboxes in which only one button
can be „checked‟ at a time Every button in a radio
button group MUST have the same name
• If no button in a radio button group is
pressed‟, the browser often „presses‟ the first one

<form action = “ “>


<p>Age Category
<label> <input type = "radio" name = "age"
value = "under20" checked = "checked“/>
0-19</label>
<label><input type = "radio" name = "age"
value = "20-35“/> 20-35</label>
<label> <input type = "radio" name = "age"
value = "36-50“/> 36-50 </label>
<label><input type = "radio" name = "age"
value = "over50“/> Over 50</label>
</p>
</form>
Reset and Submit buttons
Reset and Submit buttons are created with <input>
-Reset button clears all of the controls in the form to their
initial state.
- Submit button is used to indicate that the form data is to be sent
to server for processing.

<form action =http://www.cs.ucp.edu/survey.pl>


– A Submit button is required in every form

<input type = "reset" value = "Reset Form“/>


<input type = "submit” value = "Submit Form“/>

• Submit has two actions:


1. Encode the data of the form
2. Request that the server execute the server-resident program specified as the value of
the action attribute of <form>
Menus
- Widgets (continued)

• After clicking the menu:

• After changing size to 2:

• With multiple
Menus (continued)

<form action = "">

<p>Grocery Menu <br/>

With size = 1 (the default)

<select name = "groceries">


<option> milk </option>
<option> bread </option>
<option> eggs </option>
<option> cheese </option>
</select>

</p>

</form>
Menus
Menus - created with <select> tags
Attributes for Menu
• name attribute
• size attribute : specifies the number of menu items to be displayed
(the default is 1)

• Item of a menu is specified with an <option> tag

2 kinds of Menus
• Behave like checkboxes (specified by including the multiple attribute, )
• Behave like radio buttons (the default)
TEXT AREAS
5. TextArea : created with <textarea>
– Includes the rows and cols attributes to specify the size of the
text area
– Default text can be included as the content of <textarea>
– Scrolling is implicit if the area is overfilled

<form action = "">


<p>Please provide your employment aspirations</br>
<textarea name = "aspirations" rows = "3”
cols = "40">
</textarea>
</p>
</form>
HTML 5
HTML 5 Introduction
• HTML 5 is a markup language used for structuring and presenting content on
the World Wide Web
• It is the fifth and current major version of the HTML standard
• Its goals are to improve the language with support for the latest multimedia
and other new features; to keep the language both easily readable by humans
and consistently understood by computers and devices such as Web
browsers, parsers, etc., without XHTML's rigidity; and also to
remain backward-compatible with older software
• HTML 5 is also a candidate for cross-platform mobile applications, because it
includes features designed with low-powered devices in mind.
• Many new syntactic features are included. To natively include and
handle multimedia and graphical content, the
new <video>, <audio> and <canvas> elements were added. It also supports
drag and drop feature for the items from one location to another location on
the same webpage
• Some deprecated elements have been dropped such as <font> and <center>
• It comes with a new introductory line - <!DOCTYPE html>
HTML 5 Features
Here is a set of some of the most prominent features introduced in HTML5.
• New Semantic Elements − These are like <header>, <footer>, and <section>.
• Forms 2.0 − Improvements to HTML web forms where new attributes have been
introduced for <input> tag.
• Persistent Local Storage − To achieve without resorting to third-party plugins.
• WebSocket − A next-generation bidirectional communication technology for web
applications.
• Server-Sent Events − HTML5 introduces events which flow from web server to the
web browsers and they are called Server-Sent Events (SSE).
• Canvas − This supports a two-dimensional drawing surface that you can program
with JavaScript.
• Audio & Video − You can embed audio or video on your webpages without
resorting to third-party plugins.
• Geolocation − Now visitors can choose to share their physical location with your
web application.
• Microdata − This lets you create your own vocabularies beyond HTML5 and extend
your web pages with custom semantics.
• Drag and drop − Drag and drop the items from one location to another location on
the same webpage.
New Semantic Elements
• <nav> : The <nav> tag defines a set of navigation links.
• <article> :
The <article> tag specifies independent, self-contained content. Potential sources
for the <article> element: Forum post, Blog post, News story and Comment
• <section>
The <section> tag defines sections in a document, such as chapters, headers,
footers, or any other sections of the document
• <header>
The header element specifies a header for a document or section.
• <footer>
The footer element specifies a footer for a document or section.
• <aside>
The <aside> tag defines some content aside from the content it is placed in. The
aside content should be related to the surrounding content.
• <canvas>
The canvas element is only a container for graphics. You must use JavaScript to
actually draw the graphics. By default, a canvas has no border and no
content....Canvas has several methods for drawing paths, boxes, circles, text, and
adding images.
Nav Tag (Navigation Bar)

<nav>
<a href=“about.html">About</a>|
<a href="https://www.w3schools.com">
Home</a>
<a href=“sports.html”>Sports</a>
</nav>
New Input Tag attributes
• number
Age: <input type=“number" name=“age“ min=“5” max=“10” step=“1”>
• date
Birthday: <input type="date" name="bday">
• time
(a) Time : <input type=“time" name=“time">
(b) <p>We open at <time>10:00</time> every morning.</p>
<p>I have a meeting on <time datetime="2018-07-01 20:00">Labor Day</time> </p>
• email
Email : <input type=“email" name=“email">
• url
URL: <input type=“url" name="blog">
• Range
CGPA : <input type=“range" name=“cgpa">
• date
Date: <input type="date" name="bday">
• Search
Enter Search string <input type="search" id=“mysearch" name=“s1“ placeholder="Search the
site...“ />
<button>Search</button>
• tel
<input type="tel" name="tel" id="tel" required>
Output of HTML 5 Pgm
color and date
Date Attribute
• date
Date: <input type="date" name="bday">
color
• color
<input type=“color" name=“col”>
New Embedded Media Elements
• <audio>
Eg <audio controls>
<source src="Bells.mp3" type="audio/mpeg">
• <video>
Eg <video width="320" height="240" controls>
<source src="Bells.mp3" type="video/mp4">
• <canvas>
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #d3d3d3;">
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.moveTo(0,0);
ctx.lineTo(200,100);
ctx.stroke();
</script>
Cascading Style Sheets
Cascading Style Sheets - Introduction
• CSS1 specification - developed in 1996.
• CSS2 - in 1998. More properties were added.
• CSS3 is in development process.

• CSS is a syntactic mechanism for specifying style information.


• Cascading Style Sheets were introduced to provide a consistent way
to specify the presentation in XHTML documents.
– They impose a standard style on a whole document, or even a whole
collection of documents.

• CSS can be embedded in HTML documents


• Style is specified for a tag by the values of its properties
eg < h1 style = “ color:red” >
Cascading Style Sheets
• XHTML style sheets are called cascading style sheets because they
can be defined at three different levels to specify the style of document.
- Lower level style sheets override higher levels so the style of a tag is
determined through a cascade of style sheets.

• Three levels of style sheets


• Inline style sheet- Apply to contents of single XHTML element .
Appear in the tag itself At the lowest level. They have the highest
precedence.

• Document-level style sheets - apply to the whole body of the


document . Appear in the head of the document. These have lower
precedence than Inline but higher than External Stylesheets

• External style sheets - can be applied to more than one document.


Are in separate files, potentially on any server on the Internet. These
have the lowest precedence
Levels Of Style Sheets
• Three levels of style sheets
• Inline - Apply to contents of single XHTML element . Appear in the tag itself At the lowest
level.

<h1 style=“color:red;font-size:36pt;”>

• Document-level style sheets - apply to the whole body of the document . Appear in the head
of the document
<head>
<style type = "text/css">
h1 {font-size: 24pt;color:red}
h2, h3 {font-size: 20pt;}
</style>
</head>

• External style sheets - can be applied to more than one document. Are in separate files,
potentially on any server on the Internet

<link rel = "stylesheet" type = "text/css"


href = http://www.wherever.org/termpaper.css”/>
Style Specification Formats
Inline Style Sheets

Inline style sheets:

– Style sheet appears as the value of the style attribute of a tag.


– General form:
<tag style = "property_1: value_1; property_2:value_2;
………………………
property_n:value_n“ >

Eg. <h1 style=“color:red;font-size:36pt;”>


Disadvantage of Inline Style Sheet
1. This leads to non uniform style in a document

2. It is always better to keep style information


separate from the markups. But in case of inline
style sheets we have style information
embedded at various places in the whole
document

3. Because of these reasons, W3C deprecated


inline style sheet from XHTML 1.1
Document Level
• Specified in style element in head section of document.
• General form:
<head>
<style type = "text/css">
style-rule-list
</style>
</head>
• Each style rule in a rule list has two parts:
• a selector, which indicates the tag or tags affected by the rule
• a list of property–value pairs.
(like in inline stylesheet but delimited by braces instead of quotes)
selector { property_1:value_1; property_2:value_2;

property_n:value_n;
}
Eg <style type = "text/css">
h1 {font-size: 24pt;color:red}
h2, h3 {font-size: 20pt;}
</style>
External Style Sheets (link tag)
– A <link> tag is used to fetch and use an external style sheet file in the
head section of the document.
<link rel = "stylesheet" type = "text/css” href = “sample.css”/>
– The rel attribute is used to specify the relationship of the linked-to
document to the document in which the link appears.
– href specifies the URL/filename of the style sheet

– @import url(filename) is alternative way of specifying style sheets


Difference between link and @import :
• @import appears only at beginning of document
<style type="text/css">
@import url("import.css");
</style>
External style sheets

• These are stored in separate files and can apply to number of documents.
• Extension of CSS files is - .css
• sample.css
selector 1{
property_1: value_1;
property_2: value_2;

property_n: value_n;
}
………………………………….
………………………………..
selector n{
property_1: value_1;

property_n: value_n;
}
Selector Forms
Selector Forms
• Simple Selectors (the property values in the rule apply to all
occurrences of the named element)
• Class Selectors (Used to allow different occurrences of the same
tag to use different style specifications)
• Generic Selectors (if you want a style to apply to more than one
kind of tag)

• Id Selectors (application of a style to more than one element)

• Universal Selectors (The properties specified are applied to all


the elements in the document )
• Pseudo Classes (apply when something happens )
Simple Selector
• The simplest selector form is a single element name, such as h 1
• In this case, the property values in the rule apply to all occurrences of
the named element. Eg.
 h1 {font-size: 24pt;}
 h2, h3 , p {font-size: 20pt;}

• Contextual selectors (descendant selector)


• Selectors can also specify that the style should apply only to elements in
certain positions in the document.
Eg. form em {font-size: 14pt;}
applies its style only to the content of emphasis elements that are nested
in a form element in the document.
Class Selectors (pgm1css.html)
• Used to allow different occurrences of the same tag to use different
style specifications
• A style class is defined in a style element by giving the style
class a name, which is attached to the tag’s name with a period.
– p.narrow { property:value list;}
– p.wide {property:value list}

 Within the document body, the class you want on a particular


occurrence of a tag is specified with the class attribute of the tag
• For example,
<p class = "narrow“>This line will appear to be narrow</p>
...
<p class = "wide"> This line will be wider than the others</p>
Generic Selectors
• A generic class can be defined if you want a style
to apply to more than one kind of tag

• A generic class must be named, and the name


must begin with a period. Example,
.sale { property:value; }

• Use it as if it were a normal style class


.sale {font-size: 20;}
<h1 class = “sale"> weekend sale </h1>
...
<p class = “sale"> This contains terms and
conditions for sale
</p>
Id Selectors
• An id selector allow the application of a style
to more than one element( similar to generic
selector)
• General form:
#specific-id {property-value list}

• Example:

#section14 {font-size: 20;}


<p id=“section14”>Information on cats </p>
Universal Selectors
• The Universal selector is denoted by asterisk (*)

• The properties specified are applied to all the


elements in the document
• Example:
* {color:red;font-size:18pt;}

<h2>Information on cats </h2>


<p> Information on cats </p>
Pseudo Classes
• Pseudo classes are styles that apply when something happens, rather
than because the target element simply exists
• Names begin with ‘ : ‘
• hover classes apply when the mouse cursor is over the element
• focus classes apply when an element has focus
<!-- pseudo.html -->
<html xmlns = "http://www.w3.org/1999/xhtml">
<head> <title> Checkboxes </title>
<style type = "text/css">
h1:hover {background-color:blue ; color:white;}
input:hover {color: red; background-color:yellow}
input:focus {color: white; background-color:magenta}
</style>
</head>
<body>
<h1>Enter the details of form</h1>
<form action = "">
Your name: <input type = "text" name=“name1”/>
</form>
</body> </html>
Pseudo Classes : Hover and Focus
Example for psuedo classes
<html>
<head><title>Pseudo Classes</title>
<style type="text/css">
input:hover {color:red;background-color:yellow;}
input:focus {color:green;background-color:magenta;}
h1:hover {background-color:blue;color:white;}
</style>
</head>
<body>
<h1>Enter the details of form</h1>
<h2>This is a simple form</h2>
<form action="">
<label>Enter your name <input type="text" name="text1"/></label>
</form>
</body></html>
Properties
• There are 60 different properties in 7 categories:
– Fonts
– Lists
– Alignment of text
– Margins
– Colors
– Backgrounds
– Borders
Property Values
– Length – numbers
• Units:
– px – pixels ; A dot on the computer screen
– in (inches)
– cm (centimeters)
– mm (millimeters)
– pt (points - 1/72 inches)
– pc (picas - 12 points or 12/72 inches)
– em (value of the current font size in pixels )
font-size:2 em (2*default-font-size)
– No space is allowed between the number and the unit specification
e.g 1.5 in // is illegal!
Font Properties
• font-style : italic, oblique , normal
• font-weight: bold, bolder, light, lighter, normal
specifies the degrees of boldness. Multiple of 100 (100 –900), 400 normal, 700 bold
• font–variant: normal or small-caps
• font-size: 10pt , xx-small, small, x-small, medium, large, x-large, xx-large,
smaller, larger, 75%, -75%, +75%
• font :
For specifying a list of font properties. The font names must be last,
the font size must be second to last. Font style, font variant, and font weight,
when they are included, can be in any order but must precede the font size and
font names.
font: bolder 14pt Arial Helvetica
Text properties
• text-decoration :line-
through, overline, underline,
none
• letter-spacing – value is
any length property value.
Eg letter-spacing : 5px

• word-spacing – value is
any length property value
eg word-spacing : 10px
Font Family

• font-family
– List of font names - Browser uses the first in the list it has
Eg. font-family: Arial, Helvetica, „Times New Roman‟
– Every Browser has a Generic name for the font names
– Safest way is to specify a font-family is as follows
font-family:Arial , san-serif
– The font-family property can hold several font names as a "fallback" system. If the
browser does not support the first font, it tries the next font.

Generic –names Examples


Serif Times New Roman,Garamond
san-serif Arial,Helvetica
Cursive Caflisch Script,Zapf-chancery
Fantasy Critter,Cottonwood
monospace Courier,Prestige
External Stylesheet Example
Document-html
External Style Sheet
<html>
<head><title>Font Properties</title>
<style type="text/css">
Example for fonts
p.major{font-size:14pt;
font-style:italic;
font-family:'Times New Roman';
}
p.minor{font:10pt bold 'Courier New';}
p.delete{text-decoration:line-through;}
p.oline{text-decoration:overline;}
p.uline{text-decoration:underline;font-size:12pt;font-family:sans-serif}
h2{font-family:cursive;
font-size:24pt;
font-weight:bold;}
h3{font-family:fantasy;font-size:18pt;}
h1{font-family:'Britannic Bold';}
h4{font-family:'Bradley Hand ITC';font-size:14pt;}
h5{font-family:'Algerian';font-size:12pt;}
h6{font-family:'Freestyle Script';font-size:10pt;}
</style>
</head>
<body>
<p class="major">This is a paragraph with major class</p>
<p class="minor">This is a paragraph with minor class</p>
<p class="delete">This is a paragraph with delete class</p>
<p class="oline">This is a paragraph with oline class</p>
<p class="uline">This is a paragraph with uline class</p>
<h2>This is a heading level 2</h2>
<h3>This is a heading level 3</h3>
<h1>This is a heading level 1</h1>
<h4>This is a heading level 4</h4>
<h5>This is a heading level 5</h5>
<h6>This is a heading level 6</h6>
</body></html>
Colors
• Color is a problem for the Web for two reasons:
1. Monitors vary widely
2. Browsers vary widely

Ways of specifying Colors :

- Named Colors : There is a set of 17 colors that are guaranteed to be


displayable by all graphical browsers on all color monitors
black 000000 green 008000
silver C0C0C0 lime 00FF00
gray 808080 olive 808000
white FFFFFF yellow FFFF00
maroon 800000 navy 000080
red FF0000 blue 0000FF
purple 800080 teal 008080
fuchia FF00FF aqua 00FFFF

- Web Palette is a much larger set Now nearly 256 colors are named
colors which browsers understand .So a function
rgb(0-255,0-255,0-255) can be used to generate any color we need

- Hexadecimal values Can specify 16 million colors.


#000000 – FFFFFF
#FF0000-RED #000000-Black #FFFFFF-White
Color Property

• The color property specifies the


foreground color of elements

<style type = “text/css”>


th.red {color: red}
th.orange {color: orange}
th.blue {color: blue}
</style>

<table border = "5">
<tr>
<th class=“red”> Apple </th>
<th class = "orange"> Orange </th>
<th class = “blue"> Banana </th>
</tr>
</table>
Background-Color property

The background-color property


specifies the background color of
elements

<body>
<p style="background-color:yellow">
This is an example of background
color property..
</p>
</body>
Alignment of Text
• text-indent
property allows indentation of the first line of the paragraph. Takes
either a length or a % value
text-indent : 0.5in Example :
The paragraph starts after leaving a gap of 0.5inches. This is an example of
text-indentation. This is an example of text-indentation. This is an example of text-
indentation.
• text-align : left (the default), center, right, or justify)
text-align : left
• float :
 This property specifies whether an element should float or not.
Elements after a floating element will flow around it.
 Values are :left, right, and none (the default)
 Eg Image floating on the right. Paragraph flows around the image.
(next slide)
Alignment of Text (continued)
<img src="c2.jpg" height=200 width=200 style = "float: right" />
<p> This is a picture of Cessna 210. the 210 is a flagship
single-engine…………………………………………………….</p>
List properties
• Unordered lists
– list-style-type property used. Set it on either the <ul> or <li> tag
• On <ul>, it applies to all list items
• On <li>, list-style-type applies to just that item
– list-style-type: disc (default), square, circle

<h3> Some Common Single-Engine Aircraft </h3>


<ul style = "list-style-type: square">
<li> Cessna Skyhawk </li>
<li> Beechcraft Bonanza </li>
<li> Piper Cherokee </li>
</ul>

<h3> Some Common Single-Engine Aircraft </h3>


<ul>
<li style = "list-style-type: disc">
Cessna Skyhawk </li>
<li style = "list-style-type: square">
Beechcraft Bonanza </li>
<li style = "list-style-type: circle">
Piper Cherokee </li>
</ul>
List properties

– Could use an image for the bullets in an unordered list

<li style = "list-style-image: url(fish.jpg)">

Example :
<style type="text/css">
ul { list-style-image:url(fish.jpg); color:blue; font-weight:bold; font-style: italic; }
</style> </head>
<body>
<ul>There are 2 varieties of food
<li>cooked food</li>
<li>uncooked food</li>
</ul>
</body>
Possible sequencing values for ordered lists
Sequence Types Example
The <span> and <div> tags

• Font properties apply to whole elements, which are often too large
• A new tag <span> tag, is used to define an element in the content of a larger element
.

Ex1: <p> Now is the <span> best time </span> ever! </p>
span {color : red;font-size:24pt} //Defined in the head section
Ex 2:
<style type = "text/css">
.bigred {font-size: 24pt; font-family: Ariel; color: red}
</style>
<p> Now is the <span class = "bigred"> best time </span>
ever!</p>
<div> Tag
<div> : defines a division or section in a document

<p> This is normal paragraph></p> This is normal paragraph

<div style="color:red"> This is red line


<p>This is red line</p> This is another red line..........
<p>This is another red line……..</p> Heading
<h1> Heading </h1>
</div>
This is normal line again

<p> This is normal line again></p>


<div> Tag
A section of three paragraphs for which you want some
particular style
<div> Tag contd….

<div style=“border-style:solid;
padding:60px">
<p>This is............ text</p>
<p>This is sample.........text</p>
<p>This is sample......... text</p>
</div>
The <span> and <div> tags (continued)

• The <span> tag is similar to other HTML tags, they


can be nested and they have id and class
attributes

• Span is a inline tag and div is a block tag.


Eg. Span could be for few words in a paragraph
while div would be for several paragraphs.
The Box Model
• Every element on a Web Page has a border property
– Border controls whether the element has a border and if so, the style
of the border

– border-style values: none, dotted, dashed, and double

– border-width – thin, medium (default), thick, or pixels


Border width can be specified for any of the four borders (e.g.,
border-top-width)

– border-color – any color Border color can be specified for any of


the four borders (e.g., border-top-color)
The Box Model
Box Model Example (Paragraph)
Borders
• border-style: solid
– Values : solid, dotted, dashed, double,none
– By default most of the elements have borders specified as none
• border-width : thick , thin, medium, number with unit
• The four side of elements width can be set using
– border-top-width
– border-bottom-width
– border-left-width
– border-right-width
• border-color :
– Black by default
• Four side colors can be set using
– border-top-color
– border-bottom-color
– border-left-color
– border-right-color
Table Border Example
<style type = "text/css">
table {border-top-width: medium;
border-top-style: dotted;
border-top-color: red;
border-bottom-width: thick;
border-bottom-style: dashed;
border-bottom-color: blue;
}
</style>
</head> <body>
<table border = "5">
<tr>
<th> </th>
<th> Apple </th>
</tr>
<tr>
<th> Breakfast </th>
<td> 0 </td>
</tr>
<tr>
<th> Lunch </th>
<td> 1 </td>
</tr>
</table>
Margins & Padding

• Padding- is the space between the content


of the element and its border
• Margin – is the space between the border
of an element and the element’s
neighbour

• Any background given extends behinds


the padding

• margin:num unit
– margin-left
– margin-right
– margin-top
– margin-bottom
• padding:num unit
– padding –left
– padding-right
– padding-top
– padding-bottom
Space Between Buttons
<style type = "text/css">
input {margin:0.1in ; padding : 0.2in }
</style>
</head> Click Reset
<body>
<input type="button" value="Click" > Margin

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


</body>
Margins with Images
• Margin – the space between the border of an element and its neighbor element
• The margins around an element can be set with margin-left, etc. - just assign them a
length value
<img src = "c210.jpg " style = "float: right;
margin-left: 0.35in;
margin-bottom: 0.35in" />
Background Image
background-image:url(plane.jpg)
• Repetition can be controlled

• background-repeat:repeat(default),
no-repeat, repeat-x, repeat-y

• background-position : top, center,


bottom, left, right,top left or bottom
right
Background Image
<style type=“text/css”>
body {
background-image:url(plane.jpg);
background-position: center top;
background-repeat : no-repeat ;
background-size : 500px 400px
}
</style>
Display of back_image.html
Conflict Resolution
When two or more styles apply to the same tag there are certain rules for deciding which
style applies
• Different levels
– Inline style sheets have precedence over document style sheets
– Document style sheets have precedence over external style sheets

• Within the same level there can be conflicts


– A tag may be used twice as a selector
(whatever is nearer to the tag will be applied)
Eg. h3 {color:red;}
body h3 {color:blue;} // Higher Precedence

• Sources of Style sheets : can be different


– author-origin : The author of a document may specify styles
– User-agent-origin (Browsers can have default settings) Least Precedence
– user-origin :The user, through browser settings, may specify styles
• Individual properties can be specified as important
eg. p.special {font-style: italic!important; font-size:14; }
Precedence Rules
• From highest to lowest
1. Important declarations with user origin
2. Important declarations with author origin
3. Normal declarations with author origin
4. Normal declarations with user origin
5. Any declarations with browser (or other user agent) origin
- User overrides the author only if the declarations are marked important
- The browser declarations are least important;

• After this if still conflict occurs then precedence order is


1. id selectors
2. class and pseudo class selectors
3. contextual selectors
4. general selectors
5. universal selectors

• Again if a conflict occurs then property near to the tag is applied


• This whole sorting process is called as cascade and that‟s the reason style sheets are called as CSS.
• If you want to specify how web pages will display, you can use your own
style sheet.
• A style sheet is a template that defines the fonts and visual styles that are
used on a webpage. Using your own style sheet is helpful if the original
design of a webpage doesn't work well for accessibility reasons.
• To pick a style sheet -
- In Internet Explorer, click the Tools button, and then click Internet
Options.
- Click the General tab, and then click Accessibility.
- In the Accessibility dialog box, select the Format documents using my
style sheet
check box.
- Type the name of the style sheet you want to use, or click Browse and
navigate to it.
- Click OK twice to finish.
MODULE-4
Dynamic Documents with JavaScript

Informally, a dynamic XHTML document is an XHTML document that, in some way, can be
changed while it is being displayed by a browser. The most common client-side approach to
providing dynamic documents is to use JavaScript to manipulate the objects of the Document
Object Model (DOM) of the displayed document. Changes to documents can occur when they
are explicitly requested by user interactions, at regular timed intervals, or when browser events
occur. XHTML elements can be initially positioned at any given location on the browser display.
If they’re positioned in a specific way, elements can be dynamically moved to new positions on
the display. Elements can be made to disappear and reappear. The colors of the background and
the foreground (the elements) of a document can be changed. The font, font size, and font style
of displayed text can be changed. Even the content of an element can be changed. Overlapping
elements in a document can be positioned in a specific top-to-bottom stacking order, and their
stacking order can be dynamically changed. The position of the mouse cursor on the browser
display can be determined when a mouse button is clicked. Elements can be made to move
slowly around the display screen. Finally, elements can be defined to allow the user to drag and
drop them anywhere in the display window. This chapter discusses the JavaScript code that can
create all of these effects.

1.Introduction
Dynamic XHTML is not a new markup language. It is a collection of technologies that allows
dynamic changes to documents defined with XHTML. Specifically, a dynamic XHTML
document is an XHTML document whose tag attributes, tag contents, or element style properties
can be changed by user interaction or the occurrence of a browser event after the document has
been, and is still being, displayed. Such changes can be made with an embedded script that
accesses the elements of the document as objects in the associated DOM structure.This chapter
discusses user interactions through XHTML documents using client-side JavaScript.

2. what are thePositioning elements in html?


It provides the means not only to position any element anywhere in the display of a document,
but also to move an element to a new position in the display dynamically, using JavaScript to
change the positioning style properties of the element. These style properties, which are
appropriately named left and top, dictate the distance from the left and top of some reference
point to where the element is to appear. Another style property, position, interacts with left and
top to provide a higher level of control of placement and movement of elements. The position
property has three possible values: absolute, relative, and static.

2.1 Absolute Positioning


The absolute value is specified for position when the element is to be placed at a specific place in
the document display without regard to the positions of other elements. For example, if a
paragraph of text is to appear 100 pixels from the left edge and 200 pixels from the top of the
display window, the following element could be used:
<p style=”position: absolute; left:100px; top:200px”>
--------text--------
</p>
One use of absolute positioning is to superimpose special text over a paragraph of ordinary text
to create an effect similar to a watermark on paper. A larger italicized font, in a light-gray color
and with space between the letters, could be used for the special text, allowing both the ordinary
text and the special text to be legible. The XHTML document that follows provides an example
that implements this effect.

2.2 Relative Positioning


An element that has the position property set to relative, but does not specify top and left
property values, is placed in the document as if the position attribute were not set at all.
However, such an element can be moved later. If the top and left properties are given values,
they displace the element by the specified amount from the position where it would have been
placed (if top and left had not been set).
Relative positioning can be used for a variety of special effects in placing elements. For example,
it can be used to create superscripts and subscripts by placing the values to be raised or lowered
in <span> tags and displacing them from their regular positions. In the next example, a line of
text is set in a normal font style in 24-point size. Embedded in the line is one word that is set in
italic, 48-point, red font. Normally, the bottom of the special word would align with the bottom
of the rest of the line. In this case, the special word is to be vertically centered in the line, so its
position property is set to relative and its top property is set to 10 pixels, which lowers it by that
amount relative to the surrounding text. The XHTML document to specify this, which is named
relPos.html, is as follows:
Output:

2.3 Static Positioning


The default value for the position property is static. A statically positioned element is placed in
the document as if it had the position value of relative but no values for top or left were given.
The difference is that a statically positioned element cannot have its top or left properties initially
set or changed later. Therefore, a statically placed element cannot be displaced from its normal
position and cannot be moved from that position later.

3. How the Elements are moved in the dynamic documents?


Moving an element is simple: Changing the top or left property values causes the element to
move on the display. If its position is set to absolute, the element moves to the new values of top
and left; if its position is set to relative, it moves from its original position by distances given by
the new values of top and left. In the next example, an image is absolutely positioned in the
display. The document includes two text boxes, labeled x coordinate and y coordinate,
respectively. The user can enter new values for the left and top properties of the image in these
boxes. When the button labeled Move It is pressed, the values of the left and top properties of the
image are changed to the given values, and the element is moved to its new position. A
JavaScript function, stored in a separate file, is used to change the values of left and top in this
example. Although it is not necessary here, the id of the element to be moved is sent to the
function that does the moving, just to illustrate that the function could be used on any number of
different elements. The values of the two text boxes are also sent to the function as parameters.
The actual parameter values are the DOM addresses of the text boxes, with the value attribute
attached, which provides the complete DOM addresses of the text box values. Notice that style is
attached to the DOM address of the image to be moved because top and left are style properties.
Because the input top and left values from the text boxes are just string representations of
numbers, but the top and left properties must end with some unit abbreviation, the event handler
catenates “px” to each value before assigning it to the top and left properties. This document,
called mover.html, and the associated JavaScript file, mover.js, are as follows:
Output:
1. Before pressing the move button

2. After pressing the move button


4. Discuss the concept of Element Visibility in html?
Document elements can be specified to be visible or hidden with the value of their visibility
property. The two possible values for visibility are, quite naturally, visible and hidden. The
appearance or disappearance of an element can be controlled by the user through a widget. The
following example displays an image and allows the user to toggle a button, causing the image to
appear and not appear in the document display (once again, the event handler is in a separate
file):
5. how to change the Colors and Fonts Dynamically in html?
The background and foreground colors of the document display can be dynamically changed, as
can the font properties of the text.

1. Changing Colors
Dynamic changes to colors are relatively simple. In the next example, the user is presented with
two text boxes into which color specifications can be typed—one for the document background
color and one for the foreground color. The colors can be specified in any of the three ways that
color properties can be given in CSS. A JavaScript function that is called whenever one of the
text boxes is changed makes the change in the document’s appropriate color property: back-
groundColor or color. The first of the two parameters to the function specifies whether the new
color is for the background or foreground; the second specifies the new color. The new color is
the value property of the text box that was changed by the user. In this example, the calls to the
handler functions are in the XHTML text box elements. This approach allows a simple way to
reference the element’s DOM address. The JavaScript this variable in this situation is a reference
to the object that represents the element in which it is referenced. A reference to such an object is
its DOM address. Therefore, in a text element, the value of this is the DOM address of the text
element. So, in the example, this.value is used as an actual parameter to the handler function.
Because the call is in an input element, this.value is the DOM address of the value of the input
element. This document, called dynColors.html, and the associated JavaScript file are as follows:
5.2 Changing Fonts
The property that is used to change the font property is fontSize, fontStyle. In the example, the
only element is a sentence with an embedded special word. The special word is the content of a
span element, so its attributes can be changed. The foreground color for the document is the
default black. The word is presented in blue. When the mouse cursor is placed over the word, its
color changes to red, its font style changes to italic, and its size changes from 16 point to 24
point. When the cursor is moved off the word, it reverts to its original style. Here is this
document, called dynFont.html:

Output:
1. Display of dynFont.html with the mouse cursor not over the word

2. Display of dynFont.html with the mouse cursor over the word


6. how to change the content in html Dynamically, illustrate with an
example?
This part investigates changing the content of XHTML elements. The content of an element is
accessed through the value property of its associated Java-Script object. So, changing the content
of an element is not essentially different from changing other properties of the element. We now
develop an example that illustrates one use of dynamic content. Assistance to a browser user
filling out a form can be provided with an associated text area, often called a help box. The
content of the help box can change, depending on the placement of the mouse cursor. When the
cursor is placed over a particular input field, the help box can display advice on how the field is
to be filled in. When the cursor is moved away from an input field, the help box content can be
changed to simply indicate that assistance is available. In the next example, an array of messages
that can be displayed in the help box is defined in JavaScript. When the mouse cursor is placed
over an input field, the mouseover event is used to call a handler function that changes the help
box content to the appropriate value (the one associated with the input field). The appropriate
value is specified with a parameter sent to the handler function. The mouseout event is used to
trigger the change of the content of the help box back to the “standard” value. Following is the
markup document and associated JavaScript file:
Output:
Display of dynValue.html with the cursor over User ID
7. Stacking Elements
The top and left properties allow the placement of an element anywhere in the two dimensions of
the display of a document. Although the display is restricted to two physical dimensions, the
effect of a third dimension is possible through the simple concept of stacked elements, such as
that used to stack windows in graphical user interfaces. Although multiple elements can occupy
the same space in the document, one is considered to be on top and is displayed. The top element
hides the parts of the lower elements on which it is superimposed. The placement of elements in
this third dimension is controlled by the z-index attribute of the element. An element whose z-
index is greater than that of an element in the same space will be displayed over the other
element, effectively hiding the element with the smaller z-index value. The JavaScript style
property associated with the z-index attribute is zIndex. In the example, three images are placed
on the display so that they overlap. In the XHTML description of this situation, each image tag
includes an onclick attribute, which is used to trigger the execution of a JavaScript handler
function. First the function defines DOM addresses for the last top element and the new top
element. Then the function sets the zIndex value of the two elements so that the old top element
has a value of 0 and the new top element has the value 10, effectively putting it at the top. The
script keeps track of which image is currently on top with the global variable top, which is
changed every time a new element is moved to the top with the toTop function. Note that the
zIndex value, as is the case with other properties, is a string. This document, called
stacking.html, and the associated JavaScript file are as follows:
Output:
1. The initial display of stacking.html (photographs courtesy of Cessna Aircraft Company)

2. The display of stacking.html after clicking the second image (photographs courtesy of
Cessna Aircraft Company)
3.The display of stacking.html after clicking the bottom image (photographs courtesy of Cessna
Aircraft Company)

8. Draggind and Dropping Elements


HTML Drag and Drop interfaces enable applications to use drag and drop features in Firefox and
other browsers. For example, with these features, the user can select draggable elements with a
mouse, drag the elements to a droppable element, and drop those elements by releasing the mouse
button. A translucent representation of the draggable elements follows the mouse pointer during
the drag operation.
For web sites, extensions, and XUL applications, you can customize the types of elements that
can become draggable elements, and the type of feedback the draggable elements produce, and
the droppable elements.
Drag Events
HTML drag and drop uses the DOM event model and drag events inherited from mouse events. A typical
drag operation begins when a user selects a draggable element with a mouse, moves the mouse to
a droppable element and then releases the mouse. During the operations, several event types are
fired and some event types might be fired many times.
All of the drag event types have an associated global event handler. Each drag event type and drag
global attribute has a reference document that describes the event. The following table provides a
short description of the event types and a link to the reference documents.

On Event
Event Description
Handler

drag ondrag Fired when an element or text selection is being dragged.

Fired when a drag operation is being ended (for example, by releasing a mouse butt
dragend ondragend
on or hitting the escape key.

Fired when a dragged element or text selection enters a valid drop target. (See
dragenter ondragenter
Specifying Drop Targets.)

dragexit ondragexit Fired when an element is no longer the drag operation's immediate selection target.

dragleave ondragleave Fired when a dragged element or text selection leaves a valid drop target.

Fired when an element or text selection is being dragged over a valid


dragover ondragover
drop target (every few hundred milliseconds).

dragstart ondragstart Fired when the user starts dragging an element or text selection.

Fired when an element or text selection is dropped on


drop ondrop
a valid drop targets.

Example:
To make an element draggable requires adding the draggable attribute plus the ondragstart global
event handler, as shown in the following code sample:

functiondragstart_handler(ev){
console.log("dragStart");
// Add the target element's id to the data transfer object
ev. dataTransfer.setData("text/plain", ev.target.id);
}

<body>
<p id="p1" draggable="true" ondragstart="dragstart_handler(event);">This element is draggable.</p>
</body>
Dropping:
The handler for the drop event is free to process the drag data in an application specific way.
Typically, an application will use the getData() method to retrieve drag items and process them
accordingly. Additionally, application semantics may differ depending on the value of
the dropEffect and/or the state of modifier keys.
The following example shows a drop handler getting the source element's id from the drag data
and then using the id to move the source element to the drop element.

functiondragstart_handler(ev){
// Add the target element's id to the data transfer object
ev. dataTransfer.setData("text/plain", ev.target.id);
ev. dropEffect ="move";
}
functiondragover_handler(ev){
ev. preventDefault ();
// Set the dropEffect to move
ev. dataTransfer.dropEffect ="move"
}
functiondrop_handler(ev){
ev. preventDefault ();
// Get the id of the target and add the moved element to the target's DOM
var data = ev. dataTransfer.getData("text/plain");
ev. target. appendChild (document. getElementById(data));
}
<body>
<p id="p1" draggable="true" ondragstart="dragstart_handler(event);">This element is draggable.</p>
<div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">Drop Zone</div>
</body>

Vous aimerez peut-être aussi