Académique Documents
Professionnel Documents
Culture Documents
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?
• 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.
</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>
</body> </body>
</html> </html>
Line Breaks
<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.
<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>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>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>
• <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>
</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
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>
</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}
/* visited link */
a:visited {
color: green;
}
/* selected link */
a:active {
color: blue;
}
</style>
</head>
<body>
</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 −
</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>
</style>
</head>
<body>
<ul class="b">
<li>Coffee</li>
<li>Tea</li>
<li>Coca Cola</li>
</ul>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<style>
<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>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>
h1 { color: #00ff00;}
<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>
</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>
</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>
<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>
</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>
</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>
<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
<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>
<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>
<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);
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>
<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>
</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>
<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>
<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
<!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>
<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
<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 }
var i = 0;
var len = cars.length;
var text = "";
</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";
</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:
</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>
<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>
<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>
• 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>
</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>
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>
<p id="demo"></p>
• JavaScript Object Constructors
<script> • My father is 50. My mother is 48.
// 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
<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.
=== Identical $x === $y Returns true if $x is equal to $y, and they are of the same type
!== Not identical $x !== $y Returns true if $x is not equal to $y, or they are not of the same type
<= 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;
} }
– <!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_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
• 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)
• Most web browsers do not use the IP address to locate Web sites and
individual pages. They use domain name addressing.
– 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
• Fully qualified domain name - the host name + all the domain names
Domain Name Conversion
• 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
• 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
• URL has 4 parts – Protocol, Domain Name, Path name, File name
Domain name
Path to Document
Uniform/Universal Resource Locator (URL)
• General form:
scheme://object-address
• 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>
– 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
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 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.
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
Submit
HTTP Request :
GET www.coffee.com/info/coffee.html ?
colour = dark & taste=malty HTTP/1.1
Request Phase
• General Form of request :
2. Header fields
Accept: text/html
Accept: text/plain
Accept-Language : en-us
3. Blank line
• Form:
1. Status line
2. Response header fields
3. Blank line
4. Response body
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
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
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
• HTML is defined with the use of the Standard Generalized Markup Language
(SGML)
• 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
• 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.
• Both classes and objects are Dynamic. So they can have different sets of
methods at different times
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 />
• -->
<!-- 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>
in Crete
The sleet
• 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
• 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
• 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.
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
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” />
• With multiple
Menus (continued)
</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)
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
<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.
<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
• 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)
• Example:
• 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.
- 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
<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
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
<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)
• 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
• background-repeat:repeat(default),
no-repeat, repeat-x, repeat-y
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.
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. 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)
On Event
Event Description
Handler
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.
dragstart ondragstart Fired when the user starts dragging an element or text selection.
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>