0% found this document useful (0 votes)
34 views525 pages

Awt Notes

The document provides an overview of the Internet's origins, starting from ARPAnet in the late 1960s to the establishment of the World Wide Web by Tim Berners-Lee in 1989. It discusses the technical aspects of the Internet, including IP addresses, domain names, and the HyperText Transfer Protocol (HTTP), as well as the evolution of HTML and XHTML. Additionally, it covers web browsers, servers, and the tools available for web programming.

Uploaded by

sanjana.kirodian
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views525 pages

Awt Notes

The document provides an overview of the Internet's origins, starting from ARPAnet in the late 1960s to the establishment of the World Wide Web by Tim Berners-Lee in 1989. It discusses the technical aspects of the Internet, including IP addresses, domain names, and the HyperText Transfer Protocol (HTTP), as well as the evolution of HTML and XHTML. Additionally, it covers web browsers, servers, and the tools available for web programming.

Uploaded by

sanjana.kirodian
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 525

1.

1 A Brief Intro to the Internet


- Origins
- ARPAnet - late 1960s and early 1970s
- Network reliability
- For ARPA-funded research organizations

- BITnet, CSnet - late 1970s & early 1980s


- email and file transfer for other institutions

- NSFnet - 1986
- Originally for non-DOD funded places
- Initially connected five supercomputer centers
- By 1990, it had replaced ARPAnet for non-
military uses
- Soon became the network for all (by the early
1990s)

- NSFnet eventually became known as the Internet

- What the Internet is:

- A world-wide network of computer networks

- At the lowest level, since 1982, all connections


use TCP/IP

- TCP/IP hides the differences among devices


connected to the Internet

Chapter 1 © 2005 by Addison Wesley Longman, Inc. 1


1.1 A Brief Intro to the Internet (continued)
- Internet Protocol (IP) Addresses
- Every node has a unique numeric address

- Form: 32-bit binary number


- New standard, IPv6, has 128 bits (1998)

- Organizations are assigned groups of IPs for


their computers

- Domain names
- Form: host-name.domain-names

- First domain is the smallest; last is the largest

- Last domain specifies the type of organization

- Fully qualified domain name - the host name


and all of the domain names

- DNS servers - convert fully qualified domain


names to IPs

- Problem: By the mid-1980s, several different


protocols had been invented and were being used
on the Internet, all with different user interfaces
(Telnet, FTP, Usenet, mailto

Chapter 1 © 2005 by Addison Wesley Longman, Inc. 2


1.2 The World-Wide Web
- A possible solution to the proliferation of different
protocols being used on the Internet

- Origins
- Tim Berners-Lee at CERN proposed the Web
in 1989
- Purpose: to allow scientists to have access
to many databases of scientific work through
their own computers

- Document form: hypertext

- Pages? Documents? Resources?


- We’ll call them documents

- Hypermedia – more than just text – images,


sound, etc.

- Web or Internet?
- The Web uses one of the protocols, http, that
runs on the Internet--there are several others
(telnet, mailto, etc.)

Chapter 1 © 2005 by Addison Wesley Longman, Inc. 3


1.3 Web Browsers
- Mosaic - NCSA (Univ. of Illinois), in early 1993
- First to use a GUI, led to explosion of Web use
- Initially for X-Windows, under UNIX, but was
ported to other platforms by late 1993

- Browsers are clients - always initiate, servers


react (although sometimes servers require
responses)

- Most requests are for existing documents, using


HyperText Transfer Protocol (HTTP)

- But some requests are for program execution,


with the output being returned as a document

1.4 Web Servers


- Provide responses to browser requests, either
existing documents or dynamically built
documents

- Browser-server connection is now maintained


through more than one request-response cycle

Chapter 1 © 2005 by Addison Wesley Longman, Inc. 4


1.4 Web Servers (continued)
- All communications between browsers and
servers use Hypertext Transfer Protocol (HTTP)

- Web servers run as background processes in the


operating system

- Monitor a communications port on the host,


accepting HTTP messages when they appear

- All current Web servers came from either


1. The original from CERN
2. The second one, from NCSA

- Web servers have two main directories:

1. Document root (servable documents)


2. Server root (server system software)

- Document root is accessed indirectly by clients

- Its actual location is set by the server


configuration file
- Requests are mapped to the actual location

- Virtual document trees

- Virtual hosts

Chapter 1 © 2005 by Addison Wesley Longman, Inc. 5


1.4 Web Servers (continued)
- Proxy servers

- Web servers now support other Internet protocols

- Apache (open source, fast, reliable)

- Directives (operation control):

ServerName

ServerRoot

ServerAdmin,

DocumentRoot

Alias

Redirect

DirectoryIndex

UserDir

- IIS

- Operation is maintained through a program with


a GUI interface

Chapter 1 © 2005 by Addison Wesley Longman, Inc. 6


1.5 URLs
- General form:

scheme:object-address

- The scheme is often a communications protocol,


such as telnet or ftp

- For the http protocol, the object-address is:


fully qualified domain name/doc path

- For the file protocol, only the doc path is needed

- Host name may include a port number, as in


zeppo:80 (80 is the default, so this is silly)

- URLs cannot include spaces or any of a collection


of other special characters (semicolons, colons, ...)

- The doc path may be abbreviated as a partial path


- The rest is furnished by the server configuration

- If the doc path ends with a slash, it means it is a


directory

Chapter 1 © 2005 by Addison Wesley Longman, Inc. 7


1.6 Multipurpose Internet Mail
Extensions (MIME)
- Originally developed for email

- Used to specify to the browser the form of a file


returned by the server (attached by the server to
the beginning of the document)

- Type specifications
- Form:
type/subtype

- Examples: text/plain, text/html, image/gif,


image/jpeg

- Server gets type from the requested file name’s


suffix (.html implies text/html)

- Browser gets the type explicitly from the server

- Experimental types

- Subtype begins with x-


e.g., video/x-msvideo

- Experimental types require the server to send


a helper application or plug-in so the browser
can deal with the file

Chapter 1 © 2005 by Addison Wesley Longman, Inc. 8


1.7 The HyperText Transfer Protocol
- The protocol used by ALL Web communications

- Request Phase

- Form:
HTTP method domain part of URL HTTP ver.
Header fields
blank line
Message body

- An example of the first line of a request:

GET /cs.uccp.edu/degrees.html HTTP/1.1

- Most commonly used methods:

GET - Fetch a document


POST - Execute the document, using the data in
body
HEAD - Fetch just the header of the document
PUT - Store a new document on the server
DELETE - Remove a document from the server

Chapter 1 © 2005 by Addison Wesley Longman, Inc. 9


1.7 The HyperText Transfer Protocol
(continued)

- Four categories of header fields:

General, request, response, & entity

- Common request fields:

Accept: text/plain

Accept: text/*

If-Modified_since: date

- Common response fields:

Content-length: 488

Content-type: text/html

-Can communicate with HTTP without a browser

> telnet blanca.uccs.edu http


GET /respond.html HTTP/1.1
Host: blanca.uccs.edu

Chapter 1 © 2005 by Addison Wesley Longman, Inc. 10


1.7 The HyperText Transfer Protocol
(continued)

- Response Phase

- Form:
Status line
Response header fields
blank line
Response body

- Status line format:


HTTP version status code explanation

- Example: HTTP/1.1 200 OK

(Current version is 1.1)

- Status code is a three-digit number; first digit


specifies the general status

1 => Informational
2 => Success
3 => Redirection
4 => Client error
5 => Server error

- The header field, Content-type, is required

Chapter 1 © 2005 by Addison Wesley Longman, Inc. 11


1.7 The HyperText Transfer Protocol
(continued)

- An example of a complete response header:

HTTP/1.1 200 OK
Date: Tues, 18 May 2004 16:45:13 GMT
Server: Apache (Red-Hat/Linux)
Last-modified: Tues, 18 May 2004 16:38:38 GMT
Etag: "841fb-4b-3d1a0179"
Accept-ranges: bytes
Content-length: 364
Connection: close
Content-type: text/html, charset=ISO-8859-1

- Both request headers and response headers must


be followed by a blank line

Chapter 1 © 2005 by Addison Wesley Longman, Inc. 12


1.8 The Web Programmer’s Toolbox
- XHTML

- To describe the general form and layout of


documents

- An XHTML document is a mix of content and


controls

- Controls are tags and their attributes

- Tags often delimit content and specify


something about how the content should be
arranged in the document

- Attributes provide additional information

about the content of a tag


- Tools for creating XHTML documents

- XHTML editors - make document creation easier


- Shortcuts to typing tag names, spell-checker,

- WYSIWYG XHTML editors


- Need not know XHTML to create XHTML
documents

Chapter 1 © 2005 by Addison Wesley Longman, Inc. 13


1.8 The Web Programmer’s Toolbox
(continued)

- Plug ins

- Integrated into tools like word processors,


effectively converting them to WYSIWYG
XHTML editors

- Filters

- Convert documents in other formats to XHTML

- Advantages of both filters and plug-ins:

- Existing documents produced with other tools


can be converted to XHTML documents

- Use a tool you already know to produce XHTML

- Disadvantages of both filters and plug-ins:

- XHTML output of both is not perfect - must be


fine tuned

- XHTML may be non-standard

- You have two versions of the document, which


are difficult to synchronize

Chapter 1 © 2005 by Addison Wesley Longman, Inc. 14


1.8 The Web Programmer’s Toolbox
(continued)

- XML(

- A meta-markup language

- Used to create a new markup language for a


particular purpose or area

- Because the tags are designed for a specific


area, they can be meaningful

- No presentation details

- A simple and universal way of representing data


of any textual kind

- JavaScript

- A client-side HTML-embedded scripting


language

- Only related to Java through syntax

- Dynamically typed and not object-oriented

- Provides a way to access elements of HTML


documents and dynamically change them

Chapter 1 © 2005 by Addison Wesley Longman, Inc. 15


1.8 The Web Programmer’s Toolbox
(continued)

- Java

- General purpose object-oriented programming


language

- Based on C++, but simpler and safer

- Our focus is on applets, servlets, and JSP

- Perl

- Provides server-side computation for


HTML documents, through CGI

- Perl is good for CGI programming because:

- Direct access to operating systems functions

- Powerful character string pattern-matching


operations

- Access to database systems

- Perl is highly platform independent, and has


been ported to all common platforms

- Perl is not just for CGI

Chapter 1 © 2005 by Addison Wesley Longman, Inc. 16


1.8 The Web Programmer’s Toolbox
(continued)

- PHP

- A server-side scripting language

- An alternative to CGI

- Similar to JavaScript

- Great for form processing and database access


through the Web

Chapter 1 © 2005 by Addison Wesley Longman, Inc. 17


2.1 Origins and Evolution of HTML
- HTML was defined with SGML

- 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

Chapter 2 © 2005 by Addison Wesley Longman, Inc. 1


2.1 Origins and Evolution of HTML
(continued)
- 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

2.2 Basic Syntax


- Elements are defined by tags (markers)

- Tag format:
- Opening tag: <name>
- Closing tag: </name>

- The opening tag and its closing tag together


specify a container for the content they enclose

Chapter 2 © 2005 by Addison Wesley Longman, Inc. 2


2.2 Basic Syntax (continued)
- Not all tags have content
- If a tag has no content, its form is <name />

- The container and its content together are called


an element

- If a tag has attributes, they appear between its


name and the right bracket of the opening tag

- Comment form: <!-- … -->

- Browsers ignore comments, unrecognizable tags,


line breaks, multiple spaces, and tabs

- Tags are suggestions to the browser, even if they


are recognized by the browser

Chapter 2 © 2005 by Addison Wesley Longman, Inc. 3


2.3 Standard HTML Document Structure
- Every XHTML document must begin with:

<?xml version = ″1.0″?>


<!DOCTYPE html PUBLIC ″-//w3c//DTD XHTML 1.1//EN″
http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd>

- <html>, <head>, <title>, and <body> are required


in every document

- The whole document must have <html> as its root

- html must have the xmlns attribute:

<html xmlns = ″http://www.w3.org/1999/xhtml″>

- A document consists of a head and a body

- The <title> tag is used to give the document a title,


which is normally displayed in the browser’s
window title bar (at the top of the display)

- Prior to XHTML 1.1, a document could have either


a body or a frameset

Chapter 2 © 2005 by Addison Wesley Longman, Inc. 4


2.4 Basic Text Markup
- Text is normally placed in paragraph elements

- Paragraph Elements

- The <p> tag breaks the current line and inserts a


blank line - the new line gets the beginning of the
content of the paragraph

- The browser puts as many words of the


paragraph’s content as will fit in each line

<?xml version = ″1.0″?>


<!DOCTYPE html PUBLIC ″-//w3c//DTD XHTML 1.1//EN″
http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd>
<!-- greet.hmtl
A trivial document
-->
<html xmlns = ″http://www.w3.org/1999/xhtml″>
<head> <title> Our first document </title>
</head>
<body>
<p>
Greetings from your Webmaster!
</p>
</body>
</html>

Chapter 2 © 2005 by Addison Wesley Longman, Inc. 5


2.4 Basic Text Markup (continued)
- W3C HTML Validation Service
http://validator.w3.org/file-upload.html

- Line breaks

- The effect of the <br /> tag is the same as that


of <p>, except for the blank line
- No closing tag!

- Example of paragraphs and line breaks

On the plains of hesitation <p> bleach the


bones of countless millions </p> <br />
who, at the dawn of victory <br /> sat down
to wait, and waiting, died.

- Typical display of this text:

On the plains of hesitation

bleach the bones of countless millions


who, at the dawn of victory
sat down to wait, and waiting, died.

Chapter 2 © 2005 by Addison Wesley Longman, Inc. 6


2.4 Basic Text Markup (continued)
- Headings

- Six sizes, 1 - 6, specified with <h1> to <h6>

- 1, 2, and 3 use font sizes that are larger than the


default font size

- 4 uses the default size

- 5 and 6 use smaller font sizes

<!-- headings.html
An example to illustrate headings
-->
<html xmlns = ″http://www.w3.org/1999/xhtml″>
<head> <title> Headings </title>
</head>
<body>
<h1> Aidan’s Airplanes (h1) </h1>
<h2> The best in used airplanes (h2) </h2>
<h3> "We’ve got them by the hangarful" (h3)
</h3>
<h4> We’re the guys to see for a good used
airplane (h4) </h4>
<h5> We offer great prices on great planes
(h5) </h5>
<h6> No returns, no guarantees, no refunds,
all sales are final (h6) </h6>
</body>
</html>

Chapter 2 © 2005 by Addison Wesley Longman, Inc. 7


2.4 Basic Text Markup (continued)

- Blockquotes

- Content of <blockquote>

- To set a block of text off from the normal flow and


appearance of text

- Browsers often indent, and sometimes italicize

- Font Styles and Sizes (can be nested)

- Boldface - <b>
- Italics - <i>
- Larger - <big>
- Smaller - <small>
- Monospace - <tt>

Chapter 2 © 2005 by Addison Wesley Longman, Inc. 8


2.4 Basic Text Markup (continued)
The <big> sleet <big> in <big> <i> Crete
</i><br /> lies </big> completely </big>
in </big> the street

The sleet in Crete


lies completely in the street
- These tags are not affected if they appear in the
content of a <blockquote>, unless there is a
conflict (e.g., italics)

- Superscripts and subscripts

- Subscripts with <sub>


- Superscripts with <sup>

Example: x<sub>2</sub><sup>3</sup>

Display: x23

- Inline versus block elements

- Block elements CANNOT be nested in inline


elements

Chapter 2 © 2005 by Addison Wesley Longman, Inc. 9


2.4 Basic Text Markup (continued)
- All of this font size and font style stuff can be
done with style sheets, but these tags are not
yet deprecated

- Character Entities

Char. Entity Meaning


& &amp; Ampersand
< &lt; Less than
> &gt; Greater than
" &quot; Double quote
' &apos; Single quote
¼ &frac14; One quarter
½ &frac12; One half
¾ &frac34; Three quarters
 &deg; Degree
(space) &nbsp; Non-breaking space

- Horizontal rules
- <hr /> draws a line across the display, after a
line break

- The meta element (for search engines)


Used to provide additional information about a
document, with attributes, not content

Chapter 2 © 2005 by Addison Wesley Longman, Inc. 10


2.5 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

- The alt attribute is required by XHTML


- Purposes:
1. Non-graphical browsers
2. Browsers with images turned off

<img src = "comets.jpg"


alt = "Picture of comets" />

- The <img> tag has 30 different attributes, including


width and height (in pixels)

- Portable Network Graphics (PNG)


- Relatively new
- Should eventually replace both gif and jpeg

Chapter 2 © 2005 by Addison Wesley Longman, Inc. 11


2.5 Images (continued)

<!-- image.html
An example to illustrate an image
-->
<html xmlns = ″http://www.w3.org/1999/xhtml″>
<head> <title> Images </title>
</head>
<body>
<h1> Aidan's Airplanes </h1>
<h2> The best in used airplanes </h2>
<h3> "We've got them by the hangarful"
</h3>
<h2> Special of the month </h2>
<p>
1960 Cessna 210 <br />
577 hours since major engine overhaul
<br />
1022 hours since prop overhaul
<br /><br />
<img src = "c210new.jpg"
alt = "Picture of a Cessna 210"/>
<br />
Buy this fine airplane today at a
remarkably low price <br />
Call 999-555-1111 today!
</p>
</body>
</html>

Chapter 2 © 2005 by Addison Wesley Longman, Inc. 12


2.5 Images (continued)

Chapter 2 © 2005 by Addison Wesley Longman, Inc. 13


2.6 Hypertext Links
- Hypertext is the essence of the Web!

- A link is specified with the href (hypertext


reference) attribute of <a> (the anchor tag)

- The content of <a> is the visual link in the


document

- If the target is a whole document (not the one in


which the link appears), the target need not be
specified in the target document as being the
target

- Note: Relative addressing of targets is easier to


maintain and more portable than absolute
addressing

Chapter 2 © 2005 by Addison Wesley Longman, Inc. 14


2.6 Hypertext Links (continued)
<!-- link.html
An example to illustrate a link
-->
<html xmlns = ″http://www.w3.org/1999/xhtml″>
<head> <title> Links </title>
</head>
<body>
<h1> Aidan's Airplanes </h1>
<h2> The best in used airplanes </h2>
<h3> "We've got them by the hangarful"
</h3>
<h2> Special of the month </h2>
<p>
1960 Cessna 210 <br />
<a href = "C210data.html">
Information on the Cessna 210 </a>
</p>
</body>
</html>

Chapter 2 © 2005 by Addison Wesley Longman, Inc. 15


2.6 Hypertext Links (continued)

Chapter 2 © 2005 by Addison Wesley Longman, Inc. 16


2.6 Hypertext Links (continued)
- 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">


What about 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

- Links can have images:


<a href = "c210data.html“>
<img src = "smallplane.jpg"
alt = "Small picture of an airplane " />
Info on C210 </a>

Chapter 2 © 2005 by Addison Wesley Longman, Inc. 17


2.7 Lists
- Unordered lists

- The list is the content of the <ul> tag

- List elements are the content of the <li> tag

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


<ul>
<li> Cessna Skyhawk </li>
<li> Beechcraft Bonanza </li>
<li> Piper Cherokee </li>
</ul>

- Ordered lists

- The list is the content of the <ol> tag

- Each item in the display is preceded by a


sequence value

Chapter 2 © 2005 by Addison Wesley Longman, Inc. 18


2.7 Lists (continued)

<h3> Cessna 210 Engine Starting Instructions


</h3>
<ol>
<li> Set mixture to rich </li>
<li> Set propeller to high RPM </li>
<li> Set ignition switch to "BOTH" </li>
<li> Set auxiliary fuel pump switch to
"LOW PRIME" </li>
<li> When fuel pressure reaches 2 to 2.5
PSI, push starter button </li>
</ol>

- Nested lists

- Any type list can be nested inside any type list

- The nested list must be in a list item

Chapter 2 © 2005 by Addison Wesley Longman, Inc. 19


2.7 Lists (continued)

- Definition lists (for glossaries, etc.)


- List is the content of the <dl> tag
- Terms being defined are the content of the
<dt> tag
- The definitions themselves are the content
of the <dd> tag

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


<dl >
<dt> 152 </dt>
<dd> Two-place trainer </dd>
<dt> 172 </dt>
<dd> Smaller four-place airplane </dd>
<dt> 182 </dt>
<dd> Larger four-place airplane </dd>
<dt> 210 </dt>
<dd> Six-place airplane - high performance
</dd>
</dl>

Chapter 2 © 2005 by Addison Wesley Longman, Inc. 20


2.8 Tables
- A table is a matrix of cells, each possibly having
content

- The cells can include almost any element

- Some cells have row or column labels and


some have data

- A table is specified as the content of a <table>


tag

- A border attribute in the <table> tag specifies a


border between the cells

- If border is set to "border", the browser’s


default width border is used

- The border attribute can be set to a number,


which will be the border width

- Without the border attribute, the table will have


no lines!

- Tables are given titles with the <caption> tag,


which can immediately follow <table>

Chapter 2 © 2005 by Addison Wesley Longman, Inc. 21


2.8 Tables (continued)
- Each row of a table is specified as the content of
a <tr> tag

- The row headings are specified as the content of


a <th> tag

- The contents of a data cell is specified as the


content of a <td> tag

<table border = "border">


<caption> Fruit Juice Drinks </caption>
<tr>
<th> </th>
<th> Apple </th>
<th> Orange </th>
<th> Screwdriver </th>
</tr>
<tr>
<th> Breakfast </th>
<td> 0 </td>
<td> 1 </td>
<td> 0 </td>
</tr>
<tr>
<th> Lunch </th>
<td> 1 </td>
<td> 0 </td>
<td> 0 </td>
</tr>
</table>

Chapter 2 © 2005 by Addison Wesley Longman, Inc. 22


2.8 Tables (continued)

- A table can have two levels of column labels

- If so, the colspan attribute must be set in the


<th> tag to specify that the label must span
some number of columns

<tr>
<th colspan = "3"> Fruit Juice Drinks </th>
</tr>
<tr>
<th> Orange </th>
<th> Apple </th>
<th> Screwdriver </th>
</tr>

Chapter 2 © 2005 by Addison Wesley Longman, Inc. 23


2.8 Tables (continued)
- If the rows have labels and there is a spanning
column label, the upper left corner must be
made larger, using rowspan

<table border = "border">


<tr>
<td rowspan = "2"> </td>
<th colspan = "3"> Fruit Juice Drinks
</th>
</tr>
<tr>
<th> Apple </th>
<th> Orange </th>
<th> Screwdriver </th>
</tr>

</table>

Chapter 2 © 2005 by Addison Wesley Longman, Inc. 24


2.8 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

Chapter 2 © 2005 by Addison Wesley Longman, Inc. 25


2.8 Tables (continued)

<table cellspacing = "50">


<tr>
<td> Colorado is a state of …
</td>
<td> South Dakota is somewhat…
</td>
</tr>
</table>

- Table Sections
- Header, body, and footer, which are the elements:
thead, tbody, and tfoot

- If a document has multiple tbody elements, they


are separated by thicker horizontal lines

Chapter 2 © 2005 by Addison Wesley Longman, Inc. 26


2.9 Forms
- A form is the usual way information is gotten from
a browser to a server

- HTML has tags to create a collection of objects that


implement this information gathering

- The objects are called widgets (e.g., radio buttons


and checkboxes)

- When the Submit button of a form is clicked, the


form’s values are sent to the server

- All of the widgets, or components of a form are


defined in the content of a <form> tag

- The only required attribute of <form> is action,


which specifies the URL of the application that is
to be called when the Submit button is clicked

action =
"http://www.cs.ucp.edu/cgi-bin/survey.pl"

- If the form has no action, the value of action is


the empty string

Chapter 2 © 2005 by Addison Wesley Longman, Inc. 27


2.9 Forms (continued)
- The method attribute of <form> specifies one of
the two possible techniques of transferring the
form data to the server, get and post

- get and post are discussed in Chapter 10

- Widgets

- Many are created with the <input> tag

- The type attribute of <input> specifies the kind of


widget being created

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

Chapter 2 © 2005 by Addison Wesley Longman, Inc. 28


2.9 Forms (continued)
- If you don’t want to allow the user to type more
characters than will fit, set maxlength, which
causes excess input to be ignored

<input type = "text" name = "Phone"


size = "12" >

2. Checkboxes - to collect multiple choice input

- Every checkbox requires a value attribute,


which is the widget’s value in the form data
when the checkbox is ‘checked’

- A checkbox that is not ‘checked’ contributes


no value to the form data

- By default, no checkbox is initially ‘checked’

- To initialize a checkbox to ‘checked’, the


checked attribute must be set to "checked"

Chapter 2 © 2005 by Addison Wesley Longman, Inc. 29


2.9 Forms (continued)
- Widgets (continued)

Grocery Checklist
<form action = "">
<p>
<input type = "checkbox" name ="groceries"
value = "milk" checked = "checked">
Milk
<input type = "checkbox" name ="groceries"
value = "bread">
Bread
<input type = "checkbox" name = "groceries"
value= "eggs">
Eggs
</p>
</form>

3. Radio Buttons - collections of checkboxes in


which only one button can be ‘checked’ at a
time
- Every button in a radio button group MUST
have the same name

Chapter 2 © 2005 by Addison Wesley Longman, Inc. 30


2.9 Forms (continued)
- Widgets (continued)

3. Radio Buttons (continued)

- If no button in a radio button group is


‘pressed’, the browser often ‘presses’ the
first one

Age Category
<form action = "">
<p>
<input type = "radio" name = "age"
value = "under20" checked = "checked"> 0-19
<input type = "radio" name = "age"
value = "20-35"> 20-35
<input type = "radio" name = "age"
value = "36-50"> 36-50
<input type = "radio" name = "age"
value = "over50"> Over 50
</p>
</form>

Chapter 2 © 2005 by Addison Wesley Longman, Inc. 31


2.9 Forms (continued)
-Widgets (continued)

4. Menus - created with <select> tags

- There are two kinds of menus, those that


behave like checkboxes and those that
behave like radio buttons (the default)

- Menus that behave like checkboxes are


specified by including the multiple attribute,
which must be set to "multiple"

- The name attribute of <select> is required

- The size attribute of <select> can be


included to specify the number of menu
items to be displayed (the default is 1)

- If size is set to > 1 or if multiple is


specified, the menu is displayed as a
pop-up menu

Chapter 2 © 2005 by Addison Wesley Longman, Inc. 32


2.9 Forms (continued)
- Widgets (continued)

4. Menus (continued)

- Each item of a menu is specified with an


<option> tag, whose pure text content
(no tags) is the value of the item

- An <option> tag can include the selected


attribute, which when assigned "selected"
specifies that the item is preselected

Grocery Menu - milk, bread, eggs, cheese

<form action = "">


<p>
With size = 1 (the default)
<select name = "groceries">
<option> milk </option>
<option> bread </option>
<option> eggs </option>
<option> cheese </option>
</select>
</p>
</form>

Chapter 2 © 2005 by Addison Wesley Longman, Inc. 33


2.9 Forms (continued)
- Widgets (continued)

- After clicking the menu:

- After changing size to 2:

Chapter 2 © 2005 by Addison Wesley Longman, Inc. 34


2.9 Forms (continued)
-Widgets (continued)

5. Text areas - created with <textarea>

- Usually include 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

Please provide your employment aspirations

<form action = "">


<p>
<textarea name = "aspirations" rows = "3”
cols = "40">
(Be brief and concise)
</textarea>
</p>
</form>

Chapter 2 © 2005 by Addison Wesley Longman, Inc. 35


2.9 Forms (continued)
- Widgets (continued)

6. Reset and Submit buttons

- Both are created with <input>

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


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

- Submit has two actions:

1. Encode the data of the form

2. Request that the server execute the


server-resident program specified as the
value of the action attribute of <form>

- A Submit button is required in every form

--> SHOW popcorn.html and display it

Chapter 2 © 2005 by Addison Wesley Longman, Inc. 36


2.10 Frames
- Frames are rectangular sections of the display
window, each of which can display a different
document

- Because frames are no longer part of XHTML, you


cannot validate a document that includes frames

- The <frameset> tag specifies the number of


frames and their layout in the window

- <frameset> takes the place of <body>


- Cannot have both!

- <frameset> must have either a rows attribute


or a cols attribute, or both (usually the case)
- Default is 1

- The possible values for rows and cols are


numbers, percentages, and asterisks

- A number value specifies the row height in


pixels - Not terribly useful!

- A percentage specifies the percentage of


total window height for the row - Very useful!

Chapter 2 © 2005 by Addison Wesley Longman, Inc. 37


2.10 Frames (continued)
- An asterisk after some other specification gives
the remainder of the height of the window

- Examples:
<frameset rows = "150, 200, 300">

<frameset rows = "25%, 50%, 25%">

<frameset rows = "50%, 20%, *" >

<frameset rows = "50%, 25%, 25%"


cols = "40%, *">

- The <frame> tag specifies the content of a frame

- The first <frame> tag in a <frameset> specifies


the content of the first frame, etc.
- Row-major order is used

- Frame content is specified with the src


attribute

- Without a src attribute, the frame will be


empty (such a frame CANNOT be filled later)

- If <frameset> has fewer <frame> tags than frames,


the extra frames are empty

Chapter 2 © 2005 by Addison Wesley Longman, Inc. 38


2.10 Frames (continued)
- Scrollbars are implicitly included if needed (they
are needed if the specified document will not fit)

- If a name attribute is included, the content of the


frame can be changed later (by selection of
a link in some other frame)

→SHOW frames.html

- Note: the Frameset standard must be specified in


the DOCTYPE declaration

Chapter 2 © 2005 by Addison Wesley Longman, Inc. 39


2.10 Frames (continued)
<!-- contents.html
The contents of the first frame of
frames.html, which is the table of
contents for the second frame
-->
<html xmlns = ″http://www.w3.org/1999/xhtml″>
<head> <title> Table of Contents Frame
</title>
</head>
<body>
<h4> Fruits </h4>
<ul>
<li> <a href = "apples.html"
target = "descriptions">
apples </a>
<li> <a href = "bananas.html"
target = "descriptions">
bananas </a>
<li> <a href = "oranges.html"
target = "descriptions">
oranges </a>
</ul>
</body>
</html>

Chapter 2 © 2005 by Addison Wesley Longman, Inc. 40


2.10 Frames (continued)

- Nested frames - to divide the screen in more


interesting ways

→ SHOW nested_frames.html

2.11 Syntactic Differences between


HTML & XHTML
- Case sensitivity

- Closing tags

- Quoted attribute values

- Explicit attribute values

- id and name attributes

- Element nesting

Chapter 2 © 2005 by Addison Wesley Longman, Inc. 41


Cascading Style Sheets (CSS)
INTRODUCTION
• Simple design language intended to transform the presentation of a Web
Pages
• CSS handles the look and feel part of a web page
• We can control the color of the text, the style of fonts, the spacing between
paragraphs, how columns are sized and laid out, what background images or
colors are used, layout designs, variations in display for different devices and
screen sizes as well as a variety of other effects
• Provides powerful control over the presentation of an HTML document
• Has the capability to impose consistency on the style of web document
ORIGINS AND EVOLUTION OF CSS
• Year Description
• 1994 HÃ¥kon Wium Lie proposed the idea of CSS to allow web designers to
change the layout, colors, and fonts of their websites.
• 1996 The first version of CSS was released while the newly established CSS
Working Group moved forward with CSS2.
• 1998 The second version of CSS was released and work on CSS-3 started at
the same time.
• 2011 A clarified version of CSS2 called CSS2.1, was released, which fixed the
errors found in CSS 2
• 2012 As of June 2012, there are over fifty CSS modules published from the
CSS-3 Working Group.
LEVELS OF STYLESHEETS
• Inline
• Applied to the content of a single HTML element
• Document level:
• Applied to the whole body of the document
• External:
• Applied to bodies of any number of documents

• Inline style sheets have precedence over the document style sheets which
have the precedence over external style sheets
LEVELS OF STYLESHEETS
• Inline style sheets:
• Appear within the opening tag and apply only to the content of that
element

• Disadvantages:

• Imposing a uniform style on the elements of least one whole document is


difficult
• Results in style information which is expressed in a language distinct from
HTML markup, being embedded in various places in documents
LEVELS OF STYLESHEETS
• Inline style sheets:
<!DOCTYPE html>
<html>
<head>
<title>Inline CSS</title>
</head>

<body>
<p style="color:#009900; font-size:50px;
font-style:italic; text-align:center;">
NMAMIT NITTE
</p>
</body>
</html>
LEVELS OF STYLESHEETS
• Document level style specification:
• Appear in the head section of the document
• Apply to the entire body of the document
• Effective way of imposing a uniform style on the presentation of all of the
content of a single document
LEVELS OF STYLESHEETS
• External style sheets
• Useful when styles are to be applied to more than one document
• Stored separately
• Referenced by documents
• Clean Separation of CSS from HTML
• Browser fetches external style sheets just as it fetches HTML documents
• <link> tag is used to specify external style sheets
<link rel=“stylesheet” type=“text/css”
href=“style1.css”/>
STYLE SPECIFICATION FORMATS
• Style formatting depends on the level of style sheet

• Inline style specification:

• style=“property1:value1;propert2:value;..”
STYLE SPECIFICATION FORMATS

Document level specification:


<style type=“text/css”>
Rule_list
</style>

Format for Style Rule:


• selector {property1:value1; propery2:value2;,,,}
STYLE SPECIFICATION FORMATS

External style sheets:


• Consists of a list of style rules (of the same form as in document
style sheets)
• <style> tag is not included

Comments :
• Pair of /* and */ is used
SELECTOR FORMS
• A selector specifies the elements to which the following style information
applies
• The selector can have a variety of forms:
• Simple selector forms
• Class selectors
• Generic selectors
• Id selectors
• Contextual selectors
• Pseudo classes
• Universal selectors
SELECTOR FORMS
Simple selector forms
• Includes element or elements name
• Property values in the rule apply to all occurrences of the named
elements

Examples:
• h1{property-value list}
• h2,h3{property-value list}
SELECTOR FORMS
Class selectors
• Used to allow different occurrences of the same tag to use different style specifications
• A style class is defined in a style element by giving the style class name, which is
attached to the tag’s name with a period

Example:
• p.normal {property-value list}
• p.warning {property-value list}
• Within the document body, the particular style class is specified with the class
attribute
<p class=“normal”>…….</p>
<p class=“warning”……</p>
SELECTOR FORMS
Generic selectors
• Used to apply class of style specifications to the content of more than one kind of tag
• A generic class is defined without tag name in its selector
• A generic class begins with a period

Example:
• p.sale {property-value list}

• Within the document body, the particular style class is specified with the class
attribute
<p class=“sale”>…….</p>
<h3 class=“sale”……</p>
SELECTOR FORMS
Id Selectors
• Allows the application of a style to the one specific element

General form:
• #specific-id {property-value list}
• Style specified in the id selector applies to the element with the given id
• Example:
• #heading2 {property-value list}

• This style is applied to following h2


• <h2 id=“heading2”>………….</h2>
SELECTOR FORMS
Contextual selectors
• It is possible to apply a style elements in certain positions in the document

Descendent selectors:
• Element B is descendent of element A if it appears in the content of A
• Example:
• ul ol {property-value list}
SELECTOR FORMS
• An element is child of another if it is descendent and it is nested directly in that
element.
• Example:
• <ol>
<li>….</li>
<ul>
<li>….</li>
....
</ul>
<li>…..</li>

</ol>

• Child selector:
ol > li {property-value list}
p> h1 > em {property-value list}
SELECTOR FORMS
Pseudo classes
• Specify that certain styles apply when something happens
• Pseudo classes for styling links:
• link – used to style a link that has not been selected
• visited – used to style a link that previously has been selected
• hover – used to apply style when its associated element has the mouse cursor over it
• Focus – used to apply style when its associated element has focus

• Example:
• h2 : hover {property-value list}
SELECTOR FORMS
Universal selector
• Applies its style to all elements in a document

• Example:
* {property-value list}
FONT PROPERTIES

• font-family
• font-size
• font-variant
• font-style
• font-weight
FONT SHORTHAND
TEXT DECORATION PROPERTIES

• text-decoration
• letter-spacing
• word-spacing
• line-height
LIST PROPERTIES

The CSS list properties allow you to:


• Set different list item markers for ordered lists: list-style-type
• Set different list item markers for unordered lists: list-style-type
• Set an image as the list item marker: list-style-image
ALIGNMENT OF TEXT

• text-indent
• text-align
• float
COLOR

• color
• background-color
• float
BOX MODEL
• It is a container that contains multiple properties including borders, margins,
padding, and the content itself
• It is used to create the design and layout of web pages
• It can be used as a toolkit for customizing
the layout of different elements.
• The web browser renders every element
as a rectangular box according
to the CSS box model
BOX MODEL
Border properties:
• border-style
• border-top-style
• border-bottom-style
• border-left-style
• border-right-style
BOX MODEL
margin properties:
• margin
• margin-left
• margin-right
• margin-top
• margin-bottom
• applies to all four sides of an element, margin-left, margin-right, margin-top,
and margin-bottom.
BACKGROUND IMAGE

• background-image
• background-repeat
• background-position
HyperText Markup Language
(HTML)
TOPICS
• Origins and evolution of html and xhtml
• Basic Syntax
• Standard Structure
• Basic Text Markup
• Images
• Hypertext Links
• Lists
• Tables
• Forms
• Frames
ORIGINS AND EVOLUTION OF HTML AND XHTML
• Markup Language-used to mark parts of documents to indicate how they
should appear on display
• Defined with Standard Generalized Markup Language(SGML) – standard for
describing information formatting languages
• HTML was designed to specify document structure at a higher and more
abstract level
• The original version of HTML was designed in conjunction with the structure
of the Web (early 90s)
• MOSAIC(Netscape) Vs Internet Explorer led to incompatible versions of
HTML
ORIGINS AND EVOLUTION OF HTML AND XHTML
(Contd..)
• 1994 – World Wide Web Consortium (W3C) was started– to develop and
distribute standards for Web technologies
• 1995 – first HTML standard HTML 2.0 was released
• Early 1997- HTML 3.2
• 1997 – HTML 4.0, Addition of Style sheets to HTML was supported
• 1999- HTML 4.01
• Specifies loose syntax rules
• No specification for browsers for error recovery
ORIGINS AND EVOLUTION OF HTML AND XHTML
(Contd..)
• 2000 – XHTML 1.0 ( eXtensible HyperText Markup Language), redefinition of HTML 4.01 using
XML ( Alternative to SGML, with strict syntax rules)
• 2001 –XHTML 1.1 – support for frames dropped
• 2002 - XHTML 2.0 – No backward compatibility with HTML 4.01 or XHTML 1.1
• 2004 – new organisation – Web HyperText Application Technology(WHAT) Working Group
• Backward compatibility with HTML 4.01
• Error handling
• Users not exposing to document syntax error

• WHATWG released Web Applications 1.0


• 2006- W3C started working with WHAT
• 2009- W3C decided to adopt HTML development and drop the XHTML 2.0 effort
• Web Applications 1.0 renamed as HTML5
ORIGINS AND EVOLUTION OF HTML AND XHTML
(Contd..)

HTML XHTML
Extended from SGML Extended from HTML and XML
Developed by W3C and WHATWG, released in Developed by W3C, released in 2000
1991
File extension: .html , .htm .xhtml, .xht, .xml, .html, .htm
Flexible framework requiring lenient HTML A restrictive subset of XML and needs to be
specific parser parsed with standard XML parsers
Not case sensitive Every tag and attribute should be in lowercase
While using the attributes, it is not necessary to While using the attributes, it is necessary to
mention quotes mention quotes

Some attribute values are implicit Attribute values must be explicitly provided
BASIC SYNTAX
Tags :
• The fundamental syntactic units, used to specify categories of content
• Tag’s name are surrounded by angle brackets
• Tags appear in pairs (e.g.: <p> and </p>)
• The opening and closing tag together specify a container for the content they
enclose
• Content: whatever appears between opening and closing tags
• Not all tags can have content (e.g :<br/>)
• Element: container + its content
BASIC SYNTAX (Contd..)
Attributes :
• Used to specify alternative/additional meaning of a tag
• Written between an opening tag’s name and its right angle bracket
• Specified in keyword form- attribute’s name is followed by an equals sign and the
attribute’s value
• Example: <img src=“img1.jpg” />

Comments:
• Ignored by browsers
• Can spread over as many lines as are needed
• <!-- this is comment -->
BASIC SYNTAX (Contd..)

• Browsers also ignore : all unrecognized tags, line breaks, multiple spaces and
tabs
• HTML tags are treated more as suggestions to the browsers => misspelled tag
name usually results in the tag being ignored by the browser, with no
indication of errors
STANDARD HTML DOCUMENT STRUCTURE
• DOCTYPE command: specifies the particular SGML document type definition
(DTD) with which the document complies
• <!DOCTYPE html>
• <html> : identifies the root element of the document
• <head>:
• Provides the information about the document but does not provide its content
• <title>: the content of this tag is displayed by the browser at the top of its display
window
• <meta/>: used to provide additional information about the document such as
character set used to write the document
• <body>: represents the contents to be displayed in webpage
BASIC TEXT MARKUP
Paragraphs:
• Text is normally organized into paragraphs in the body of the document
specified with the <p> tag
• In displaying text, the browser puts as many words as will fit on the lines in
the browser window. The browser supplies a line break at the end of each line

Line breaks:
• Used when text requires an explicit line break without preceding blank line
• Achieved using <br/> tag
BASIC TEXT MARKUP(Contd..)
Preserving White spaces
• Sometimes it is desirable to preserve the white space in text- to prevent the browser
from eliminating multiple spaces and ignoring embedded line breaks
• Achieved using <pre> tag
Headings:
• There are six levels of headings: <h1> to <h6>
Block quotations:
• Sometimes we want a block of text to be set off from the normal flow of a text in a
document
• <blockquote> is used for the same
BASIC TEXT MARKUP(Contd..)
Font Styles and Sizes:
Content based tags- indicate the particular kind of text that appears in their content
<em>
• specifies that its textual content is special and should be displayed in some way
that indicate this distinctiveness. Most browsers use italics for such content
<strong>
• Browsers often set the content of strong in bold
<code>
• Used to specify a monospace font, usually for program code

Content based tags are not affected by <blockquote>


BASIC TEXT MARKUP(Contd..)
Font Styles and Sizes:
Subscript and Superscript:
• Specified using <sub> and <sup> tags respectively

Block and inline tags:


• Inline tag: its content appears on the current line
• Example: <em>, <strong> etc
• Block tags: breaks the current line; so its content appears on a new line
• Example: <p>, heading tags, <blockquote> etc
• A block tag cannot be directly nested in an inline tag
BASIC TEXT MARKUP(Contd..)
Character entities:
• HTML provides a collection of special characters that are sometimes needed in a
document but cannot be typed as themselves
• These special characters are defined as entities, which are codes for the characters
• The browser replaces an entity in a document by its associated character
Result Description Entity Name Entity Number
non-breaking &nbsp; &#160;
space
< less than &lt; &#60;
> greater than &gt; &#62;
& ampersand &amp; &#38;
" double quotation &quot; &#34;
mark
' single quotation &apos; &#39;
mark (apostrophe)
¢ cent &cent; &#162;
£ pound &pound; &#163;
¥ yen &yen; &#165;
€ euro &euro; &#8364;
© copyright &copy; &#169;
® registered &reg; &#174;
trademark
1/2 Half &frac12; &#189;
BASIC TEXT MARKUP(Contd..)
Horizontal Rules:
• Two parts of a document can be separated from each other by placing a horizontal line
between them using <hr /> tag
• Makes document easier to read
• It causes a line break and places a line across the screen
• The browser chooses the thickness, length, and horizontal placement of the line
IMAGES
• The inclusion of images in a document enhances its appearances although document
download process slows down
• The image element specifies an image that is to appear in a document
• <img /> tag is used to add image along with attributes:
• src: specifies the file containing the image
• alt : specifies text to be displayed when it is not possible to display the image
• width and height can be used to specify(in pixels) the size of the rectangle for the
image
• A percentage value can be given for the width to specify the percentage of the width
of the display that will be occupied by the image
LISTS
• HTML provides simple and effective ways to specify lists in documents
Types:
• Unordered lists
• Ordered lists
• Definition lists
UNORDERED LISTS
• <ul> tag creates unordered list
• <li> is used to specify each item in the list
• Any tags can appear in a list item including nested lists
• When displayed each list item is implicitly preceded by a bullet
ORDERED LISTS
• Lists in which the order of items is important
• Orderness of a list is shown by the implicit attachment of a sequential value to the
beginning of each item
• The default sequential values begins with 1
• An ordered list is created within the block tag <ol>
• type attribute : specifies which type of sequence to be used (1,a,A,i,I)
• start attribute : specifies from which value sequencing should start
• The items are specified using <li>
• Items in an ordered list are preceded by sequential values
• Lists can be nested- but nested list must be the content of <li> element
DEFINITION LISTS
• Used to specify lists of terms and their definitions (as in glossaries)
• <dl> element is used
• Each term to be defined in the definition list is given as the content of a dt element
• The definition are specified as the content of dd elements
• Defined terms are usually displayed in the left margin
• The definitions are usually shown indented on the line or lines following the term
HTML5
IFRAME
• iframe in HTML stands for Inline Frame
• Frame divides the web page into various frames/windows; where as
iframe embeds some other document within the current HTML
document
• It defines a rectangular region within the document in which the
browser can display a separate document, including scrollbars and
borders
• The ‘ src ‘ attribute is used to specify the URL of the document that
occupies the iframe
SEMANTIC HTML

• Use of HTML tags that convey the meaning—or semantics—of the


content contained within them
• By adding semantic HTML tags to web pages, we can provide additional
information that helps define the roles and relative importance of the
different parts of the page
SEMANTIC TAGS
• Semantic HTML tags are tags that define the meaning of the content
they contain
• Example: <header>, <article>, <footer> etc
• They clearly indicate the role of the content they contain

• Non Semantic tags serve only as content holders but give no indication
as to what type of content they contain or what role that content plays
on the page
• Example: <div> , <span> etc
SEMANTIC TAGS-USES
• Semantic HTML tags are easier to read and understand-(example: for
developers reviewing the code)
• Pages with correctly implemented semantic HTML have an advantage in SEO
over those that don’t.
• Semantic HTML tags indicate the role of the content within the tags
• This information gives search engine crawlers, like Googlebot, a better
understanding of content.
• This increases the chances that the content will be selected as a candidate for
ranking on the search engine results page (SERP) for relevant keywords.
TYPES OF HTML SEMANTIC TAGS
HTML Semantic Tags for Text-
• <h1> to <h6> , <p>, <a>, <ol>, <ul>, <strong>, <code> etc
HTML SEMANTIC TAGS FOR STRUCTURE
HTML SEMANTIC TAGS FOR STRUCTURE

• <header>: The header tag defines content that should be considered


the introductory information of a page or section

• <nav>: The navigation tag is used for navigation links. It can be nested
within the <header> tag, but secondary navigation <nav> tags are also
commonly used elsewhere on the page
HTML SEMANTIC TAGS FOR STRUCTURE
• <main>: This tag contains the main content (also called the body) of a
page. There should be only one tag per page

• <article>: specifies independent, self-contained content.

• <section>: Using <section> is a way of grouping nearby content of a


similar theme. A section tag differs from an article tag. It isn’t necessarily
self-contained, but it forms part of something else.
HTML SEMANTIC TAGS FOR STRUCTURE
• <aside>: An aside element defines content that’s less important than main
content. It’s often used for sidebars—areas that add complementary
information. It let us easily recognize the main text and subordinate text

• <footer>: You use <footer> at the bottom of a page. It usually includes


contact information, copyright information, and some site navigation.
VIEWPORT
• viewport is the area of web page in which the content is visible to the
user
• The viewport does not have the same size, it varies with the variation in
screen size of the devices on which the website is visible.
• For a laptop, the viewport has a larger size as compared to a
smartphone or tablet
• When a page is not made responsive for smaller viewports it looks bad
• To fix this problem, meta viewport was introduced, a responsive tag to
control the viewport
VIEWPORT

• width=device-width sets the width of the page to follow the screen-


width of the device (which will vary depending on the device)
• initial-scale=1.0 sets the initial zoom level when the page is first loaded
by the browser
Computer code elements
• <kbd>
• The HTML <kbd> element is used to define keyboard input. The content
inside is displayed in the browser's default monospace font
Computer code elements
• <samp>
• The HTML <samp> element is used to define sample output from a
computer program. The content inside is displayed in the browser's
default monospace font
Computer code elements
• <code>
• The HTML <code> element is used to define a piece of computer code.
The content inside is displayed in the browser's default monospace font

• <code> element does not preserve extra whitespace and line-breaks.


Computer code elements
• <var>
• The HTML <var> element is used to define a variable in programming or
in a mathematical expression. The content inside is typically displayed in
italic.
The <canvas> element
The canvas element allows for dynamic, scriptable rendering of 2D shapes and bitmap
images.
A canvas consists of a drawable region defined in HTML code with height and width
attributes. JavaScript code may access the area through a full set of drawing functions thus
allowing for dynamically generated graphics.

The <canvas> element is only a container for graphics. We must use JavaScript to actually
draw the graphics.

Canvas has several methods for drawing paths, boxes, circles, text, and adding images.

A canvas is a rectangular area on an HTML page. By default, a canvas has no border and no
content.

Creating an empty canvas:

<canvas id="myCanvas" width="200" height="100" style="border:1px solid


#000000;"></canvas>

Adding JavaScript:
After creating the rectangular canvas area, we must add a JavaScript to do the drawing.
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.moveTo(0, 0);
ctx.lineTo(200, 100);
ctx.stroke();
</script>
Drawing circle:
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.arc(95, 50, 40, 0, 2 * Math.PI);
ctx.stroke();
</script>

Drawing text:
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.font = "30px Arial";
ctx.fillText("Hello World", 10, 50);
</script>

HTML5 <svg> element.


SVG stands for Scalable Vector Graphics. It basically defines vector-based graphics in XML
format. SVG graphics do NOT lose any quality if they are zoomed or resized.

The HTML <svg> element is a container for SVG graphics.

SVG has several methods for drawing paths, boxes, circles, text, and graphic images.

Examples:
Circle:
<svg width="100" height="100">
<circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
</svg>

Rectangle:
<svg width="400" height="100">
<rect width="400" height="100" style="fill:rgb(0,0,255);stroke-
width:10;stroke:rgb(0,0,0)" />
</svg>

<svg width="400" height="180">


<rect x="50" y="20" rx="20" ry="20" width="150" height="150"
style="fill:red;stroke:black;stroke-width:5;opacity:0.5" />
</svg>

Differences Between SVG and Canvas

SVG is a language for describing 2D graphics in XML.

Canvas draws 2D graphics, on the fly (with JavaScript).


SVG is XML based, which means that every element is available within the SVG DOM. You
can attach JavaScript event handlers for an element.

In SVG, each drawn shape is remembered as an object. If attributes of an SVG object are
changed, the browser can automatically re-render the shape.

Canvas is rendered pixel by pixel. In canvas, once the graphic is drawn, it is forgotten by the
browser. If its position should be changed, the entire scene needs to be redrawn, including
any objects that might have been covered by the graphic.

New input types in HTML5

color: This input type allows the user to select a color from a color picker.

date: This input type allows the user to select a date from a drop-down calendar.

time: This input type allows the user to enter a time.

datetime: This input type allows the user to select date and time along with timezone.

datetime-local: This input type allows the user to select both local date and time.

week: This input type allows the user to select week and year from the drop-down calendar.

email: This input type allows the user to enter an e-mail address.

month: This input type allows the user to select a month and year from a drop-down calendar.

number: This input type allows the user to enter a numerical value.

range: This input type allows the user to enter a numerical value within a specified range.

search: This input type allows the user to enter a search string within the input field.

tel: This input type allows the user to enter a telephone number.

url: This input type allows the user to enter the URL.
New form elements:

<fieldset>

The HTML <fieldset> tag is used to group similar form elements. It is a presentational tag
and does not affect the data in the form.

form >
<fieldset>
<label for="firstname">First name:</label><br>
<input type="text" id="firstname" name="fname"><br>
<label for="lastname">Last name:</label><br>
<input type="text" id="lastname" name="lname"><br>
</fieldset>
</form>

<legend> tag

The HTML <legend> tag is another presentational tag used to give a caption to

a <fieldset> element.

<form>
<fieldset>
<legend>Name</legend>
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname"><br>
</fieldset>
</form>

<datalist> tag
The <datalist> tag defines a list of pre-defined options for an <input> element. It is used to

provide autocomplete options to the form elements that show up as recommended options

when the user fills in the form.

<label for="country-choice">Choose a country:</label>


<input list="country-options" id="country-choice" name="country-choice">
<datalist id="country-options">
<option value="Australia">
<option value="Austria">
<option value="America">
<option value="Nepal">
</datalist>

<output> tag

The HTML <output> tag is a container element that is used to store the output of a

calculation usually performed using javascript.

<form>
<input type="number" id="b" name="b" value="50" /> +
<input type="number" id="a" name="a" value="10" /> =
<output name="result" for="a b"></output>
</form>
<script>
const output = document.getElementsByName("result")[0]
const inputA = document.getElementById('a')
const inputB = document.getElementById('b')
output.innerText = Number(inputA.value) + Number(inputB.value)
</script>

The for attribute of the <output> tag accepts a space-separated value of all the inputs used

in the calculation. The value inside the <output> is generally generated from Javascript and

filled inside the element.

Google Maps:
<!DOCTYPE html>

<html>

<body>

<h1>My First Google Map</h1>

<div id="googleMap" style="width:100%;height:400px;"></div>

<script>

function myMap() {

var mapProp= {

center:new google.maps.LatLng(51.508742,-0.120850),

zoom:5,

};

var map

= new google.maps.Map(document.getElementById("googleMap"),mapProp);

</script>

<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_KEY&callb

ack=myMap"></script>

</body>

</html>
Steps:

1. The map needs an HTML element to hold the map:

<div id="googleMap" style="width:100%;height:400px"></div>

2. function myMap() {

var mapProp = {

center:new google.maps.LatLng(51.508742,-0.120850),

zoom:5,

};

var map = new

google.maps.Map(document.getElementById("googleMap"),mapProp);

The mapProp variable defines the properties for the map.

The center property specifies where to center the map (using latitude and longitude
coordinates).

The zoom property specifies the zoom level for the map (try to experiment with the zoom
level).

The line: var map=new google.maps.Map(document.getElementById("googleMap"),


mapProp); creates a new map inside the <div> element with id="googleMap", using the
parameters that are passed (mapProp).
HTML5 media:
HTML5 <audio> Tag:
The <audio> tag is an inline element that is used to embed sound files into a web page.

<audio>
<source src="sample.mp3" type="audio/mpeg">
</audio>

• Using the <source> element enables the specification of various audio files,
allowing the browser to choose the compatible format.
• The <audio> element allows integration with JavaScript, enabling the creation
of custom audio controls and behaviors.
• The ‘controls’ attribute provides buttons for managing audio, like play, pause,
and volume adjustment.
• Any text contained between the <audio> tags is visible only on browsers that
can’t render the <audio> element.

<audio controls autoplay>


<source src="horse.ogg" type="audio/ogg">
<source src="horse.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
HTML5 Video

The <video> element is used to embed video content on the web page. It allows the
addition of video files in many formats.
This element supports attributes like controls, autoplay, and loop to control video
playback. It also enables the addition of captions and subtitles for accessibility.

<video width="320" height="240" controls>


<source src="movie.mp4" type="video/mp4">
<source src="movie.ogg" type="video/ogg">
Your browser does not support the video tag.
</video>

The controls attribute adds video controls, like play, pause, and volume.

It is a good idea to always include width and height attributes. If height and width are not
set, the page might flicker while the video loads.

The <source> element allows you to specify alternative video files which the browser may
choose from. The browser will use the first recognized format.

The text between the <video> and </video> tags will only be displayed in browsers that do
not support the <video> element.
BOOTSTRAP
Introduction to Bootstrap:

Bootstrap is a free and open-source tool collection for creating responsive websites and web
applications. It is the most popular HTML, CSS, and JavaScript framework for developing responsive,
mobile-first websites.

By using this framework we can easily manipulate the styling of any web page, like font style, text color,
background color, flex, grid system, etc.

Features:

• It is Faster and Easier way for Web-Development.


• It creates Platform-independent web-pages.
• It creates Responsive Web-pages.
• It designs responsive web pages for mobile devices too.
• It is a free and open-source framework available on www.getbootstrap.com

Applications:

• Responsive Web Design: Bootstrap empowers developers to create


websites that seamlessly adapt to different screen sizes and devices,
providing a consistent and optimal user experience.
• Mobile-First Development: Bootstrap’s mobile-first approach ensures
that websites are designed and optimized for mobile devices, catering to
the increasing usage of smartphones and tablets.
• Efficient Prototyping: With its extensive collection of pre-designed
components and templates, Bootstrap facilitates rapid prototyping,
enabling developers to quickly create functional website layouts and UIs.
• Consistent Cross-Browser Compatibility: Bootstrap’s standardized CSS
and JavaScript codebase ensures consistent rendering and functionality
across various web browsers, saving developers time and effort in browser-
specific troubleshooting.
• Customizable Themes and Styling: Bootstrap offers a wide range of
customizable themes and styles, allowing developers to create visually
appealing and unique designs that align with their brand or project
requirements.
• Time and Cost Efficiency: By leveraging the power of Bootstrap,
developers can save significant time and effort in front-end development,
resulting in faster project delivery and cost savings.

Bootstrap 5 is the newest version of Bootstrap with new components, faster


stylesheet and more responsiveness.

There are two ways to start using Bootstrap:


Include Bootstrap 5 from a CDN

• If we don't want to download and host Bootstrap 5, we can include it


from a CDN (Content Delivery Network).

• jsDelivr provides CDN support for Bootstrap's CSS and JavaScript:

<!-- Latest compiled and minified CSS -->


<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/boots
trap.min.css" rel="stylesheet">

<!-- Latest compiled JavaScript -->


<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/boots
trap.bundle.min.js"></script>

Why use CDN?

Many users already have downloaded Bootstrap 5 from jsDelivr when visiting
another site. As a result, it will be loaded from cache when they visit your
site, which leads to faster loading time. Also, most CDN's will make sure that
once a user requests a file from it, it will be served from the server closest to
them, which also leads to faster loading time.

Bootstrap 5 uses JavaScript for different components (like modals, tooltips,


popovers etc). However, if you just use the CSS part of Bootstrap, you don't
need them.

Download Bootstrap 5 from getbootstrap.com

We can download ready-to-use compiled code to easily drop into the project, which
includes:

• Compiled and minified CSS bundles


• Compiled and minified JavaScript plugins

Download and unzip the compiled Bootstrap. Now if we look inside the folders
we will find the compiled CSS and JS files (bootstrap.*), as well as the compiled
and minified CSS and JS (bootstrap.min.*). We can refer to these files in our
HTML file.

Containers:
Bootstrap requires a containing element to wrap site contents.

Containers are used to pad the content inside of them, and there are two
container classes available:

1. The .container class provides a responsive fixed width container


2. The .container-fluid class provides a full width container, spanning
the entire width of the viewport

Example(CDN is used)

<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/boo
tstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/boo
tstrap.bundle.min.js"></script>
</head>
<body>

<div class="container">
<h1>My First Bootstrap Page</h1>
<p>This part is inside a .container class.</p>
<p>The .container class provides a responsive fixed width
container.</p>
</div>

</body>
</html>

Bootstrap 5 Grid System:

Bootstrap's grid system is built with flexbox and allows up to 12 columns


across the page.
If we do not want to use all 12 columns individually, we can group the
columns together to create wider columns.

The grid system is responsive, and the columns will re-arrange automatically
depending on the screen size.

Grid Classes

The Bootstrap 5 grid system has six classes:

.col- (extra small devices - screen width less than 576px)

.col-sm- (small devices - screen width equal to or greater than 576px)

.col-md- (medium devices - screen width equal to or greater than 768px)

.col-lg- (large devices - screen width equal to or greater than 992px)

.col-xl- (xlarge devices - screen width equal to or greater than 1200px)

.col-xxl- (xxlarge devices - screen width equal to or greater than 1400px)

The classes above can be combined to create more dynamic and flexible
layouts.

Basic Structure of a Bootstrap Grid:

The following is a basic structure of a Bootstrap 5 grid:

<!-- Control the column width, and how they should appear on different
devices -->
<div class="row">
<div class="col-*-*"></div>
<div class="col-*-*"></div>
</div>
<div class="row">
<div class="col-*-*"></div>
<div class="col-*-*"></div>
<div class="col-*-*"></div>
</div>

• First create a row (<div class="row">)

• In col-*-*", first star (*) represents the responsiveness: sm, md, lg,
xl or xxl, while the second star represents a number, which should add
up to 12 for each row.

<!-- Or let Bootstrap automatically handle the layout -->


<div class="row">
<div class="col"></div>
<div class="col"></div>
<div class="col"></div>
</div>

Here, instead of adding a number to each col, bootstrap is let to handle the
layout, to create equal width columns: two "col" elements = 50% width to
each col, while three cols = 33.33% width to each col. Four cols = 25%
width, etc.

Example:

The following example shows how to create four equal-width columns


starting at tablets and scaling to extra large desktops.

<div class="row">
<div class="col-sm-3">.col-sm-3</div>
<div class="col-sm-3">.col-sm-3</div>
<div class="col-sm-3">.col-sm-3</div>
<div class="col-sm-3">.col-sm-3</div>
</div>

Creating two various-width columns starting at tablets and scaling to large


extra desktops:

<div class="row">
<div class="col-sm-4">.col-sm-4</div>
<div class="col-sm-8">.col-sm-8</div>
</div>
Tables:

The .table class adds basic styling to a table:

<!DOCTYPE html>

<html lang="en">

<head>

<title>Bootstrap Example</title>

<meta charset="utf-8">

<meta name="viewport" content="width=device-width, initial-scale=1">

<link
href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.c
ss" rel="stylesheet">

<script
src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.
min.js"></script>

</head>

<body>

<div class="container mt-3">

<h2>Basic Table</h2>

<p>The .table class adds basic styling (light padding and horizontal
dividers) to a table:</p>

<table class="table">

<thead>

<tr>

<th>Firstname</th>

<th>Lastname</th>

<th>Email</th>
</tr>

</thead>

<tbody>

<tr>

<td>John</td>

<td>Doe</td>

<td>[email protected]</td>

</tr>

<tr>

<td>Mary</td>

<td>Moe</td>

<td>[email protected]</td>

</tr>

<tr>

<td>July</td>

<td>Dooley</td>

<td>[email protected]</td>

</tr>

</tbody>

</table>

</div>

</body>

</html>
The .table-striped class adds zebra-stripes to a table:

The .table-bordered class adds borders on all sides of the table and cells:

The .table-hover class adds a hover effect (grey background color) on table
rows.

The .table-dark class adds a black background to the table.

The .table-hover class adds a hover effect (grey background color) on table
rows.

The .table-responsive class adds a scrollbar to the table when needed


(when it is too big horizontally)

You can also decide when the table should get a scrollbar, depending on the
screen width:

Class Screen width


.table-responsive-sm < 576px
Class Screen width
.table-responsive-md < 768px
.table-responsive-lg < 992px
.table-responsive-xl < 1200px
.table-responsive-xxl < 1400px

Contextual Classes
Contextual classes can be used to color the whole table (<table>), the table
rows (<tr>) or table cells (<td>).

The contextual classes that can be used are:

Example:
Images:

The .rounded class adds rounded corners to an image.

<img src="cinqueterre.jpg" class="rounded" alt="Cinque Terre">

The .rounded-circle class shapes the image to a circle.

<img src="cinqueterre.jpg" class="rounded-circle" alt="Cinque Terre">

The .img-thumbnail class shapes the image to a thumbnail

<img src="cinqueterre.jpg" class="img-thumbnail" alt="Cinque Terre">

Float an image to the left with the .float-start class or to the right
with .float-end

<img src="paris.jpg" class="float-start">


<img src="paris.jpg" class="float-end">

Center an image by adding the utility classes .mx-auto (margin:auto) and .d-
block (display:block) to the image:
<img src="paris.jpg" class="mx-auto d-block">

Responsive images automatically adjust to fit the size of the screen.

We can create responsive images by adding an .img-fluid class to


the <img> tag. The image will then scale nicely to the parent element.

The .img-fluid class applies max-width: 100%; and height: auto; to the image:

<img class="img-fluid" src="ny.jpg" alt="New York">

Bootstrap Jumbotron:

A jumbotron was introduced in Bootstrap 3 as a big padded box for calling


extra attention to some special content or information.

We use a <div> element with class .jumbotron to create a jumbotron.

If we want a full-width jumbotron without rounded borders, add


the .jumbotron-fluid class and a .container or .container-fluid inside of
it.

<div class="jumbotron jumbotron-fluid">


<div class="container">
<h1>Bootstrap Tutorial</h1>
<p>Bootstrap is the most popular HTML, CSS...</p>
</div>
</div>

Creating a Page Header


A page header is like a section divider.

The .page-header class adds a horizontal line under the heading (+ adds some
extra space around the element):

<div class="page-header">
<h1>Example Page Header</h1>
</div>

Wells
The .well class adds a rounded border around an element with a gray
background color and some padding

Change the size of the well by adding the .well-sm class for small wells
or .well-lg class for large wells.

<div class="well well-sm">Small Well</div>


<div class="well well-lg">Large Well</div>

Alerts
Bootstrap provides an easy way to create predefined alert messages:
Alerts are created with the .alert class, followed by one of the four
contextual classes .alert-success, .alert-info, .alert-warning or .alert-
danger

We can add the alert-link class to any links inside the alert box to create
"matching colored links":

<div class="alert alert-success">


<strong>Success!</strong> You should <a href="#" class="alert-
link">read this message</a>.
</div>

To close the alert message, add a .alert-dismissible class to the alert


container. Then add class="close" and data-dismiss="alert" to a link or a
button element (when you click on this the alert box will disappear).
<div class="alert alert-success alert-dismissible">
<a href="#" class="close" data-dismiss="alert" aria-
label="close">&times;</a>
<strong>Success!</strong> Indicates a successful or positive action.
</div>

Bootstrap Buttons
Bootstrap provides different styles of buttons.

To achieve the button styles above, Bootstrap has the following classes:

• .btn
• .btn-default
• .btn-primary
• .btn-success
• .btn-info
• .btn-warning
• .btn-danger
• .btn-link

The button classes can be used on an <a>, <button>, or <input> element:

<a href="#" class="btn btn-info" role="button">Link Button</a>


<button type="button" class="btn btn-info">Button</button>
<input type="button" class="btn btn-info" value="Input Button">
<input type="submit" class="btn btn-info" value="Submit Button">
Bootstrap provides four button sizes. The classes that define the different
sizes are:

• .btn-lg
• .btn-sm
• .btn-xs

<button type="button" class="btn btn-primary btn-lg">Large</button>


<button type="button" class="btn btn-primary">Normal</button>
<button type="button" class="btn btn-primary btn-sm">Small</button>
<button type="button" class="btn btn-primary btn-xs">XSmall</button>

A block level button spans the entire width of the parent element. Add
class .btn-block to create a block level button.

<button type="button" class="btn btn-primary btn-block">Button


1</button>
A button can be set to an active (appear pressed) or a disabled (unclickable)
state. The class .active makes a button appear pressed, and the
class .disabled makes a button unclickable.

Badges
Badges are numerical indicators of how many items are associated with a
link. We use the .badge class for the same.

<a href="#">News <span class="badge">5</span></a><br>


<a href="#">Comments <span class="badge">10</span></a><br>
<a href="#">Updates <span class="badge">2</span></a>

<button type="button" class="btn btn-


primary">Primary <span class="badge">7</span></button>

Labels
Labels are used to provide additional information about something:

Use the .label class, followed by one of the six contextual classes .label-
default, .label-primary, .label-success, .label-info, .label-
warning or .label-danger, within a <span> element to create a label.
<span class="label label-default">Default Label</span>
<span class="label label-primary">Primary Label</span>
<span class="label label-success">Success Label</span>
<span class="label label-info">Info Label</span>
<span class="label label-warning">Warning Label</span>
<span class="label label-danger">Danger Label</span>

Progress Bars
A progress bar can be used to show a user how far along he/she is in a
process.

Bootstrap provides several types of progress bars.

To create a default progress bar, add a .progress class to a <div> element.


<div class="progress">
<div class="progress-bar" role="progressbar" aria-valuenow="70"
aria-valuemin="0" aria-valuemax="100" style="width:70%">
<span class="sr-only">70% Complete</span>
</div>
</div>

Progress Bar With Label


If we remove the .sr-only class from the progress bar we can show a visible
percentage of progress.

<div class="progress">
<div class="progress-bar" role="progressbar" aria-valuenow="70"
aria-valuemin="0" aria-valuemax="100" style="width:70%">
70%
</div>
</div>
The contextual classes that can be used with progress bars are:

• .progress-bar-success
• .progress-bar-info
• .progress-bar-warning
• .progress-bar-danger

Add class .progress-bar-striped to add stripes to the progress bars

<div class="progress">
<div class="progress-bar progress-bar-success progress-bar-
striped" role="progressbar"
aria-valuenow="40" aria-valuemin="0" aria-
valuemax="100" style="width:40%">
40% Complete (success)
</div>
</div>

We can create a stacked progress bar by placing multiple bars into the
same <div class="progress">

Bootstrap List Groups


To create a basic list group, use an <ul> element with class .list-group,
and <li> elements with class .list-group-item
<ul class="list-group">
<li class="list-group-item">First item</li>
<li class="list-group-item">Second item</li>
<li class="list-group-item">Third item</li>
</ul>
To create a badge, create a <span> element with class .badge inside the list
item
<ul class="list-group">
<li class="list-group-item">New <span class="badge">12</span></li>
<li class="list-group-item">Deleted <span class="badge">5</span></li>
<li class="list-group-
item">Warnings <span class="badge">3</span></li>
</ul>

To create a list group with linked items, use <div> instead


of <ul> and <a> instead of <li>
<div class="list-group">
<a href="#" class="list-group-item">First item</a>
<a href="#" class="list-group-item">Second item</a>
<a href="#" class="list-group-item">Third item</a>
</div>

We can use the .active class to highlight the current item


<div class="list-group">
<a href="#" class="list-group-item active">First item</a>
<a href="#" class="list-group-item">Second item</a>
<a href="#" class="list-group-item">Third item</a>
</div>

To disable an item, add the .disabled class:


<div class="list-group">
<a href="#" class="list-group-item disabled">First item</a>
<a href="#" class="list-group-item">Second item</a>
<a href="#" class="list-group-item">Third item</a>
</div>

Contextual classes can be used to color list items. The classes for coloring
list-items are: .list-group-item-success, list-group-item-info, list-
group-item-warning, and .list-group-item-danger
<ul class="list-group">
<li class="list-group-item list-group-item-success">First item</li>
<li class="list-group-item list-group-item-info">Second item</li>
<li class="list-group-item list-group-item-warning">Third item</li>
<li class="list-group-item list-group-item-danger">Fourth item</li>
</ul>

Bootstrap provides the classes .list-group-item-heading and .list-group-


item-text which can be used to create custom content.
Navigation Bar
A navigation bar is a navigation header that is placed at the top of the page.
With Bootstrap, a navigation bar can extend or collapse, depending on the
screen size.

A standard navigation bar is created with <nav class="navbar navbar-default">.

<nav class="navbar navbar-default">


<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="#">WebSiteName</a>
</div>
<ul class="nav navbar-nav">
<li class="active"><a href="#">Home</a></li>
<li><a href="#">Page 1</a></li>
<li><a href="#">Page 2</a></li>
<li><a href="#">Page 3</a></li>
</ul>
</div>
</nav>

If we change the .navbar-default class into .navbar-inverse we get:

Navigation bars can also hold dropdown menus:


<nav class="navbar navbar-inverse">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="#">WebSiteName</a>
</div>
<ul class="nav navbar-nav">
<li class="active"><a href="#">Home</a></li>
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="#">Page
1
<span class="caret"></span></a>
<ul class="dropdown-menu">
<li><a href="#">Page 1-1</a></li>
<li><a href="#">Page 1-2</a></li>
<li><a href="#">Page 1-3</a></li>
</ul>
</li>
<li><a href="#">Page 2</a></li>
<li><a href="#">Page 3</a></li>
</ul>
</div>
</nav>

The .navbar-right class is used to right-align navigation bar buttons.


<nav class="navbar navbar-inverse">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="#">WebSiteName</a>
</div>
<ul class="nav navbar-nav">
<li class="active"><a href="#">Home</a></li>
<li><a href="#">Page 1</a></li>
<li><a href="#">Page 2</a></li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><a href="#"><span class="glyphicon glyphicon-
user"></span> Sign Up</a></li>
<li><a href="#"><span class="glyphicon glyphicon-log-
in"></span> Login</a></li>
</ul>
</div>
</nav>
To add buttons inside the navbar, add the .navbar-btn class on a Bootstrap
button:
<nav class="navbar navbar-inverse">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="#">WebSiteName</a>
</div>
<ul class="nav navbar-nav">
<li class="active"><a href="#">Home</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
</ul>
<button class="btn btn-danger navbar-btn">Button</button>
</div>
</nav>

To add form elements inside the navbar, add the .navbar-form class to a
form element and add an input(s).

<form class="navbar-form navbar-left" action="/action_page.php">


<div class="form-group">
<input type="text" class="form-control" placeholder="Search">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>

The .navbar-fixed-top class makes the navigation bar fixed at the top;
The .navbar-fixed-bottom class makes the navigation bar stay at the
bottom

Forms
Bootstrap Form Layouts
Bootstrap provides three types of form layouts:

• Vertical form (this is default)


• Horizontal form
• Inline form

Standard rules for all three form layouts:

• Wrap labels and form controls in <div class="form-group"> (needed for


optimum spacing)
• Add class .form-control to all textual <input>, <textarea>,
and <select> elements

Bootstrap Vertical Form (default)


<form action="/action_page.php">
<div class="form-group">
<label for="email">Email address:</label>
<input type="email" class="form-control" id="email">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd">
</div>
<div class="checkbox">
<label><input type="checkbox"> Remember me</label>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>

Bootstrap Inline Form


In an inline form, all of the elements are inline, left-aligned, and the labels
are alongside.

Additional rule for an inline form:


• Add class .form-inline to the <form> element

<form class="form-inline" action="/action_page.php">


<div class="form-group">
<label for="email">Email address:</label>
<input type="email" class="form-control" id="email">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd">
</div>
<div class="checkbox">
<label><input type="checkbox"> Remember me</label>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>

Bootstrap Horizontal Form


A horizontal form means that the labels are aligned next to the input field
(horizontal) on large and medium screens. On small screens (767px and
below), it will transform to a vertical form (labels are placed on top of each
input).

Additional rules for a horizontal form:

• Add class .form-horizontal to the <form> element


• Add class .control-label to all <label> elements

<form class="form-horizontal" action="/action_page.php">


<div class="form-group">
<label class="control-label col-sm-2" for="email">Email:</label>
<div class="col-sm-10">
<input type="email" class="form-
control" id="email" placeholder="Enter email">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="pwd">Password:</label>
<div class="col-sm-10">
<input type="password" class="form-
control" id="pwd" placeholder="Enter password">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<div class="checkbox">
<label><input type="checkbox"> Remember me</label>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default">Submit</button>
</div>
</div>
</form>

Form Inputs
Bootstrap supports the following form controls:

• input
• textarea
• checkbox
• radio
• select

Bootstrap Input
Bootstrap supports all the HTML5 input types: text, password, datetime,
datetime-local, date, month, time, week, number, email, url, search, tel, and
color.

<div class="form-group">
<label for="usr">Name:</label>
<input type="text" class="form-control" id="usr">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd">
</div>

Textarea
<div class="form-group">
<label for="comment">Comment:</label>
<textarea class="form-control" rows="5" id="comment"></textarea>
</div>

Checkboxes
<div class="checkbox">
<label><input type="checkbox" value="">Option 1</label>
</div>
<div class="checkbox">
<label><input type="checkbox" value="">Option 2</label>
</div>
<div class="checkbox disabled">
<label><input type="checkbox" value="" disabled>Option 3</label>
</div>

Use the .checkbox-inline class if you want the checkboxes to appear on the same line

Radio Buttons
<div class="radio">
<label><input type="radio" name="optradio" checked>Option 1</label>
</div>
<div class="radio">
<label><input type="radio" name="optradio">Option 2</label>
</div>
<div class="radio disabled">
<label><input type="radio" name="optradio" disabled>Option 3</label>
</div>

Use the .radio-inline class if you want the radio buttons to appear
on the same line

Select List
<div class="form-group">
<label for="sel1">Select list:</label>
<select class="form-control" id="sel1">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
</select>
</div>

Media Objects
Bootstrap provides an easy way to align media objects (like images
or videos) to the left or to the right of some content. This can be
used to display blog comments, tweets and so on

We use a <div> element with the .media class to create a container for media
objects.

We use the .media-left class to align the media object (image) to the left, or
the .media-right class to align it to the right.

Text that should appear next to the image, is placed inside a container with
class="media-body".

Additionally, you can use .media-heading for headings.

<!-- Left-aligned -->


<div class="media">
<div class="media-left">
<img src="img_avatar1.png" class="media-object" style="width:60px">
</div>
<div class="media-body">
<h4 class="media-heading">John Doe</h4>
<p>Lorem ipsum...</p>
</div>
</div>

<!-- Right-aligned -->


<div class="media">
<div class="media-body">
<h4 class="media-heading">John Doe</h4>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
</div>
<div class="media-right">
<img src="img_avatar1.png" class="media-object" style="width:60px">
</div>
</div>

The media object can also be top, middle or bottom aligned with
the media-top, media-middle or media-bottom class:
<!-- Media top -->
<div class="media">
<div class="media-left media-top">
<img src="img_avatar1.png" class="media-object" style="width:60px">
</div>
<div class="media-body">
<h4 class="media-heading">Media Top</h4>
<p>Lorem ipsum...</p>
</div>
</div>

The Carousel Plugin


Carousels require the use of an id (in this case id="myCarousel") for carousel
controls to function properly.

The class="carousel" specifies that this <div> contains a carousel.


The .slide class adds a CSS transition and animation effect, which makes the
items slide when showing a new item. Omit this class if you do not want this
effect.

The data-ride="carousel" attribute tells Bootstrap to begin animating the


carousel immediately when the page loads.

The "Indicators" part:

The indicators are the little dots at the bottom of each slide (which indicates
how many slides there are in the carousel, and which slide the user is
currently viewing).

The indicators are specified in an ordered list with class .carousel-indicators.

The data-target attribute points to the id of the carousel.

The data-slide-to attribute specifies which slide to go to, when clicking on the
specific dot.

The "Wrapper for slides" part:

The slides are specified in a <div> with class .carousel-inner.

The content of each slide is defined in a <div> with class .item. This can be
text or images.

The .active class needs to be added to one of the slides. Otherwise, the
carousel will not be visible.

The "Left and right controls" part:

This code adds "left" and "right" buttons that allows the user to go back and
forth between the slides manually.

The data-slide attribute accepts the keywords "prev" or "next", which alters
the slide position relative to its current position.

<div id="myCarousel" class="carousel slide" data-ride="carousel">


<!-- Indicators -->
<ol class="carousel-indicators">
<li data-target="#myCarousel" data-slide-
to="0" class="active"></li>
<li data-target="#myCarousel" data-slide-to="1"></li>
<li data-target="#myCarousel" data-slide-to="2"></li>
</ol>

<!-- Wrapper for slides -->


<div class="carousel-inner">
<div class="item active">
<img src="la.jpg" alt="Los Angeles">
</div>

<div class="item">
<img src="chicago.jpg" alt="Chicago">
</div>

<div class="item">
<img src="ny.jpg" alt="New York">
</div>
</div>

<!-- Left and right controls -->


<a class="left carousel-control" href="#myCarousel" data-
slide="prev">
<span class="glyphicon glyphicon-chevron-left"></span>
<span class="sr-only">Previous</span>
</a>
<a class="right carousel-control" href="#myCarousel" data-
slide="next">
<span class="glyphicon glyphicon-chevron-right"></span>
<span class="sr-only">Next</span>
</a>
</div>
1

Web Technologies

Module VI

PHP

Introduction to PHP: Origins and Uses of PHP, Overview of PHP - General Syntactic Characteristics -
Primitives, Operations, and Expressions – Control Statements, Arrays, Functions, Pattern Matching, Form
Handling, Cookies, Session Tracking

1. Origin and Use of PHP


PHP was developed by Rasmus Lerdorf, in 1994 PHP stands for “Hypertext Preprocessor ”.Originally, PHP
was an acronym for Personal Home Page. It is open source general-purpose scripting language As a server-
side scripting language, PHP is naturally used for form handling and database access.

2. Overview of PHP
PHP is a web development tool and can be embedded into HTML .When a browser requests a document that
includes PHP script, the Web server that provides the document calls its PHP processor. The server
determines that a document includes PHP script by the file-name extension. If it is .php, .php3, or .phtml, the
document has embedded PHP.

The PHP processor has two modes of operation: copy mode and interpret mode. It takes a PHP document
file as input and produces an HTML or XHTML document file. When the PHP processor finds markup code
(which may include embedded client-side script) in the input file, it simply copies it to the output file. When
the processor 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 HTML or XHTML, either of which could
include embedded client-side script. The new file (the output file) is sent to the requesting browser. The
client never sees the PHP script. If the user clicks View Source while the browser is displaying the
document, only the markup (and embedded client-side script) will be shown, because that is all that ever
arrives at the client. Separated in files with the <?php ?> tag . php commands can make up an entire file, or
can be contained in html. Program lines end in ";" or you get an error.PHP scripts are executed on the
server.PHP supports many databases (MySQL, Informix, Oracle, Sybase, Solid, PostgreSQL, Generic
ODBC, etc.) .

3. General Syntactic Characteristics

PHP scripts either are embedded in HTML or XHTML documents or are in files that are referenced by such
documents. PHP code is embedded in documents by enclosing it between the <?php and ?> tags. If a PHP
script is stored in a different file, it can be brought into a document with the include construct, which takes
the filename as its parameter— for example, include(“hello.php”); The included file can contain
markup or client-side script, as well as PHP code, but any PHP script it includes must be the content of a
<?php tag.

The reserved words of PHP


2

PHP allows comments to be specified in three different ways. Single-line comments can be specified either
with # or with //, as in JavaScript. Multiple-line comments are delimited with /* and */, as in many other
programming languages. PHP statements are terminated with semicolons. Braces are used to form
compound statements for control structures.

4. Primitives, Operations, and Expressions

PHP has four scalar types—Boolean, integer, double, and string; two compound types—array and object;
and two special types—resource and NULL.

4.1 Variable

All variable names in PHP begin with a dollar sign ($). The part of the name after the dollar sign is like the
names of variables in many common programming languages: a letter or an underscore followed by any
number (including zero) of letters, digits, or underscores. PHP variable names are case sensitive.PHP is
compatible with almost all servers used today (Apache, IIS, etc.) . PHP is easy to learn and runs efficiently
on the server side

<P>

<?php $myvar = "Hello World!";

echo $myvar;

?>

</P>

Assigned by value - $foo = "Bob"; $bar = $foo;

Assigned by reference, this links vars

$bar = &$foo;

4.2 Integer Type

PHP has a single integer type, named integer. (corresponds to the long type of C) . In most cases, this is 32
bits, or a bit less (not fewer) than ten decimal digits.

4.3 Double Type

PHP's double type corresponds to the double type of C and its successors. Double literals can include a
decimal point, an exponent, or both. The exponent has an E or an e.T here need not be any digits before or
after the decimal point, so both .345 and 345.are legal double literals.

4.4 String Type


3

Characters in PHP are single bytes.There is no character type. A single character data value is represented
as a string of length 1. String literals are defined with either single (') or double quotes (") delimiters. In
single-quoted string literals, escape sequences, such as \n, are not recognized and the values of embedded
variables are not substituted. This substitution is called interpolation.

Print ‘The sum is :$sum’ is exactly as it is typed.ie The. sum is:$sum

In double-quoted string literals, escape sequences are recognized, and embedded variables are replaced by
their current values.

$sum=10;

Print “The sum : $sum”;

o/p :The sum : 10

4.5 Boolean Type

The only two possible values for the Boolean type are TRUE and FALSE, both of which are case
insensitive. If an integer expression is used in Boolean context, it evaluates to FALSE if it is zero; otherwise,
it is TRUE. If a string expression is used in Boolean context, it evaluates to FALSE if it is either the empty
string or the string "0"; otherwise, it is TRUE.

4.6 PHP Objects


An object is a data type that not only allows storing data but also information on, how to process that data.
An object is a specific instance of a class which serve as templates for objects. Objects are created based on
this template via the new keyword.
Every object has properties and methods corresponding to those of its parent class.

4.7 NULL
The special NULL value is used to represent empty variables in PHP. A variable of type NULL is a variable
without any data. NULL is the only possible value of type null.

4.8 RESOURCE
A resource is a special variable, holding a reference to an external resource. Resource variables typically
hold special handlers to opened files and database connections.

4.9 Arithmetic Operators and Expressions

PHP has the usual (for C-based programming languages) collection of arithmetic operators (+, -, *, /, %, ++,
and --).If either operand is a double, the operation is double and a double result is produced .
4
5

4.10 String Operations

The only string operator is the concatenation operator (.) ,used to put two string values together. To
concatenate two string variables together, use the concatenation operator.
6

4.11 Scalar Type Conversions

PHP includes both implicit and explicit type conversions. Implicit type conversions are called
coercions. The context can cause a coercion of the type of the value of the expression. Whenever a numeric
value appears in string context, the numeric value is coerced to a string. whenever a string value appears in
numeric context, the string value is coerced to a numeric value. If the string contains a period, an e, or an E,
it is converted to double; otherwise, it is converted to an integer. When a double is converted to an integer,
the fractional part is dropped; rounding is not done.

Explicit type conversions can be specified in three ways.

Using the syntax of C, an expression can be cast to a different type. The cast is a type name in parentheses
preceding the expression. For example, if the value of $sum is 4.777, the following produces 4:
(int)$sum.
7

Another way to specify explicit type conversion is to use one of the functions intval, doubleval, or strval.
For example, if $sum is still 4.77 7, the following call returns 4:

intval($sum)

The third way to specify an explicit type conversion is the settype function, which takes two parameters: a
variable and a string that specifies a type name. For example, if $sum is still 4 . 777, the following statement
converts the value of $sum to 4 and its type to integer:

settype($sum, "integer");

5. Output
The print function is used to create simple unformatted output. It can be called with or without parentheses
around its parameter.

Legal statements example

print "Apples are red <br /> Kumquats aren't <br />";

print( 47 ); produce 47

print "The result is: $result <br />";

The general form of a call to printf is as follows:

printf (literal_string, param l, param 2, ...)

The literal string can include labeling information about the parameters whose values are to be displayed.

It also contains format codes for those values. The form of the format codes is a percent sign (%) followed
by a field width and a type specifier. The most common type specifiers are s for strings, d for integers, and f
for floats and doubles.

Consider the following examples:

% 10 s—a character string field of 10 characters

%6d—an integer field of 6 digits

%5. 2f—a float or double field of 8 spaces, with two digits to the right of the decimal point, the decimal
point, and 5 digits to the left.

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

<!DOCTYPE html PUBLIC "-//w3c//DTD XHTML 1.1 //EN"


"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns = "http://www.w3.org/1999/xhtml"> <head>

<title> today.php </title> </head>

<body>

<p>

<?php
8

print "<b>Welcome to my home page <br /> <br />";

print "Today is:</b>date("Y/m/d"); print "<br />";

?>

</p>

</body>

</html>

OUTPUT

Welcome to my Home Page

Today is 2014/09/24

NB: Try, date(l,F,jS)=>Saturday June 1st

6. Control Statements
6.1 Relational Operators

PHP uses the eight relational operators of JavaScript. The usual six (>, <, >=, <=, ! =, and ==) have the usual
meanings. It also has ===, which produces TRUE only if both operands are the same type and have the same
value, and ! ==, the opposite of ===.

6.2 Boolean Operators

There are six Boolean operators: and, or, xor, !, &&, and | |. The and and && operators perform the same
operation, as do or and | |.

6.3 Selection Statements


if

PHP’s if statement is like that of C.The control expression can be an expression of any type,but its value
coerced to Boolean.The controlled statement segment can be either a single statement or a compound
statement.An is can include any number of elseif clauses

Example of an if construct:

if ($day == "Saturday" || $day == "Sunday")

{$today = "weekend”};

else

{$today = "weekday";}

switch

switch (n) {
case label1:
code to be executed if n=label1;
break;
9

case label2:
code to be executed if n=label2;
break;
case label3:
code to be executed if n=label3;
break;
...
default:
code to be executed if n is different from all labels;
}

6.4 Loop Statements


Loop statements are while, for, do-while and foreach statement

while

Compute the factorial of $n

$fact=1;

$count=1

While($count<$n) {

$count++;

$fact *=$count;

do-while

computes the sum of the positive integers up to 100using do while

$count = 1;

$sum = 0;

do

$sum += $count;

$count++;

} while ($count <= 100);

for
10

for($count=1,$fact=1;$count<$n;$count++)

$fact *=$count;

Break and continue

The break statement can be used to terminate the execution of a for, foreach, while, or do-while construct.
The continue statement is used in loop constructs to skip the remainder of the current iteration but continue
execution at the beginning of the next.

7 .PHP Arrays
• In PHP, there are three kind of arrays:

• Numeric array - An array with a numeric index


• Associative array - An array where each ID key is associated with a value

• Multidimensional array - An array containing one or more arrays

7.1 Array creation

7.2 Accessing Array elements

7.3 Functions dealing with Arrays

7.4 Sequential Access to Array

7.5 Sorting Arrays

7.1 Numeric Arrays creation

• A numeric array stores each array element with a numeric index.

• There are two methods to create a numeric array.

• The assignment operation creates scalar variables. The same operation works for arrays —assigning
a value to an element of an array that does not yet exist creates the array.

• For example, assuming no array named $list currently exists, the following statement creates
one:$list[0] = 17;

• If the script has a scalar variable named $list prior to this assignment, $list is now an array.

• If the array currently has no elements with numeric keys, the value 0 is used. For example, in the
following code, the second element's subscript will be 2:
11

• $list[l] = "Today is my birthday!"; $list[] = 42;

• The second way to create an array is with the array construct.

• In the following example the index is automatically assigned (the index starts at 0):

$list==array(17,24,45,91);

The elements are stored like this

Array construct can be used to create empty array.in the following statement $list becomes an array
variable with no element.

7.2 Accessing Array Elements

Individual array elements can be accessed by subscrpting. The value in the subscript (enclosed in brackets)
is the key of the value being referenced. For example ,the value of the element whose key is “mary” in the
$ages array can be set to 29 with the following statement:

$ages[‘Mary’]=29;

In the following example you access the variable values by referring to the array name and index:

• The code above will output:

PHP Associative Arrays


12

• With an associative array, each ID key is associated with a value.

• When storing data about specific named values, a numerical array is not always the best way to do
it.

> With associative arrays we can use the values as keys and assign values to them

• In this example we use an array to assign ages to the different persons:

• This example is the same as the one above, but shows a different way of creating the array:

PHP Multidimensional Arrays

• In a multidimensional array, each element in the main array can also be an array.And each element in
the sub-array can be an array, and so on.
13
14

7.3 Functions dealing with Arrays

A whole array can be deleted with unset, as with a scalar variable. Individual elements of an array also can
be removed with unset, as in the following:

$list = array(2, 4, 6, 8);

unset($list[2]);

Now $list has three remaining elements with keys 0,1, and 3 and elements 2, 4, and 8.

The collection of keys and the collection of values of an array can be extracted with built-in functions. The
array_keys function takes an array as its parameter and returns an array of the keys of the given array.
The returned array uses 0, 1, and so forth as its keys. The array_values function does for values what
array_keys does for keys.

For example:

$highs = array("Mon" => 74, "Tue" => 70, "Wed" => 67,"Thu" => 62,
"Fri" => 65);

$days = array_keys($highs);

$temps = array_values($highs);

Now the value of $days is ("Mon", "Tue", "Wed", "Thu", "Fri"), and

The value of $temps is (74 , 70, 67 , 62 , 65).

The existence of an element of a specific key can be determined with the array_key_exists function,
which returns a Boolean value. For example, consider the following:

$highs = array("Mon" => 74, "Tue" => 70, "Wed" => 67,"Thu" => 62,
"Fri" => 65);

if (array_key_exists("Tue", $highs))

{ $tues_high = $highs["Tue"];

print "The high on Tuesday was $tues_high <br />";

The is_array function is similar to the is_int function: It takes a variable as its parameter and returns
TRUE if the variable is an array, FALSE otherwise. The in_ array function takes two parameters an
expression and an array and returns TRUE if the value of the expression is a value in the array; otherwise, it
returns FALSE.

The number of elements in an array can be determined with the sizeof function.

For example, consider the following code:


$list = array("Bob", "Fred", "Alan", "Bozo");
$len = sizeof($list);
After executing this code, $len will be 4.
15

Note that PHP does not interpolate array elements embedded in double quoted strings.

It is able to convert between strings and arrays. These conversions can be done with the implode and
explode functions.

explode & implode

The explode function explodes a string into substrings and returns them in an array.The delimiters of the
substrings are defined by the first parameter to explode, which is a string; the second parameter is the string
to be converted. For example, consider the following:

$str = "April in Paris, Texas is nice";

$words = explode(" ", $str);

$words contains ("April", "in", "Paris,", "Texas", "is", "nice").

The implode function does the inverse of explode. Given a separator character (or string) and an array, it
catenates the elements of the array together, using the given separator string between the elements, and
returns the result as a string.

$words = array("Are", "you", “coming", "tonight");

$str = implode(" ", $words);

$str has "Are you coming tonight".

Internal structure of Arrays

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 keyhashing 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. The elements all have links that connect them in the order in
which they were created, which allows them to be accessed in that order if the keys are strings and in the
order of their keys if the keys are numbers.

Logical internal structure of arrays


16

7.4 Sequential Access to Array

PHP includes different ways to access array elements in sequential order. Every array has an internal
pointer, or marker, that references one element of the array called the "current" pointer. current pointer is
initialized to reference the first element of the array at the time the array is created.

$cities = array("Hoboken", "Chicago", "Moab", "Atlantis");

$city = current($cities);

print("The first city is $city <br />");

This code produces the following:


The first city is Hoboken

current() & next()

The "current" pointer can be moved with the next function, which both moves the pointer to the next array
element and returns the value of that element. If the "current" pointer is already pointing at the last element
of the array, next returns FALSE.

For example, if the "current" pointer is referencing the first element of the $cities array, the following code
produces a list of all of the elements of that array:

$city = current($cities);

print("$city <br />");

while ($city = next($cities))

print("$city <br />");

NB: creates problem when array includes an element with false value. each function avoids this problem.

each function

The each function, which returns a two-element array consisting of the key and the value of the "current"
element .It returns FALSE only if the "current" pointer has gone past the last element of the array. difference
between each and next .

- each returns the element being referenced by the "current" pointer and then moves that pointer.

- next function first moves the "current" pointer and then returns the value being referenced by the
"current" pointer.

consider the following code:

$salaries = array("Mike" => 4250,"Jery" => 5250,"Fred" => 3792);

while ($employee = each($salaries))

{$name = $employee["key"];

$salary = $employee["value"];

print("The salary of $name is $salary <br />");


17

prev(), reset(), end(), key()

• The "current" pointer can be moved backward (that is, to the element before the "current" element)
with the prev function.

• Like the next function, the prev function returns the value of the element referenced by the "current"
pointer after the pointer has been moved.

• The "current" pointer can be set to the first element with the reset function, which also returns the
value of the first element. It can be set to the last element of the array with the end function, which
also returns the value of the last element.

• The key function, when given the name of an array, returns the key of the "current" element of the
array.

array_push() and array_pop()

The array_push and array_pop functions provide a simple way to implement a stack in an array.

The array_push function takes as its first parameter an array. After this first parameter, there can be any
number of additional parameters. The values of all subsequent parameters are placed at the end of the array.
The array_push function returns the new number of elements in the array. The array_pop function takes a
single parameter, the name of an array. It removes the last element from the array and returns it. The value
NULL is returned if the array is empty.

foreach statement

• The foreach statement is designed to build loops that process all of the elements of an array.

• This statement has two forms:

foreach (array as scalar_variable) loop body

foreach (array as key => value) loop body

• In the first form, one of the array's values is set to the scalar variable for each iteration of the loop
body.

For example:

foreach (Slist as $temp)

print("$temp <br />");

• This code will produce the values of all of the elements of $list .

The second form of foreach provides both the key and the value of each element of the array.

Syntax:

foreach (array as key => value) loop body

For example:
18

$lows = array("Mon" => 23, "Tue" => 18, "Wed" => 27);

foreach ($lows as $day => $temp)

print("The low temperature on $day was $temp <br />");

7.5 Sorting Arrays

Sort()

The sort function, which takes an array as a parameter, sorts the values in the array, replacing the keys with
the numeric keys, 0, 1, 2, ..... The array can have both string and numeric values. The string values migrate to
the beginning of the array in alphabetical order. The numeric values follow in ascending order.

asort()

The asort function is used to sort arrays that correspond to Perl hashes. It sorts the elements of a given array
by their values but keeps the original key/ value associations.As with sort, string values all appear before the
numeric values, in alphabetical order. The numeric values follow in ascending order.

ksort()

The ksort function sorts its given array by keys, rather than values. The key/value associations are
maintained by the process.

The rsort,arsort and krsort functions behave like the sort,assort and ksort functions respectivelyexcept that
they sort into the reverse order of their counterparts.

<!DOCTYPE html>

<!—sorting.php>

<html lang=”en”>

<head>

<title>sorting</title>

<meta charset=”utf-8” />

</head>
19

8. Functions
8.1 General characteristics of functions
20

PHP supports user-defined functions.The general form of a PHP function definition is as follows:

function name( [parameters] ) { }

Function names are not case sensitive. So, you cannot have a function named sum and another named Sum.
The return statement is used in a function to specify the value to be returned to the caller.If no return
statement no value returned.

8.2 Parameters

The parameters in the call to a function actual parameters. The parameters that are listed in the function
definition formal parameters. The number of actual parameters in a call to a function does not need to
match the number of formal parameters defined in that function. If there are too few actual parameters in a
call, the corresponding formal parameters will be unbound variables. If there are too many actual
parameters, the excess parameters will be ignored.

pass-by-value

Default parameter-passing mechanism of PHP is pass by value. The values of actual parameters are copied
into the memory locations associated with the corresponding formal parameters in the called function. The
values of the formal parameters are never copied back to the caller, so passing by value a one-way
communication to the function.

function max_abs($first, $second)

{$first = abs($first);

$second = abs($second);

if ($first >= $second)

return $first;

else

return $second;}

Pass-by-reference

• Pass-by-reference parameters can be done in PHP in two ways.

• One way is to add an ampersand (&) to the beginning of the name of the formal parameter that you
want to be passed by reference.

• The other way is to add an ampersand to the actual parameter in the function call.

function set_max(&$max, $first, $second)

{ if ($first >= $second)

$max = $first;

else

$max = $ second;

}
21

In this example, the first actual parameter in the caller is set to the larger of the second and third parameters.

The Scope & Lifetime of Variables

The default scope of a variable defined in a function is local. If a variable defined in a function has the same
name as a variable used outside the function, there is no interference between the two. A local variable is
visible only in the function in which it is used.

In some cases it is convenient for the code in a function to be able to access a variable that is defined outside
the function. For this,PHP has the global declaration. When a variable is listed in a global declaration in a
function, that variable is expected to be defined outside the function. So, such a variable has the same
meaning inside the function as outside.

8.4 The lifetime of variables


22

The default lifetime of local variables in a PHP function is from the time the variable is first used (that is,
when storage for it is allocated) until the function's execution terminates. The lifetime of a static variable in
a function begins when the variable is first used in the first execution of the function. Its lifetime ends when
the script execution ends. static declaration can include an initial value,which is only assigned the first time
the declaration is reached.

displays the number of times it has been called, even if it is called from several different places. The fact that
its local variable $count is static allows this to be done.

9. Pattern Matching
PHP includes two different kinds of string pattern matching using regular expressions: one that is based on
POSIX regular expressions and one that is based on Perl regular expressions.

The POSIX regular expressions are compiled into PHP, but the Perl-Compatible Regular Expression
(PCRE) library must be compiled before Perl regular expressions can be used.

The preg_match function takes two parameters, the first of which is the Perl-style regular expression as a
string. The second parameter is the string to be searched.

if (preg_match("/"PHP/", $str))

print "\$str begins with PHP <br />";

else

print "\$str does not begin with PHP <br />";

The preg_split function operates on strings but returns an array and uses patterns. preg_split takes two
parameters, the first of which is a Perl-style pattern as a string. The second parameter is the string to be split.

For example, consider the following sample code:

$fruit_string = "apple : orange : banana";

$fruits = preg_split("/ : /", $fruit_string);

The array $ fruits now has ( "apple", "orange", "banana").

<!DOCTYPE html>
23

<html lang=”en”>

<head>

<title> word_table.php </title>

<meta charset=”utf-8” />

</head>
24

10. Form handling


• when PHP is used for form handling, the PHP script is embedded in an XHTML document, like
other uses of PHP.

• The recommended approach is to use the implicit arrays for form values, $_POST and $_GET.

• These arrays have keys that match the form element names and values that were input by the client.

• For example, if a form has a text box named phone and the form method is POST, the value of that
element is available in the PHP script as follows:

$_POST["phone"]

• The built-in $_GET function is used to collect values from a form sent with method="get".

> Information sent from a form with the GET method is visible to everyone and has limits on the amount of
information to send (max. 100 characters).

Notice how the URL carries the information after the file name.

PHP Forms - $_POST Function

And here is what the code of action.php might look like:


25

• Apart from htmlspecialchars() and (int), it should be obvious what this does. htmlspecialchars()
makes sure any characters that are special in html are properly encoded so people can't inject HTML
tags or Javascript into your page.

• For the age field, since we know it is a number, we can just convert it to an integer which will
automatically get rid of any stray characters. The $_POST['name'] and $_POST['age'] variables are
automatically set for you by PHP.

• When to use method="post"?

• > Information sent from a form with the POST method is invisible to others and has no limits on the
amount of information to send.

• > However, because the variables are not displayed in the URL, it is not possible to bookmark the
page.

Simple php program

Wt12.php

<!DOCTYPE html>

<html lang=”en”>

<head>

<title> A Simple math calculator </title>

<meta charset=”utf-8” />

</head>

<body>Insert two numbers in the form and hit submit button <br>

<form action="calculation.php" method="post">

Firstnumber: <input name="num1" type="text" /><br>

Secondnumber: <input name="num2" type="text" />

<input type="submit" />

</form>

</body>

</html>

……………………//calculation.php

<html><head><title>Simple </title></head><body>

<?php
26

$num1 = $_POST['num1'];

$num2 = $_POST['num2'];

$a = $num1 + $num2;

$b = $num1 - $num2;

$e=sqrt($num1);

$f=pow($num1,$num2);

echo "The sum of the two numbers is ". $a;

echo "The difference of the two numbers is ". $b;

echo "The sqrt of the numbers is ". $e;

echo "The power of the numbers is ". $f;

?></body></html>

Example of PHP program which handles forms with output:popcorn.html

<!DOCTYPE html>

<html lang=”en”>

<head>

<title> Popcorn Sales form </title>

<meta charset=”utf-8” />

<style type=”text/css”>

td,th,table {border:thin solid black;}

</style>

</head>

<body>

<form action = ”http://localhost/popcorn.php” method = “POST”>

<label>Buyers Name: <input type=”text” name= ”name” ></label>

<label>Address: <input type = “text” name = “address”></label>

<table>

<tr>

<th>Product Name</th>

<th>Price</th>

<th>quantity</th>

</tr>
27

<tr>

<td>Unpopped Popcorn</td>

<td>$3.00</td>

<td><input type=”text” name=”unpop” size=”2”></td>

</tr>

<tr>

<td>Caramel Popcorn</td>

<td>$3.50</td>

<td><input type=”text” name= “caramel” size=”2”></td>

</tr></table><p>input type = “submit” value=”submit Form” /> </p>

</form></body></html>

OUTPUT:

Buyer’s Name: Anu

Street Address: Ernakulam


Product Price Quantity
Name
Unpopped $3.00
Popcorn 2

Caramel $3.50
Popcorn 2

Submit Order

The PHP script that handles the data from the form is described in popcorn3.html

<!DOCTYPE html>

<html lang=”en”>

<head>

<title> Process the popcorn.html form </title>

<meta charset=”utf-8” />

<style type =”text/css”>

td,th,table {border:thin solid black;}</style>

</head>

<body>

<?php>
29

//get form data values

$total_price=0;

$total_item=0;

$name=$_POST[“name”];

$street = $_POST[“street”];

$unpop=$_POST[“unpop”];

$caramel=$_POST[“caramel”];

$total_price= 3.0*$unpop+3.5*$caramel;

$total_items=$unpop+$caramel;

//Return the results to the browser in a table

?> Print “$name<br/>\n”,

$street<br/>\n”; Print “Thank You for

your order<br/>\n”;

<h3> Customer:</h3>

<?php
Print <b> “Your total bill is:</b> $ $total_price<br/>\n”;

?>

</body></html>

OUTPUT

Customer

Anu

Ernakulam

Thank you for your order

Your total bill is: $13


30

EXAMPLE:
REGISTRATION PAGE
<form method="post" action="">

// if action of set as null then the page will redirect to itself


<table>
<tr><td>Name: </td><td>
31

<input type="text" name="name"></td></tr>


<tr><td>Address:</td><td>

<textarea name="address"></textarea></td></tr>
<tr><td>
Gender:</td><td>
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
</td></tr>
<tr><td></td><td><input type="submit" name="submit“
value="Submit"></td></tr>
</table>
</form>

// Storing registration details into database


<?php
if(isset($_POST['submit']))

{ // Check if we click on SUBMIT BUTTON


$servername = "localhost";
$username = "root";
$password = "";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}// insert Query

$sql = "INSERT INTO register(name,address,gender) VALUES


('$_POST[name]', '$_POST[address]', '$_POST[gender]')";
if ($conn->query($sql) === TRUE) {
echo "Registration Completed successfully!";
} else {
echo "Error: " . $sql . "<br />" . $conn->error;
}$conn->close();}?>

11. FILES

All file operations in PHP are implemented as functions.

11.1 Opening and Closing Files

11.2 Reading from a file

11.3 Writing to a File

11.4 Locking Files

11.1Opening and Closing Files


32

The first step in some file operations is to open it, a process that prepares the file for use and associates a
program variable with the file for future reference. This program variable is called the file variable.

• For example,

$file_var = fopen("testdata.txt", "r") or

die ("Error — testdata.txt cannot be opened");

fopen & fclose

The fopen function takes two parameters: the filename, including the path to it if it is in a different directory,
and a use indicator, which specifies the operation or operations that must be performed on the file. Both
parameters are given as strings.

The fopen function returns the reference to the file for the file variable. Every open file has an internal
pointer(file pointer) that is used to indicate where the next file operation should take place within the file.
The file_exists function takes a single parameter, the file's name. It returns TRUE if the file exists, FALSE
otherwise. A file is closed with the fclose function, which takes a file variable as its only parameter.

Table File use indicators

11.2 Reading from a file

The fread function reads part or all of a file and returns a string of what was read. This function takes two
parameters: a file variable and the number of bytes to be read. The reading operation stops when either the
end-of-file marker is read or the specified number of bytes has been read. The filesize function takes a single
parameter, the name of the file (not the file variable). For example, to read the entire contents of the file
testdata.dat as a string into the variable $file_string:
33

$file_string = fread($file_var,filesize("testdata.dat"));

One alternative to fread is file, which takes a filename as its parameter and returns an array of all of the lines
of the file

$file_lines = file("testdata.dat");

PHP has another file input function that does not require calling fopen, file_get_contents, which takes the
file's name as its parameter. This function reads the entire contents of the file. For example, consider the
following call:

$file_string = file_get_contents("testdata.dat");

A single line of a file can be read with fgets, which takes two parameters: the file variable and a limit on the
length of the line to be read. Consider the following statement:

$line = fgets ( $file var, 100);

This statement reads characters from testdata.dat until it finds a newline character, encounters the end-of-file
marker, or has read 99 characters.

11.3 Writing to a File

The fwrite function takes two parameters: a file variable and the string to be written to the file. It is possible
to include a third parameter, which would be used to specify the number of bytes to be written.

The fwrite function returns the number of bytes written.

$bytes written = fwrite($file_var, $out_data);

This statement writes the string value in $out_data to the file referenced with $file_var and places the
number of bytes written in $bytes_written. Of course, this will work only if the file has been opened for
writing.

The file_put_contents function writes the value of its second parameter, a string, to the file specified in its
first parameter.

file_put_contents("savedata.dat", $str);

//test.txt //test.php

AJAX = Asynchronous <?php


JavaScript and XML $myfile =
CSS = Cascading Style fopen(“test.txt", "r")
Sheets or die("Unable to open
HTML = Hyper Text Markup file!");
Language
PHP = PHP Hypertext echo fread($myfile,filesize(“t
Preprocessor est.txt"));
SQL = Structured Query fclose($myfile);
Language ?>
SVG = Scalable Vector
Graphics
XML = EXtensible Markup
Language
34

Check End-Of-File - feof()

<?php
$myfile = fopen(“test.txt", "r") or die("Unable to open file!");

// Output one line until end-of-file


while(!feof($myfile))

{
echo fgets($myfile) . "<br />";
}
fclose($myfile);
?>

fwrite() function

<?php
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = "Doe John \n";
fwrite($myfile, $txt);
$txt = "Jane Doe\n";
fwrite($myfile, $txt);
fclose($myfile);
?>

11.4 Locking Files

 file lock prevents any other access to the file while the lock is set.

• File locking is done in PHP with the flock function, which should sound familiar to UNIX
programmers.

• The flock() function locks or releases a file.

Syntax: flock ( file, lock , block )

file Required. Specifies an open file to lock or release

lock Required. Specifies what kind of lock to use.

block Optional. Set to 1 to block other processes while locking

• LOCK_SH - Shared lock (reader). Allow other processes to access the file

• LOCK_EX - Exclusive lock (writer). Prevent other processes from accessing the file

• LOCK_UN - Release a shared or exclusive lock

• LOCK_NB - Avoids blocking other processes while locking


35

<?php

$file = fopen("test.txt","w+");

// exclusive lock

if (flock($file,LOCK_EX))

{ fwrite($file,"Write something");

// release lock

flock($file,LOCK_UN);

}else { echo "Error locking file!"; }

fclose($file); ?>

12.COOKIES

A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's
computer. Each time the same computer requests a page with a browser, it will send the cookie too. With
PHP, you can both create and retrieve cookie values.Cookies provide a general approach to storing
information about sessions on the browser system itself. The server is given this information when the
browser makes subsequent requests for Web resources from the server. Cookies allow the server to present a
customized interface to the client. They also allow the server to connect requests from a particular client to
previous requests, thereby connecting sequences of requests into a session.

A cookie is a small object of information that consists of a name and a textual value. A cookie is created by
some software system on the server.A message from a browser to a server is a request; a message from a
server to a browser is a response. The header part of an HTTP communication can include cookies. So,
every request sent from a browser to a server, and every response from a server to a browser, can include
one or more cookies.At the time it is created, a cookie is assigned a lifetime. When the time a cookie has
existed reaches its associated lifetime, the cookie is deleted from the browser's host machine. A particular
cookie is information that is exchanged exclusively between one specific browser and one specific server.

setcookie function

A cookie is set in PHP with the setcookie function. This function takes one or more parameters.

setcookie(name, value, expire, path, domain, secure, httponly)

The first parameter, which is mandatory, is the cookie's name given as a string. The second, if present, is the
new value for the cookie, also a string. If the value is absent, setcookie undefines the cookie. The third
parameter, when present, is the expiration time in seconds for the cookie, given as an integer.

The default value for the expiration time is zero, which specifies that the cookie is destroyed at the end of
the current session

setcookie("voted", "true", time() + 86400);

This call creates a cookie named "voted" whose value is "true" and whose lifetime is one day (86,400 is the
number of seconds in a day).
36

<?php
$cookie_name = "user";
$cookie_value = “admin123";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");

// 86400 = 1 day
?>
<html>
<body>

<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?></body>
</html>

The example creates a cookie named "user" with the value “admin123". The cookie will expire after 30 days
(86400 * 30). The "/" means that the cookie is available in entire website (otherwise, select the directory you
prefer). Retrieve the value of the cookie "user" (using the global variable $_COOKIE).

use the isset() function to find out if the cookie is set:

Delete a Cookie

• To delete a cookie, use the setcookie() function with an expiration date in the past:

Example

<?php
// set the expiration date to one hour ago
setcookie("user", "", time() - 3600);
?>
<html>
<body>
<?php
echo "Cookie 'user' is deleted.";
?>
</body></html>

In PHP, cookie values are treated much like form values. All cookies that arrive with a request are placed in
the implicit $_COOKIES array, which has the cookie names as keys and the cookie values as values. Most
browsers have a limit on the number of cookies that will be accepted from a particular server site. In many
cases, information about a session is needed only during the session. Rather than using one or more cookies,
a single session array can be used to store information about the previous requests of a client during a
session. In particular, session arrays often store a unique session ID for a session.

PHP Session
37

When you work with an application, you open it, do some changes, and then you close it. This is much like a
Session. The computer knows who you are. It knows when you start the application and when you end. But
on the internet the web server does not know who you are or what you do, because the HTTP address doesn't
maintain state.Session variables solve this problem by storing user information to be used across multiple
pages (e.g. username,pwd, etc). By default, session variables last until the user closes the browser.So;
Session variables hold information about one single user, and are available to all pages in one application.

Session Tracking
One significant way that session arrays differ from cookies is that they can be stored on the server, whereas
cookies are stored on the client.In PHP, a session ID is an internal value that identifies a session. Session IDs
need not be known or handled in any way by PHP scripts.

PHP is made aware that a script is interested in session tracking by calling the session_start function, which
takes no parameters. The first call to session_start in a session causes a session ID to be created and
recorded. On subsequent calls to session_start in the same session, the function retrieves the $_SESSION
array, which stores any session variables and their values that were registered in previously executed scripts
in this session.

A session is started with the session_start() function.

Session variables are set with the PHP global variable: $_SESSION.

<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html><body>
<?php
// Set session variables
$_SESSION[“uname"] = “admin";
$_SESSION[“pwd"] = “admin123";
echo "Session variables are set.";
?>
</body></html>

Modify a PHP Session Variable

To change a session variable, just overwrite it:

Example

<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// to change a session variable, just overwrite it
$_SESSION[“uname"] = “aministrator";
38

print_r($_SESSION);
?>
</body>
</html>

Destroy a PHP Session

To remove all global session variables and destroy the session, use session_unset() and
session_destroy():

Example

<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// remove all session variables
session_unset();
// destroy the session
session_destroy();
?></body>
</html>

Session key/value pairs are created or changed by assignments to the $_SESSION array. They can be
destroyed with the unset operator.

session_start();

if ($_POST[“uname"])!=“ ”)

$_SESSION[“username"] =$_POST[“uname"]) ;

print("You are visitor: $_SESSION[“username"] <br />");

Session tracking is relatively simple in PHP.

The session_start function creates a session ID. Session variables are stored in the $_SESSION array.

Sample programs in PHP


1. //Wt12.php

<html><title>A simple math calculator</title>

<body>Insert two numbers in the form and hit submit button <br>

<form action="" method="post">


39

Firstnumber: <input name="num1" type="text" /><br>

Secondnumber: <input name="num2" type="text" />

<input type="submit" />

</form>

</body>

</html>

// Reg.php

<?php

if(isset($_POST['submit']))

{$num1 = $_POST['num1'];

$num2 = $_POST['num2'];

$a = $num1 + $num2;

$b = $num1 - $num2;

$e=sqrt($num1);

$f=pow($num1,$num2);

echo "The sum of the two numbers is ". $a;

echo "The difference of the two numbers is ". $b;

echo "The sqrt of the numbers is ". $e;

echo "The power of the numbers is ". $f;

}?></body></html>

2. Program to check whether the number is Armstrong or not using function

<?php
// PHP code to check whether a number is
// armstrong number or not

// function to check whether the number is


// armstrong number or not

function armstrongCheck($number){
$sum = 0;
$x = $number;
while($x != 0)
{
$rem = $x % 10;
$sum = $sum + $rem*$rem*$rem;
$x = $x / 10;
}
40

// if true then armstrong number


if ($number == $sum)
return 1;

// not an armstrong number


return 0;
}
// Driver Code
$number = 407;
$flag = armstrongCheck($number);
if ($flag == 1)
echo "Yes";
else
echo "No"
?>

KTU QUESTION PAPER 2018

1. What are the different ways to create an array in PHP? Explain with example?

2. What is server side scripting?

3. Write a PHP program to check whether the given number is Armstrong or not?

5. Design an HTML form for entering a number by the user. Write a PHP code to display a message
indicating, whether the number is odd or even, when clicking on the submit button.

6. Write a PHP script to count the instances of words in a string?

6. What is the significance of cookies in web? How can a cookie be created and destroyed in PHP?

Write a program to find the factorial of a number

<html>

<head>

<title>Factorial Program using loop in PHP</title>

</head>

<body>

<form method="post">

Enter the Number:<br>

<input type="number" name="number" id="number">

<input type="submit" name="submit" value="Submit" />

</form>

<?php
41

$fact = 1;

//getting value from input text box 'number'

$number = $_POST['number'];

echo "Factorial of $number:<br /><br />";

//start loop

for ($i = 1; $i <= $number; $i++){

$fact = $fact * $i;

echo $fact . "<br />";

?>

</body>

</html>

OR

<?php

$num = 4;
$factorial = 1;
for ($x=$num; $x>=1; $x--)
{
$factorial = $factorial * $x;
}
echo "Factorial of $num is $factorial";

?>
OUTPUT

Factorial of 4 is 24

Write a program to swap two numbers

<?php

$a=10;
$b=20;

echo "Value of a: $a</br>";

Prepared by Theresa Jose, Asst. Professor Dept. of CSE, ICET


42

echo "Value of b: $b</br>";

$temp=$a;
$a=$b;
$b=$temp;

echo "Value of a: $a</br>";


echo "Value of b: $b</br>";

?>

Output

Value of a: 10

Value of b: 20

Value of a: 20

Value of b: 10

Write a program to check whether the number is odd or even


<?php

$num=10;

if($num%2==0)
{
echo "Even number";
}
else
{
echo "Odd number";
}

?>

OUTPUT

Even number
43

Write a program to find the reverse of a number

<?php

$num = 2039;
$revnum = 0;
while ($num != 0)
{
$revnum = $revnum * 10 + $num % 10;
//below cast is essential to round remainder towards zero
$num = (int)($num / 10);
}

echo "Reverse number: $revnum";

?>
OUTPUT

Reverse number: 9302

Write a program to find the reverse of string


<?php

$string = "hitesh";
$length = strlen($string);

for ($i=($length-1) ; $i >= 0 ; $i--)


{
echo $string[$i];
}

?>
OUTPUT
hsetih

Write a program to print the Fibonacci series using function

<?php
44

function printFibonacci($n)
{

$first = 0;
$second = 1;

echo "Fibonacci Series \n";

echo $first.' '.$second.' ';

for($i = 2; $i < $n; $i++){

$third = $first + $second;

echo $third.' ';

$first = $second;
$second = $third;

}
}

/* Function call to print Fibonacci series upto 6 numbers. */

printFibonacci(6);

?>

Output

Fibonacci Series 0 1 1 2 3 5
JavaScript
TOPICS
• Overview of JavaScript
• Object Orientation and JavaScript
• Syntactic Characteristics
• Primitives
• Operations
• Expressions
• Screen Output and Keyboard Input
• Control Statements
• Object Creation and Modification
• Arrays
• Functions
• Constructors
• Pattern Matching
ORIGINS AND EVOLUTION OF JAVASCRIPT
• JavaScript was originally developed at Netscape by Brendan Eich in 1995
JAVASCRIPT

• Java!=JavaScript
• Uses:
GENERAL SYNTACTIC CHARACTERISTICS
• JavaScript code is inserted between <script> and </script> tags when used
in an HTML document
• Scripts can be placed inside the body or the head section of an HTML page or
inside both the head and body
• JavaScript can also be used in external files. The file extension of the
JavaScript file should be .js.
• To use an external script put the name of the script file in the src attribute of a
script tag. External scripts cannot contain script tags.
GENERAL SYNTACTIC CHARACTERISTICS
Identifiers:
• Identifiers must begin with a letter, an underscore (_), or a dollar
• Subsequent characters may be letters, underscores, dollar signs, or digits
• There is no length limitation for identifiers
• Case sensitive

Comments:
• Single line: //
• Multiline: /* */
GENERAL SYNTACTIC CHARACTERISTICS
• Reserve words:

• Safe way to organize JavaScript statements is to put each on its own line
whenever possible and terminate each statement with a semicolon
PRIMITIVE TYPES
• JavaScript primitive types: : Number, String, Boolean, Undefined, Null
• Number, String, and Boolean have wrapper objects

In the cases of Number and String, primitive


• values and objects are coerced back and forth so that primitive values can be treated
essentially as if they were objects
• All numeric values are stored in double-precision floating point

• String literals are delimited by either ' or "


• Can include escape sequences (e.g., \t)
PRIMITIVE TYPES
• Boolean values are true and false
• The only Null value is null
• The only Undefined value is undefined

• Numeric operators: unary +,-, ++,-- , binary +,-*,/, %


Variables:
• JavaScript is dynamically typed - The interpreter determines the type of a particular
occurrence of a variable
• 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.
• Variables can be either implicitly or explicitly declared
• In many cases, the interpreter converts the type of a value to whatever is needed for the context
in which it appears.

• var sum = 0,
today = "Monday",
flag = false;
THE MATH OBJECT
• It provides a collection of properties of Number objects and methods that operate on
Number object
• It has methods for:
• trigonometric functions, such as sin
• To truncate a number floor
• To round a number round
• To return the largest of two given numbers max
• All of the Math methods are referenced through the Math object: Math.sin(x)
THE NUMBER OBJECT
• It includes a collection of useful properties that have constant values

• 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 a number that is too
large returns the value “not a number,” which is displayed as NaN
THE NUMBER OBJECT
• The toString method converts the number through which it is called to a string.
• Because numeric primitives and Number objects are always coerced to the other when
necessary, toString can be called through a numeric primitive
• Example: price.toString();
THE STRING CATENATION OPERATOR
• String catenation is specified with the operator denoted by a plus sign (+)
• Example: “hello”+”abc”
IMPLICIT TYPE CONVERSION
• When a value of one type is used in a position that requires a value of a different type,
JavaScript attempts to convert the value to the type that is required
• When used as a number, null is 0
• When used as a number, undefined is interpreted as NaN.
EXPLICIT TYPE CONVERSION
• Number to string conversion
• Using String() constructor
• toString() method

• //string to number conversion


• Number constructor
• by subtracting zero from the string
• parseInt(), parseFloat()
STRING PROPERTIES AND METHODS
• String methods can always be used through String primitive values, as if the values were
objects because of coercion
• length property: gives number of characters in a string
• String Methods:
THE TYPEOF OPERATOR
• returns the type of its single operand
• produces "number","string", or "boolean" if the operand is of primitive type Number,
String, or Boolean, respectively
• If the operand is an object or null, typeof produces "object“ => Objectsdo not have
types
• If the operand is a variable that has not been assigned a value, typeof produces
"undefined", reflecting the fact that variables themselves are not typed
• typeof operator always returns a string
• typeof x and typeof(x) are equivalent
ASSIGNMENT STATEMENTS
• simple assignment operator =
• compound assignment operators +=
THE DATE OBJECT
• A Date object is created with the new operator and the Date constructor
• var today = new Date();
• Builds an object with the current date and time for its properties

• Date methods:
SCREEN OUTPUT AND KEYBOARD INPUT
• The normal output screen for JavaScript is the same as the screen in which the
content of the host HTML document is displayed
• JavaScript models the HTML document with the Document object
• The window in which the browser displays an HTML document is modeled with
the Window object
• The Window object includes two properties, document and window.
• The document property refers to the Document object.
• The window property is self-referential; it refers to the Window object.
SCREEN OUTPUT AND KEYBOARD INPUT
• The Document object has several properties and methods.
• write(): used to create output, which is dynamically created HTML document
content
• The parameter of write can include any HTML tags and content
• write often includes <br />
• The write method actually can take any number of parameters.
• Multiple parameters are catenated and placed in the output
• The writeln() method implicitly adds "\n" to its parameter, but since browsers
ignore line breaks when displaying HTML, it has no effect on the output
SCREEN OUTPUT AND KEYBOARD INPUT
• Window includes three methods that create dialog boxes for three specific kinds
of user interactions
• The default object for JavaScript is the Window object currently being displayed,
so calls to these methods need not include an object reference.
• Methods: alert, confirm, and prompt
SCREEN OUTPUT AND KEYBOARD INPUT
alert():
• It opens a dialog window and displays its parameter in that window.
• It also displays an OK button.
• The string parameter of alert is not HTML code; it is plain text. Therefore, the
string parameter of alert may include \n but never should include <br />
SCREEN OUTPUT AND KEYBOARD INPUT
confirm():
• It opens a dialog window in which the method displays its string parameter,
along with two buttons: OK and Cancel
• confirm returns a Boolean value that indicates the user’s button input: true for OK
and false for Cancel.
• This method is often used to offer the user the choice of continuing some
process
• After the user presses one of the buttons in the confirm dialog window, the script
can test the variable and react accordingly
SCREEN OUTPUT AND KEYBOARD INPUT
prompt():
• creates a dialog window that contains a text box used to collect a string of input from
the user, which prompt returns as its value
• this window also includes two buttons: OK and Cancel
• Prompt takes two parameters: the string that prompts the user for input and a default
string in case the user does not type a string before pressing one of the two buttons.
• In many cases, an empty string is used for the default input.
• alert, prompt, and confirm cause the browser to wait for a user response. In the case
of alert, the OK button must be pressed for the JavaScript interpreter to continue. The
prompt and confirm methods wait for either OK or Cancel to be pressed
CONTROL STATEMENTS
Control Expressions
• The expressions upon which statement flow control can be based
• They include primitive values, relational expressions, and compound expressions
• The result of evaluating a control expression is one of the Boolean values true and false
• If the value of a control expression is a string, it is interpreted as true unless it is empty string
(“ “)
• If the value is a number, it is true unless it is zero (0)
• If the special value, NaN, is interpreted as a Boolean, it is false.
• If undefined is used as a Boolean, it is false.
• When interpreted as a Boolean, null is false.
• When interpreted as a number, true has the value 1 and false has the value 0
Relational operators:
Strict equality vs Loose equality:
• The loose equality operator ‘==’ allows us to compare two or more operands by
converting their value to a common type first and then checking for the equality
between them
• If one operand is a string and the other is a number, Java Script attempts to convert the
string to a number. If one operand is Boolean and the other is not, the Boolean value is
converted to a number (1 for true, 0 for false)

• Strict equality operator ‘===’ allows us to compare two or more operands by


checking the equality between the values as well as their types . It returns true only
if the values and the type both match with the other operand
Operator precedence and associativity quality:
Selection Statements: if
The switch Statement
• The control expression of a switch statement could evaluate to a number, a string, or a
Boolean value.
• Case labels also can be numbers, strings, or Booleans,
• Different case values can be of different types
Loop Statements
while loop:

do while

for loop:
OBJECT CREATION AND MODIFICATION
• Objects are often created with a new, which must include a call to a constructor
method
• constructor that is called in the new expression creates the properties that characterize the
new object

• The constructor both creates and initializes the properties


var my_object = new Object();
• It creates an object that has no properties
OBJECT CREATION AND MODIFICATION
var my_car = new Object(); // Creates an Object object
my_car.make = "Ford"; // Creates and initializes the make property
my_car.model = "Fusion"; // Creates and initializes model

var my_car = {make: "Ford", model: "Fusion"};

• We can create a new object that is a property of my_car with properties of its own
my_car.engine = new Object();
my_car.engine.config = "V6";
my_car.engine.hp = 263;
OBJECT CREATION AND MODIFICATION
Accessing properties:
• object-dot-property notation: my_car.make
• Array notation: my_car[“make”];

• A property can be deleted with delete: delete my_car.model;

• for-in, can be used for listing the properties of an object


for (identifier in object)
statement or compound statement

Objects are mutable: They are addressed by reference, not by value.


ARRAYS
• An array is an ordered list of values
• Array elements can be primitive values or references to other objects
• JavaScript arrays have dynamic lengths
• They can contain a mix of different data types
ARRAY OBJECT CREATION
• An array object can be created in two distinct ways
1. Using new operator
• var my_array = new Array(1, 2, "three", "four");
//Array object of length 4 is created , initialized

• var my_array2 = new Array(100);


//Array object of length 100 is created, without actually creating any elements

• Whenever a call to the Array constructor has a single parameter, that parameter is
taken to be the number of elements, not the initial value of a one-element array
ARRAY OBJECT CREATION
2. Using literal array value
var my_array = [1, 2, "three", "four"];
ARRAY OBJECT CHARACTERISTICS

• The lowest index of every JavaScript array is zero


• The length of an array is the highest subscript to which a value has been assigned,
plus 1
• if my_list is an array with four elements and my_list[47] = 2222; is executed, the new
length of my_list will be 48
• length property is created for every array object by the Array constructor.
• length of an array is both read and write accessible
• my_list.length = 1002;
• Assigning a value to the length property can lengthen, shorten, or not affect the
array’s length
ARRAY OBJECT CHARACTERISTICS

• Only the assigned elements of an array actually occupy space


• If it is convenient to use the subscript range of 100 to 150, an array of length 151 can
be created; But if only the elements indexed 100 to 150 are assigned values, the array
will require the space of 51 elements
• The length property of an array is not necessarily the number of elements allocated
• new_list.length = 1002;
• sets the length property of new_list to 1002, but new_list may have no elements that
have values or occupy space
ARRAY METHODS

join()
• The join method converts all of the elements of an array to strings and catenates them
into a single string
• If no parameter is provided to join, the values in the new string are separated by
commas
• If a string parameter is provided, it is used as the element separator

reverse():
• It reverses the order of the elements of the Array object through which it is called.
ARRAY METHODS

sort()
• It coerces the elements of the array to become strings if they are not already strings
and sorts them alphabetically
concat()
• It catenates its actual parameters to the end of the Array object on which it is called
ARRAY METHODS

slice()
• It returns the part of the Array object specified by its parameters, which are used as
subscripts
• The array returned has the elements of the Array object through which it is called,
from the first parameter up to, but not including, the second parameter
• If slice is given just one parameter, the array that is returned has all of the elements of
the object, starting with the specified index
toString()
• each of the elements of the object is converted (if necessary) to a string. These strings
are catenated, separated by commas.
ARRAY METHODS

pop()
• It removes an element from the end
push()
• It inserts an element to the end
shift()
• It removes an element from the beginning of an array
unshift()
• It adds an element to the beginning of an array
FUNCTIONS

A JavaScript function is a block of code designed to perform a particular task


FUNCTIONS

• A return statement returns control from the function in which it appears to the
function’s caller
• Optionally, it includes an expression, whose value is returned to the caller
• If there are no return statements in a function or if the specific return that is executed
does not include an expression, the value returned is undefined
• This is also the case if execution reaches the end of the function body without
executing a return statement
FUNCTIONS

• JavaScript functions are objects, so variables that reference them can be treated as are
other object references
• They can be passed as parameters, be assigned to other variables, and be the
elements of an array
• The interpreter sees the definition of a function before it sees a call to the function
FUNCTIONS-LOCAL VARIABLE

• Variables that are implicitly declared have global scope-even if the implicit
declaration occurs within a function definition
• Variables that are explicitly declared outside function definitions also have global
scope
• Any variable explicitly declared with var in the body of a function has local scope
• If a variable that is defined both as a local variable and as a global variable appears in
a function, the local variable has precedence, effectively hiding the global variable
with the same name
FUNCTIONS-PARAMETERS

• The parameter values that appear in a call to a function are called actual parameters
• The parameter names that appear in the header of a function definition are called
formal parameters
• JavaScript uses the pass-by-value parameter-passing method
• When a function is called, the values of the actual parameters specified in the call are,
in effect, copied into their corresponding formal parameters, which behave exactly
like local variables
• Because of JavaScript’s dynamic typing, there is no type checking of parameters
FUNCTIONS-PARAMETERS

• Because of JavaScript’s dynamic typing, there is no type checking of parameters


• The number of parameters in a function call is not checked against the number of
formal parameters in the called function.
• In the function, excess actual parameters that are passed are ignored; excess formal
parameters are set to undefined
• All parameters are communicated through a property array, arguments property
named length
• By accessing arguments.length, a function can determine the number of actual
parameters that were passed.
• Because the arguments array is directly accessible, all actual parameters specified in
the call are available, including actual parameters that do not correspond to any
formal parameters
FUNCTIONS-PARAMETERS

• All parameters are communicated through a property array, arguments property


named length
• By accessing arguments.length, a function can determine the number of actual
parameters that were passed
• Because the arguments array is directly accessible, all actual parameters specified in
the call are available, including actual parameters that do not correspond to any
formal parameters
sort() Revisited
• sort method for array objects converts the array’s elements to strings, if
necessary, and then sorts them alphabetically
• If we need to sort something other than strings, or if you want an array to be
sorted in some order other than alphabetically as strings, the comparison
operation must be supplied to the sort method by the caller
• Such a comparison operation is passed as a parameter to sort
sort() Revisited
• The comparison function must return a negative number if the two elements
being compared are in the desired order, zero if they are equal, and a number
greater than zero if they must be interchanged
function my_order(a,b){return a-b;}
array.sort(my_order)
• Rather than defining a comparison function elsewhere and passing its name,
the function definition can appear as the actual parameter in the call to sort
array.sort(function(a, b){return a-b};)
• Such a function is nameless and can be used only where its definition appears.
CLASSES AND CONSTRUCTORS

• The version of JavaScript (ES6) introduced the use of classes


• A class in javascript is basically a blueprint or template of the object;
New objects can be created from a class
• JavaScript constructors are special functions that create and initialize
the properties of newly created objects
• Every new expression must include a call to a constructor
• this variable is used to construct and initialize the properties of the
object
PATTERN MATCHING BY USING REGULAR
EXPRESSIONS
• JavaScript has powerful pattern-matching capabilities based on regular
expressions
• Two approaches: methods of the RegExp object and methods of the
String object
• Patterns are specified in a form that is based on regular expressions
• Patterns are sent as parameters to the pattern matching methods, are
delimited with slashes
PATTERN MATCHING BY USING REGULAR
EXPRESSIONS
• search( ) takes a pattern as a parameter
• It returns the position in the String object (through which it is called) at
which the pattern matched. If there is no match, search returns –1
• The position of the first character in the string is 0
CHARACTER AND CHARACTER-CLASS PATTERNS
• Metacharacters are characters that have special meanings in some contexts
in patterns
\ | ( ) [ ] { } ^ $ * + ? .

• Metacharacters can themselves be matched by being immediately


preceded by a backslash
PATTERN MATCHING BY USING REGULAR
EXPRESSIONS
• A . matches any character except newline
• It is often convenient to be able to specify classes of characters rather
than individual characters. Such classes are defined by placing the
desired characters in brackets
PATTERN MATCHING BY USING REGULAR
EXPRESSIONS
• In many cases, it is convenient to be able to repeat a part of a pattern,
often a character or character class.
• To repeat a pattern, a numeric quantifier, delimited by braces, is attached
• /xy{4}z/ matches xyyyyz
PATTERN MATCHING BY USING REGULAR
EXPRESSIONS
• An asterisk(*) matches zero or more repetitions
• A plus sign(+) matches one or more repetitions
• A question mark(?) matches one or none
• /x*y+z?/ matches strings with any number of x’s (including zero),
followed by one or more y’s, possibly followed by z
PATTERN MATCHING BY USING REGULAR
EXPRESSIONS
• The quantifiers are often used with the predefined character-class names
• /\d+\.\d*/ matches a string of one or more digits followed by a decimal
point and possibly more digits
• /[A-Za-z]\w*/ matches the identifiers (a letter, followed by zero or more
letters, digits, or underscores) in some programming languages
PATTERN MATCHING BY USING REGULAR
EXPRESSIONS
• It is useful to be able to specify that a pattern must match at a particular position
in a string
• A pattern is tied to a string position with an anchor
• A pattern can be specified to match only at the beginning of the string by
preceding it with a circumflex (^) anchor
• A pattern can be specified to match at the end of a string only by following the
pattern with a dollar sign anchor
• /^pearl/ matches "pearls are pretty" but does not match "My pearls are pretty“
• /gold$/ matches "I like gold" but does not match "golden"
PATTERN MATCHING BY USING REGULAR
EXPRESSIONS
• Anchors do not match specific characters in the string; rather, they match
positions
• When a circumflex appears in a pattern at a position other than the
beginning of the pattern it has no special meaning. (It matches itself.)
• Likewise, if a dollar sign appears in a pattern at a position other than the
end of the pattern, it has no special meaning
PATTERN MATCHING BY USING REGULAR
EXPRESSIONS
• Modifiers:
• They can be attached to patterns to change how they are used, thereby
increasing their flexibility
• The modifiers are specified as letters just after the right delimiter of the
pattern
• The i modifier makes the letters in the pattern match either uppercase or
lowercase letters in the string
• /Apple/i matches ‘APPLE’, ‘apple’, ‘APPle’, and any other combination of
uppercase and lowercase spellings of the word “apple.”
PATTERN MATCHING BY USING REGULAR
EXPRESSIONS
• The x modifier allows white space to appear in the pattern. Because
comments are considered white space, this provides a way to include
explanatory comments in the pattern
/\d+ # The street number
\s # The space before the street name
[A-Z][a-z]+ # The street name
/x
PATTERN MATCHING BY USING REGULAR
EXPRESSIONS
• Other Pattern-Matching Methods of String
• The replace method is used to replace substrings of the String object that
match the given pattern.
• The replace method takes two parameters: the pattern and the replacement
string.
• The g modifier can be attached to the pattern if the replacement is to be
global in the string, in which case the replacement is done for every match
in the string.
• The matched substrings of the string are made available through the
predefined variables $1, $2, and so on
PATTERN MATCHING BY USING REGULAR
EXPRESSIONS
• var str = "Fred, Freddie, and Frederica were siblings";
• str.replace(/Fre/g, “xyz");
• str is set to “xyzd, xyzddie, and xyzderica were siblings", and $1, $2, and $3
are all set to "Fre"
PATTERN MATCHING BY USING REGULAR
EXPRESSIONS
• The match method takes a single parameter: a pattern
• It returns an array of the results of the pattern-matching operation
• If the pattern has the g modifier, the returned array has all of the substrings
of the string that matched.
• If the pattern does not include the g modifier, the returned array has the
match as its first element, and the remainder of the array has the matches of
parenthesized parts of the pattern if there are any
PATTERN MATCHING BY USING REGULAR
EXPRESSIONS
• var str ="Having 4 apples is better than having 3 oranges";
• var matches = str.match(/\d/g);
• matches is set to [4, 3]

• var str = "I have 428 dollars, but I need 500";


• var matches = str.match(/(\d+)([^\d]+)(\d+)/);

The following is the value of the matches array after this code is interpreted:
• ["428 dollars, but I need 500", "428"," dollars, but I need ", "500"]
PATTERN MATCHING BY USING REGULAR
EXPRESSIONS
• The split method of String splits its object string into substrings on the basis
of a given string or pattern.
• The substrings are returned in an array
• var str = "grapes:apples:oranges";
• var fruit = str.split(":");
• fruit is set to [grapes, apples, oranges].
JAVASCRIPT Notes

JAVASCRIPT

JavaScript is the scripting language of the Web.

JavaScript is used in millions of Web pages to add functionality, validate forms, detect browsers, and
much more.

Introduction to JavaScript

JavaScript is used in millions of Web pages to improve the design, validate forms, detect browsers, create
cookies, and much more.

JavaScript is the most popular scripting language on the Internet, and works in all major browsers, such as
Internet Explorer, Mozilla Firefox, and Opera.

What is JavaScript?

 JavaScript was designed to add interactivity to HTML pages


 JavaScript is a scripting language
 A scripting language is a lightweight programming language
 JavaScript is usually embedded directly into HTML pages
 JavaScript is an interpreted language (means that scripts execute without preliminary compilation)
 Everyone can use JavaScript without purchasing a license

Java and JavaScript are two completely different languages in both concept and design!

Java (developed by Sun Microsystems) is a powerful and much more complex programming language - in
the same category as C and C++.

What can a JavaScript Do ?

 JavaScript gives HTML designers a programming tool - HTML authors are normally not
programmers, but JavaScript is a scripting language with a very simple syntax! Almost anyone can
put small "snippets" of code into their HTML pages
 JavaScript can put dynamic text into an HTML page - A JavaScript statement like this:
document.write("<h1>" + name + "</h1>") can write a variable text into an HTML page
 JavaScript can react to events - A JavaScript can be set to execute when something happens,
like when a page has finished loading or when a user clicks on an HTML element
 JavaScript can read and write HTML elements - A JavaScript can read and change the content
of an HTML element
 JavaScript can be used to validate data - A JavaScript can be used to validate form data before
it is submitted to a server. This saves the server from extra processing
 JavaScript can be used to detect the visitor's browser - A JavaScript can be used to detect the
visitor's browser, and - depending on the browser - load another page specifically designed for that
browser

Page 1
JAVASCRIPT Notes

 JavaScript can be used to create cookies - A JavaScript can be used to store and retrieve
information on the visitor's computer.

JavaScript Variables
Variables are "containers" for storing information.

JavaScript variables are used to hold values or expressions.

A variable can have a short name, like x, or a more descriptive name, like carname.

Rules for JavaScript variable names:

 Variable names are case sensitive (y and Y are two different variables)
 Variable names must begin with a letter or the underscore character

Note: Because JavaScript is case-sensitive, variable names are case-sensitive.

Example

A variable's value can change during the execution of a script. You can refer to a variable by its name to
display or change its value.

<html>
<body>
<script type="text/javascript">
var firstname;
firstname="Welcome";
document.write(firstname);
document.write("<br />");
firstname="XYZ";
document.write(firstname);
</script>

<p>The script above declares a variable,


assigns a value to it, displays the value, change the value,
and displays the value again.</p>

</body>
</html>

Output :
Welcome
XYZ

The script above declares a variable, assigns a value to it, displays the value, change the value, and
displays the value again.
Page 2
JAVASCRIPT Notes

Declaring (Creating) JavaScript Variables

Creating variables in JavaScript is most often referred to as "declaring" variables.

You can declare JavaScript variables with the var statement:

var x;
var carname;

After the declaration shown above, the variables are empty (they have no values yet).

However, you can also assign values to the variables when you declare them:

var x=5;
var carname="Scorpio";

After the execution of the statements above, the variable x will hold the value 5, and carname will hold
the value Scorpio.

Note: When you assign a text value to a variable, use quotes around the value.

Assigning Values to Undeclared JavaScript Variables

If you assign values to variables that have not yet been declared, the variables will automatically be
declared.

These statements:

x=5;
carname="Scorpio";

have the same effect as:

var x=5;
var carname="Scorpio";

Redeclaring JavaScript Variables

If you redeclare a JavaScript variable, it will not lose its original value.

var x=5;
var x;

Page 3
JAVASCRIPT Notes

After the execution of the statements above, the variable x will still have the value of 5. The value of x is
not reset (or cleared) when you redeclare it.

Page 4
JAVASCRIPT Notes

DataTypes

 Numbers - are values that can be processed and calculated. You don't enclose them in quotation
marks. The numbers can be either positive or negative.
 Strings - are a series of letters and numbers enclosed in quotation marks. JavaScript uses the string
literally; it doesn't process it. You'll use strings for text you want displayed or values you want
passed along.
 Boolean (true/false) - lets you evaluate whether a condition meets or does not meet specified
criteria.
 Null - is an empty value. null is not the same as 0 -- 0 is a real, calculable number, whereas null is
the absence of any value.

Data Types

TYPE EXAMPLE
Numbers Any number, such as 17, 21, or 54e7
Strings "Greetings!" or "Fun"
Boolean Either true or false
Null A special keyword for exactly that – the null value (that is, nothing)

JavaScript Arithmetic

As with algebra, you can do arithmetic operations with JavaScript variables:

y=x-5;
z=y+5;

JavaScript Operators
The operator = is used to assign values.

The operator + is used to add values.

The assignment operator = is used to assign values to JavaScript variables.

The arithmetic operator + is used to add values together.

y=5;
z=2;
x=y+z;

Page 5
JAVASCRIPT Notes

The value of x, after the execution of the statements above is 7.

JavaScript Arithmetic Operators

Arithmetic operators are used to perform arithmetic between variables and/or values.

Given that y=5, the table below explains the arithmetic operators:

Operator Description Example Result


+ Addition x=y+2 x=7
- Subtraction x=y-2 x=3
* Multiplication x=y*2 x=10
/ Division x=y/2 x=2.5
% Modulus (division remainder) x=y%2 x=1
++ Increment x=++y x=6
-- Decrement x=--y x=4

JavaScript Assignment Operators

Assignment operators are used to assign values to JavaScript variables.

Given that x=10 and y=5, the table below explains the assignment operators:

Operator Example Same As Result


= x=y x=5
+= x+=y x=x+y x=15
-= x-=y x=x-y x=5
*= x*=y x=x*y x=50
/= x/=y x=x/y x=2
%= x%=y x=x%y x=0

The + Operator Used on Strings

The + operator can also be used to add string variables or text values together.

To add two or more string variables together, use the + operator.

txt1="What a very";
txt2="nice day";
txt3=txt1+txt2;

Page 6
JAVASCRIPT Notes

After the execution of the statements above, the variable txt3 contains "What a verynice day".

To add a space between the two strings, insert a space into one of the strings:

txt1="What a very ";


txt2="nice day";
txt3=txt1+txt2;

or insert a space into the expression:

txt1="What a very";
txt2="nice day";
txt3=txt1+" "+txt2;

After the execution of the statements above, the variable txt3 contains:

"What a very nice day"

Adding Strings and Numbers

Look at these examples:

x=5+5;
document.write(x);

x="5"+"5";
document.write(x);

x=5+"5";
document.write(x);

x="5"+5;
document.write(x);

The rule is:

If you add a number and a string, the result will be a string.

JavaScript Comparison and Logical Operators

Comparison and Logical operators are used to test for true or false.

Page 7
JAVASCRIPT Notes

Comparison Operators

Comparison operators are used in logical statements to determine equality or difference between variables
or values.

Given that x=5, the table below explains the comparison operators:

Operator Description Example


== is equal to x==8 is false
=== is exactly equal to (value and type) x===5 is true
x==="5" is false
!= is not equal x!=8 is true
> is greater than x>8 is false
< is less than x<8 is true
>= is greater than or equal to x>=8 is false
<= is less than or equal to x<=8 is true

How Can it be Used

Comparison operators can be used in conditional statements to compare values and take action depending
on the result:

if (age<18) document.write("Too young");

You will learn more about the use of conditional statements in the next chapter of this tutorial.

Logical Operators

Logical operators are used to determine the logic between variables or values.

Given that x=6 and y=3, the table below explains the logical operators:

Operator Description Example


&& and (x < 10 && y > 1) is true
|| or (x==5 || y==5) is false
! not !(x==y) is true

Conditional Operator

JavaScript also contains a conditional operator that assigns a value to a variable based on some condition.

Page 8
JAVASCRIPT Notes

Syntax
variablename=(condition)?value1:value2

Example
greeting=(visitor=="PRES")?"Dear President ":"Dear ";

If the variable visitor has the value of "PRES", then the variable greeting will be assigned the value
"Dear President " else it will be assigned "Dear".

Conditional Statements

Very often when you write code, you want to perform different actions for different decisions. You can
use conditional statements in your code to do this.

In JavaScript we have the following conditional statements:

 if statement - use this statement if you want to execute some code only if a specified condition is
true
 if...else statement - use this statement if you want to execute some code if the condition is true
and another code if the condition is false
 if...else if....else statement - use this statement if you want to select one of many blocks of code to
be executed
 switch statement - use this statement if you want to select one of many blocks of code to be
executed

If Statement

You should use the if statement if you want to execute some code only if a specified condition is true.

Syntax
if (condition)
{
code to be executed if condition is true
}

Note that if is written in lowercase letters. Using uppercase letters (IF) will generate a JavaScript error!

Example 1
<script type="text/javascript">
//Write a "Good morning" greeting if
//the time is less than 10
var d=new Date();
var time=d.getHours();

Page 9
JAVASCRIPT Notes

if (time<10)
{
document.write("<b>Good morning</b>");
}
</script>

Example 2
<script type="text/javascript">
//Write "Lunch-time!" if the time is 11
var d=new Date();
var time=d.getHours();

if (time==11)
{
document.write("<b>Lunch-time!</b>");
}
</script>

Note: When comparing variables you must always use two equals signs next to each other (==)!

Notice that there is no ..else.. in this syntax. You just tell the code to execute some code only if the
specified condition is true.

If...else Statement

If you want to execute some code if a condition is true and another code if the condition is not true, use
the if....else statement.

Syntax

if (condition)
{
code to be executed if condition is true
}
else
{
code to be executed if condition is not true
}

Example
<script type="text/javascript">
//If the time is less than 10,
//you will get a "Good morning" greeting.
//Otherwise you will get a "Good day" greeting.
var d = new Date();

Page 10
JAVASCRIPT Notes

var time = d.getHours();

if (time < 10)


{
document.write("Good morning!");
}
else
{
document.write("Good day!");
}
</script>

If...else if...else Statement

You should use the if....else if...else statement if you want to select one of many sets of lines to execute.

Syntax
if (condition1)
{
code to be executed if condition1 is true
}
else if (condition2)
{
code to be executed if condition2 is true
}
else
{
code to be executed if condition1 and
condition2 are not true
}

Example
<script type="text/javascript">
var d = new Date()
var time = d.getHours()
if (time<10)
{
document.write("<b>Good morning</b>");
}
else if (time>10 && time<16)
{
document.write("<b>Good day</b>");
}
else

Page 11
JAVASCRIPT Notes

{
document.write("<b>Hello World!</b>");
}
</script>

The JavaScript Switch Statement

You should use the switch statement if you want to select one of many blocks of code to be executed.

Syntax
switch(n)
{
case 1:
execute code block 1
break;
case 2:
execute code block 2
break;
default:
code to be executed if n is
different from case 1 and 2
}

This is how it works: First we have a single expression n (most often a variable), that is evaluated once.
The value of the expression is then compared with the values for each case in the structure. If there is a
match, the block of code associated with that case is executed. Use break to prevent the code from
running into the next case automatically.

Example
<script type="text/javascript">
//You will receive a different greeting based
//on what day it is. Note that Sunday=0,
//Monday=1, Tuesday=2, etc.
var d=new Date();
theDay=d.getDay();
switch (theDay)
{
case 5:
document.write("Finally Friday");
break;
case 6:
document.write("Super Saturday");
break;
case 0:
document.write("Sleepy Sunday");

Page 12
JAVASCRIPT Notes

break;
default:
document.write("I'm looking forward to this weekend!");
}
</script>

JavaScript Controlling(Looping) Statements

Loops in JavaScript are used to execute the same block of code a specified number of times or while
a specified condition is true.

JavaScript Loops

Very often when you write code, you want the same block of code to run over and over again in a row.
Instead of adding several almost equal lines in a script we can use loops to perform a task like this.

In JavaScript there are two different kind of loops:

 for - loops through a block of code a specified number of times


 while - loops through a block of code while a specified condition is true

The for Loop

The for loop is used when you know in advance how many times the script should run.

Syntax

for (var=startvalue;var<=endvalue;var=var+increment)
{
code to be executed
}

Example

Explanation: The example below defines a loop that starts with i=0. The loop will continue to run as long
as i is less than, or equal to 10. i will increase by 1 each time the loop runs.

Note: The increment parameter could also be negative, and the <= could be any comparing statement.

<html>
<body>
<script type="text/javascript">
var i=0;
for (i=0;i<=10;i++)
{

Page 13
JAVASCRIPT Notes

document.write("The number is " + i);


document.write("<br />");
}
</script>
</body>
</html>

Result

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

JavaScript While Loop

Loops in JavaScript are used to execute the same block of code a specified number of times or while
a specified condition is true.

The while loop

The while loop is used when you want the loop to execute and continue executing while the specified
condition is true.

while (var<=endvalue)
{
code to be executed
}

Note: The <= could be any comparing statement.

Example

Explanation: The example below defines a loop that starts with i=0. The loop will continue to run as long
as i is less than, or equal to 10. i will increase by 1 each time the loop runs.

<html>

Page 14
JAVASCRIPT Notes

<body>
<script type="text/javascript">
var i=0;
while (i<=10)
{
document.write("The number is " + i);
document.write("<br />");
i=i+1;
}
</script>
</body>
</html>

Result

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 do...while Loop

The do...while loop is a variant of the while loop. This loop will always execute a block of code ONCE,
and then it will repeat the loop as long as the specified condition is true. This loop will always be
executed at least once, even if the condition is false, because the code is executed before the condition is
tested.

do
{
code to be executed
}
while (var<=endvalue);

Example

<html>
<body>
<script type="text/javascript">

Page 15
JAVASCRIPT Notes

var i=0;
do
{
document.write("The number is " + i);
document.write("<br />");
i=i+1;
}
while (i<0);
</script>
</body>
</html>

Result

The number is 0

JavaScript Break and Continue


There are two special statements that can be used inside loops: break and continue.

JavaScript break and continue Statements

There are two special statements that can be used inside loops: break and continue.

Break

The break command will break the loop and continue executing the code that follows after the loop (if
any).

Example

<html>
<body>
<script type="text/javascript">
var i=0;
for (i=0;i<=10;i++)
{
if (i==3)
{
break;
}
document.write("The number is " + i);
document.write("<br />");
}
</script>
</body>
Page 16
JAVASCRIPT Notes

</html>

Result

The number is 0
The number is 1
The number is 2

Continue

The continue command will break the current loop and continue with the next value.

Example

<html>
<body>
<script type="text/javascript">
var i=0
for (i=0;i<=10;i++)
{
if (i==3)
{
continue;
}
document.write("The number is " + i);
document.write("<br />");
}
</script>
</body>
</html>

Result

The number is 0
The number is 1
The number is 2
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

Page 17
JAVASCRIPT Notes

JavaScript Functions

A function (also known as a method) is a self-contained piece of code that performs a particular
"function". You can recognise a function by its format - it's a piece of descriptive text, followed by open
and close brackets.A function is a reusable code-block that will be executed by an event, or when the
function is called.

To keep the browser from executing a script when the page loads, you can put your script into a function.

A function contains code that will be executed by an event or by a call to that function.

You may call a function from anywhere within the page (or even from other pages if the function is
embedded in an external .js file).

Functions can be defined both in the <head> and in the <body> section of a document. However, to
assure that the function is read/loaded by the browser before it is called, it could be wise to put it in the
<head> section.

Example
<html>
<head>
<script type="text/javascript">
function displaymessage()
{
alert("Hello World!");
}
</script>
</head>
<body>
<form>
<input type="button" value="Click me!"
onclick="displaymessage()" >
</form>
</body>
</html>

If the line: alert("Hello world!!") in the example above had not been put within a function, it would have
been executed as soon as the line was loaded. Now, the script is not executed before the user hits the
button. We have added an onClick event to the button that will execute the function displaymessage()
when the button is clicked.

Page 18
JAVASCRIPT Notes

You will learn more about JavaScript events in the JS Events chapter.

How to Define a Function

The syntax for creating a function is:

function functionname(var1,var2,...,varX)
{
some code
}

var1, var2, etc are variables or values passed into the function. The { and the } defines the start and end of
the function.

Note: A function with no parameters must include the parentheses () after the function name:

function functionname()
{
some code
}

Note: Do not forget about the importance of capitals in JavaScript! The word function must be written in
lowercase letters, otherwise a JavaScript error occurs! Also note that you must call a function with the
exact same capitals as in the function name.

The return Statement

The return statement is used to specify the value that is returned from the function.

So, functions that are going to return a value must use the return statement.

Example

The function below should return the product of two numbers (a and b):

function prod(a,b)
{
x=a*b;
return x;
}

When you call the function above, you must pass along two parameters:

product=prod(2,3);

Page 19
JAVASCRIPT Notes

The returned value from the prod() function is 6, and it will be stored in the variable called product.

The Lifetime of JavaScript Variables

When you declare a variable within a function, the variable can only be accessed within that function.
When you exit the function, the variable is destroyed. These variables are called local variables. You can
have local variables with the same name in different functions, because each is recognized only by the
function in which it is declared.

If you declare a variable outside a function, all the functions on your page can access it. The lifetime of
these variables starts when they are declared, and ends when the page is closed.

What is an Event?

Event Handlers

Event Handlers are JavaScript methods, i.e. functions of objects, that allow us as JavaScript
programmers to control what happens when events occur.

Directly or indirectly, an Event is always the result of something a user does. For example, we've already
seen Event Handlers like onClick and onMouseOver that respond to mouse actions. Another type of
Event, an internal change-of-state to the page (completion of loading or leaving the page). An onLoad
Event can be considered an indirect result of a user action.

Although we often refer to Events and Event Handlers interchangeably, it's important to keep in mind the
distinction between them. An Event is merely something that happens - something that it is initiated by
an Event Handler (onClick, onMouseOver, etc...).

The elements on a page which can trigger events are known as "targets" or "target elements," and we can
easily understand how a button which triggers a Click event is a target element for this event. Typically,
events are defined through the use of Event Handlers, which are bits of script that tell the browser what to
do when a particular event occurs at a particular target. These Event Handlers are commonly written as
attributes of the target element's HTML tag.

The Event Handler for a Click event at a form field button element is quite simple to understand:

<INPUT TYPE="button" NAME="click1" VALUE="Click me for fun!"


onClick="event_handler_code">

The event_handler_code portion of this example is any valid JavaScript and it will be executed when the
specified event is triggered at this target element. This particular topic will be continued in Incorporating
JavaScripts into your HTML pages.

There are "three different ways" that Event Handlers can be used to trigger Events or Functions.

Method 1 (Link Events):

Page 20
JAVASCRIPT Notes

Places an Event Handler as an attribute within an <A HREF= > tag, like this:

<A HREF="foo.html" onMouseOver="doSomething()"> ... </A>

You can use an Event Handler located within an <A HREF= > tag to make either an image or a text link
respond to a mouseover Event. Just enclose the image or text string between the <A HREF= > and the
</A> tags.

Whenever a user clicks on a link, or moves her cursor over one, JavaScript is sent a Link Event. One
Link Event is called onClick, and it gets sent whenever someone clicks on a link. Another link event is
called onMouseOver. This one gets sent when someone moves the cursor over the link.

You can use these events to affect what the user sees on a page. Here's an example of how to use link
events. Try it out, View Source, and we'll go over it.

<A HREF="javascript:void('')"
onClick="open('index.htm', 'links', 'height=200,width=200');">How to Use Link Events
</A>

The first interesting thing is that there are no <SCRIPT> tags. That's because anything that appears in the
quotes of an onClick or an onMouseOver is automatically interpreted as JavaScript. In fact, because
semicolons mark the end of statements allowing you to write entire JavaScripts in one line, you can fit an
entire JavaScript program between the quotes of an onClick. It'd be ugly, but you could do it.

Here are the three lines of interest:

1. <A HREF="#" onClick="alert('Ooo, do it again!');">Click on me!</A>


2. <A HREF="javascript:void('')" onClick="alert('Ooo, do it again!');">
Click on me!
</A>
3. <A HREF="javascript:alert('Ooo, do it again!')" >Click on me!</A>

In the first example we have a normal <A> tag, but it has the magic onClick="" element, which says,
"When someone clicks on this link, run the little bit of JavaScript between my quotes." Notice, there's
even a terminating semicolon at the end of the alert. Question: is this required? NO.

Let's go over each line:

1. HREF="#" tells the browser to look for the anchor #, but there is no anchor "#", so the browser
reloads the page and goes to top of the page since it couldn't find the anchor.
2. <A HREF="javascript:void('')" tells the browser not to go anywhere - it "deadens" the link when
you click on it. HREF="javascript: is the way to call a function when a link (hyperlink or an
HREFed image) is clicked.
3. HREF="javascript:alert('Ooo, do it again!')" here we kill two birds with one stone. The default
behavior of a hyperlink is to click on it. By clicking on the link we call the window Method alert()
and also at the same time "deaden" the link.

Page 21
JAVASCRIPT Notes

The next line is

<A HREF="javascript:void('')" onMouseOver="alert('Hee hee!');">


Mouse over me!
</A>

This is just like the first line, but it uses an onMouseOver instead of an onClick.

Method 2 (Actions within FORMs):

The second technique we've seen for triggering a Function in response to a mouse action is to place an
onClick Event Handler inside a button type form element, like this:

<FORM>
<INPUT TYPE="button" onClick="doSomething()">
</FORM>

While any JavaScript statement, methods, or functions can appear inside the quotation marks of an Event
Handler, typically, the JavaScript script that makes up the Event Handler is actually a call to a function
defined in the header of the document or a single JavaScript command. Essentially, though, anything that
appears inside a command block (inside curly braces {}) can appear between the quotation marks.

For instance, if you have a form with a text field and want to call the function checkField() whenever the
value of the text field changes, you can define your text field as follows:

<INPUT TYPE="text" onChange="checkField(this)">

Nonetheless, the entire code for the function could appear in quotation marks rather than a function call:

<INPUT TYPE="text" onChange="if (this.value <= 5) {


alert("Please enter a number greater than 5");
}">

To separate multiple commands in an Event Handler, use semicolons

<INPUT TYPE="text" onChange="alert(‘Thanks for the entry.’);


confirm(‘Do you want to continue?’);">

The advantage of using functions as Event Handlers, however, is that you can use the same Event Handler
code for multiple items in your document and, functions make your code easier to read and understand.

Method 3 (BODY onLoad & onUnLoad):

The third technique is to us an Event Handler to ensure that all required objects are defined involve the
onLoad and onUnLoad. These Event Handlers are defined in the <BODY> or <FRAMESET> tag of an
HTML file and are invoked when the document or frameset are fully loaded or unloaded. If you set a flag

Page 22
JAVASCRIPT Notes

within the onLoad Event Handler, other Event Handlers can test this flags to see if they can safely run,
with the knowledge that the document is fully loaded and all objects are defined. For example:

<SCRIPT>

var loaded = false;

function doit() {
// alert("Everything is \"loaded\" and loaded = " + loaded);
alert('Everything is "loaded" and loaded = ' + loaded);
}

</SCRIPT>

<BODY onLoad="loaded = true;">


-- OR --
<BODY onLoad="window.loaded = true;">

<FORM>
<INPUT TYPE="button" VALUE="Press Me"
onClick="if (loaded == true) doit();">
-- OR --
<INPUT TYPE="button" VALUE="Press Me"
onClick="if (window.loaded == true) doit();">
-- OR --
<INPUT TYPE="button" VALUE="Press Me"
onClick="if (loaded) doit();">
</FORM>

</BODY>

The onLoad Event Handler is executed when the document or frameset is fully loaded, which means that
all images have been downloaded and displayed, all subframes have loaded, any Java Applets and Plugins
(Navigator) have started running, and so on. The onUnLoad Event Handler is executed just before the
page is unloaded, which occurs when the browser is about to move on to a new page. Be aware that when
you are working with multiple frames, there is no guarantee of the order in which the onLoad Event
Handler is invoked for the various frames, except that the Event Handlers for the parent frame is invoked
after the Event Handlers of all its children frames -- This will be discussed in detail in Week 8.

Setting the bgColor Property

The first example allows the user to change the color by clicking buttons, while the second example
allows you to change colors by using drop down boxes.

Event Handlers

Page 23
JAVASCRIPT Notes

EVENT DESCRIPTION
onAbort the user cancels loading of an image
input focus is removed from a form element (when the user clicks outside the field) or
onBlur
focus is removed from a window
onClick the user clicks on a link or form element
onChange the value of a form field is changed by the user
onError an error happens during loading of a document or image
onFocus input focus is given to a form element or a window
onLoad once a page is loaded, NOT while loading
onMouseOut the user moves the pointer off of a link or clickable area of an image map
onMouseOver the user moves the pointer over a hypertext link
onReset the user clears a form using the Reset button
onSelect the user selects a form element’s field
onSubmit a form is submitted (ie, when the users clicks on a submit button)
onUnload the user leaves a page

Note: Input focus refers to the act of clicking on or in a form element or field. This can be done by
clicking in a text field or by tabbing between text fields.

Which Event Handlers Can Be Used

OBJECT EVENT HANDLERS AVAILABLE


Button element onClick, onMouseOver
Checkbox onClick
Clickable ImageMap area onClick, onMouseOver, onMouseOut
Document onLoad, onUnload, onError
Form onSubmit, onReset
Framesets onBlur, onFocus
Hypertext link onClick, onMouseOver, onMouseOut
Image onLoad, onError, onAbort

Page 24
JAVASCRIPT Notes

Radio button onClick


Reset button onClick
Selection list onBlur, onChange, onFocus
Submit button onClick
TextArea element onBlur, onChange, onFocus, onSelect
Text element onBlur, onChange, onFocus, onSelect
Window onLoad, onUnload, onBlur, onFocus

JavaScript Arrays

An array object is used to create a database-like structure within a script. Grouping data points
(array elements) together makes it easier to access and use the data in a script. There are methods
of accessing actual databases (which are beyond the scope of this series) but here we're talking
about small amounts of data.

An array can be viewed like a


column of data in a spreadsheet. The
name of the array would be the same
as the name of the column. Each
piece of data (element) in the array
is referred to by a number (index),
just like a row number in a column.

An array is an object. Earlier, I said


that an object is a thing, a collection
of properties (array elements, in this
case) grouped together.

You can name an array using the


same format as a variable, a function or an object. Remember our basic rules: The first
character cannot be a number, you cannot use a reserved word, and you cannot use spaces.
Also, be sure to remember that the name of the array object is capitalized, e.g. Array.

The JavaScript interpreter uses numbers to access the collection of elements (i.e. the data) in
an array. Each index number (as it is the number of the data in the array's index) refers to a
specific piece of data in the array, similar to an ID number. It's important to remember that
the index numbering of the data starts at "0." So, if you have 8 elements, the first element
will be numbered "0" and the last one will be "7."

Elements can be of any type: character string, integer, Boolean, or even another array. An
array can even have different types of elements within the same array. Each element in the

Page 25
JAVASCRIPT Notes

array is accessed by placing its index number in brackets, i.e. myCar[4]. This would mean
that we are looking for data located in the array myCar which has an index of "4." Since the
numbering of an index starts at "0," this would actually be the fifth index. For instance, in the
following array,

var myCar = new Array("Chev","Ford","Buick","Lincoln","Truck");


alert(myCar[4])

the data point with an index of "4" would be Truck. In this example, the indexes are
numbered as follows: 0=Chev, 1=Ford, 2=Buick, 3=Lincoln, and 4=Truck. When creating
loops, it's much easier to refer to a number than to the actual data itself.

The Size of the Array

The size of an array is determined by either the actual number of elements it contains or by
actually specifying a given size. You don't need to specify the size of the array. Sometimes,
though, you may want to pre-set the size, e.g.:

var myCar = new Array(20);

That would pre-size the array with 20 elements. You might pre-size the array in order to set
aside the space in memory.

Multidimensional Arrays

This type of an array is similar to parallel arrays. In a multidimensional array, instead of


creating two or more arrays in tandem as we did with the parallel array, we create an array
with several levels or "dimensions." Remember our example of a spreadsheet with rows and
columns? This time, however, we have a couple more columns.

Multidimensional arrays can be created in different ways. Let's look at one of these method.
First, we create the main array, which is similar to what we did with previous arrays.
var emailList = new Array();

Next, we create arrays for elements of the main array:


Page 26
JAVASCRIPT Notes

emailList[0] = new Array("President", "Paul Smith", "[email protected]");


emailList[1] = new Array("Vice President", "Laura Stevens", "[email protected]");
emailList[2] = new Array("General Manager", "Mary Larsen", "[email protected]");
emailList[3] = new Array("Sales Manager", "Bob Lark", "[email protected]");

In this script we created "sub arrays" or arrays from another level or "dimension." We used
the name of the main array and gave it an index number (e.g., emailList[0]). Then we created
a new instance of an array and gave it a value with three elements.

In order to access a single element, we need to use a double reference. For example, to get
the e-mail address for the Vice President in our example above, access the third element "[2]"
of the second element "[1]" of the array named emailList.

It would be written like this:

var vpEmail = emailList[1][2]


alert("The address is: "+ vpEmail)
1. We declared a variable, named it emailList, and initialized it with a
value of a new instance of an array.
2. Next, we created an array for each of the elements within the original
array. Each of the new arrays contained three elements.
3. Then we declared a variable named vpEmail and initialized it with the
value of the third element ([email protected]) of the second
element "[1]" of the array named emailList.

You could also retrieve the information using something like:

var title = emailList[1][0]


var email = emailList[1][2]
alert("The e-mail address for the " + title +" is: " + email)

Page 27
JAVASCRIPT Notes

Array Properties
length

The length property returns the number of elements in an array. The format is
arrayName.length. The length property is particularly useful when using a loop to cycle
through an array. One example would be an array used to cycle banners:

var bannerImg = new Array();


bannerImg[0]="image-1.gif";
bannerImg[1]="image-2.gif";
bannerImg[2]="image-3.gif";

var newBanner = 0
var totalBan = bannerImg.length

function cycleBan() {
newBanner++
if (newBanner == totalBan) {
newBanner = 0
}
document.banner.src=bannerImg[newBanner]
setTimeout("cycleBan()", 3*1000)
}
window.onload=cycleBan;

This portion is then placed in the body where the banner is to be displayed:

&lt;img src="image-1.gif" name="banner">

Let's take a look and see what happened here:

Page 28
JAVASCRIPT Notes

1. On the first line, we created a new instance of the array bannerImg, and gave it three data
elements. (Remember, we are only making a copy of the Array object here.)
2. Next, we created two variables: newBanner, which has a beginning value of zero; and
totalBan, which returns the length of the array (the total number of elements contained in the
array).
3. Then we created a function named cycleBan. This function will be used to create a loop to
cycle the images.
a. We set the newBanner variable to be increased each time the function cycles.
(Review: By placing the increment operator [" ++ "] after the variable [the
"operand"], the variable is incremented only after it returns its current value to the
script. For example, its beginning value is "0", so in the first cycle it will return a
value of "0" to the script and then its value will be increased by "1".)
b. When the value of the newBanner variable is equal to the variable totalBan (which is
the length of the array), it is then reset to "0". This allows the images to start the
cycle again, from the beginning.
c. The next statement uses the Document Object Method (DOM - we'll be taking a look
at that soon) to display the images on the Web page. Remember, we use the dot
operator to access the properties of an object. We also read the statement backwards,
i.e., "take the element from the array bannerImg, that is specified by the current
value of the variable newBanner, and place it in the src attribute located in the
element with the name attribute of banner, which is located in the document object."
d. We then used the setTimeout function to tell the script how long to display each
image. This is always measured in milliseconds so, in this case, the function
cycleBan is called every 3,000 milliseconds (i.e., every 3 seconds).
4. Finally, we used the window.onload statement to execute the function cycleBan as soon as
the document is loaded.

There are a total of five properties for the Array object. In addition to the length property
listed above, the others are:

1. constructor: Specifies the function that creates an object's prototype.


2. index: Only applies to JavaScript arrays created by a regular expression
match.
3. input: Only applies to JavaScript arrays created by a regular expression
match.
4. prototype: Used to add properties or methods.

Page 29
JAVASCRIPT Notes

The other properties listed here are either more advanced or seldom used. For now, we'll
stick to the basics.

Javascript Object Hierarchy

Hierarchy Objects
Object Properties Methods Event Handlers
Window defaultStatus alert onLoad
frames blur onUnload
opener close onBlur
parent confirm onFocus
scroll focus
self open
status prompt
top clearTimeout
window setTimeout
History length back none
forward
go
Navigator appCodeName javaEnabled none
appName
appVersion
mimeTypes
plugins
userAgent
document alinkColor clear none (the onLoad and onUnload event handlers
anchors close belong to the Window object.
applets open
area write
bgColor writeln
cookie
fgColor
forms
images
lastModified
linkColor
links
location
referrer
title

Page 30
JAVASCRIPT Notes

vlinkColor
image border none none
complete
height
hspace
lowsrc
name
src
vspace
width
form action submit onSubmit
elements reset onReset
encoding
FileUpload
method
name
target
text defaultValue focus onBlur
name blur onCharge
type select onFocus
value onSelect

Built-in Objects
Array length join none
reverse
sort xx
Date none getDate none
getDay
getHours
getMinutes
getMonth
getSeconds
getTime
getTimeZoneoffset
getYear
parse
prototype
setDate
setHours
setMinutes
setMonth
setSeconds
setTime

Page 31
JAVASCRIPT Notes

setYear
toGMTString
toLocaleString
UTC
String length anchor Window
prototype big
blink
bold
charAt
fixed
fontColor
fontSize
indexOf
italics
lastIndexOf
link
small
split
strike
sub
substring
sup
toLowerCase
toUpperCase

JavaScript Array Object

The Array object is used to store multiple values in a single variable.

Create an Array

The following code creates an Array object called myCars:

var myCars=new Array();

There are two ways of adding values to an array (you can add as many values as you need to define as
many variables you require).

1:

var myCars=new Array();


myCars[0]="Saab";
myCars[1]="Volvo";
myCars[2]="BMW";

Page 32
JAVASCRIPT Notes

You could also pass an integer argument to control the array's size:

var myCars=new Array(3);


myCars[0]="Saab";
myCars[1]="Volvo";
myCars[2]="BMW";

2:

var myCars=new Array("Saab","Volvo","BMW");

Note: If you specify numbers or true/false values inside the array then the type of variables will be
numeric or Boolean instead of string.

Access an Array

You can refer to a particular element in an array by referring to the name of the array and the index
number. The index number starts at 0.

The following code line:

document.write(myCars[0]);

will result in the following output:

Saab

Modify Values in an Array

To modify a value in an existing array, just add a new value to the array with a specified index number:

myCars[0]="Opel";

Now, the following code line:

document.write(myCars[0]);

will result in the following output:

Opel

JavaScript Date Object

Page 33
JAVASCRIPT Notes

Create a Date Object

The Date object is used to work with dates and times.

The following code create a Date object called myDate:

var myDate=new Date()

Note: The Date object will automatically hold the current date and time as its initial value!

Set Dates

We can easily manipulate the date by using the methods available for the Date object.

In the example below we set a Date object to a specific date (14th January 2010):

var myDate=new Date();


myDate.setFullYear(2010,0,14);

And in the following example we set a Date object to be 5 days into the future:

var myDate=new Date();


myDate.setDate(myDate.getDate()+5);

Note: If adding five days to a date shifts the month or year, the changes are handled automatically by the
Date object itself!

Compare Two Dates

The Date object is also used to compare two dates.

The following example compares today's date with the 14th January 2010:

var myDate=new Date();


myDate.setFullYear(2010,0,14);
var today = new Date();
if (myDate>today)
{
alert("Today is before 14th January 2010");
}
else
{
alert("Today is after 14th January 2010");
}

JavaScript Math Object


Page 34
JAVASCRIPT Notes

Math Object

The Math object allows you to perform mathematical tasks.

The Math object includes several mathematical constants and methods.

Syntax for using properties/methods of Math:

var pi_value=Math.PI;
var sqrt_value=Math.sqrt(16);

Note: Math is not a constructor. All properties and methods of Math can be called by using Math as an
object without creating it.

Mathematical Constants

JavaScript provides eight mathematical constants that can be accessed from the Math object. These are: E,
PI, square root of 2, square root of 1/2, natural log of 2, natural log of 10, base-2 log of E, and base-10 log
of E.

You may reference these constants from your JavaScript like this:

Math.E
Math.PI
Math.SQRT2
Math.SQRT1_2
Math.LN2
Math.LN10
Math.LOG2E
Math.LOG10E

Mathematical Methods

In addition to the mathematical constants that can be accessed from the Math object there are also several
methods available.

The following example uses the round() method of the Math object to round a number to the nearest
integer:

document.write(Math.round(4.7));

The code above will result in the following output:

Page 35
JAVASCRIPT Notes

The following example uses the random() method of the Math object to return a random number between
0 and 1:

document.write(Math.random());

The code above can result in the following output:

0.4218824567728053

The following example uses the floor() and random() methods of the Math object to return a random
number between 0 and 10:

document.write(Math.floor(Math.random()*11));

The code above can result in the following output:

JavaScript String Object

String object

The String object is used to manipulate a stored piece of text.

Examples of use:

The following example uses the length property of the String object to find the length of a string:

var txt="Hello world!";


document.write(txt.length);

The code above will result in the following output:

12

The following example uses the toUpperCase() method of the String object to convert a string to
uppercase letters:

var txt="Hello world!";


document.write(txt.toUpperCase());

The code above will result in the following output:

HELLO WORLD!

Page 36
JAVASCRIPT Notes

Window Object

The Window object is the top level object in the JavaScript hierarchy.

The Window object represents a browser window.

A Window object is created automatically with every instance of a <body> or <frameset> tag.

IE: Internet Explorer, F: Firefox, O: Opera.

Window Object Collections


Collection Description IE F O
frames[] Returns all named frames in the window 4 1 9

Window Object Properties


Property Description IE F O
closed Returns whether or not a window has been closed 4 1 9
defaultStatus Sets or returns the default text in the statusbar of the window 4 No 9
document See Document object 4 1 9
history See History object 4 1 9
length Sets or returns the number of frames in the window 4 1 9
location See Location object 4 1 9
name Sets or returns the name of the window 4 1 9
opener Returns a reference to the window that created the window 4 1 9
outerHeight Sets or returns the outer height of a window No 1 No
outerWidth Sets or returns the outer width of a window No 1 No
pageXOffset Sets or returns the X position of the current page in relation to the No No No
upper left corner of a window's display area
pageYOffset Sets or returns the Y position of the current page in relation to the No No No
upper left corner of a window's display area
parent Returns the parent window 4 1 9
personalbar Sets whether or not the browser's personal bar (or directories bar)
should be visible
scrollbars Sets whether or not the scrollbars should be visible
self Returns a reference to the current window 4 1 9
status Sets the text in the statusbar of a window 4 No 9
statusbar Sets whether or not the browser's statusbar should be visible
toolbar Sets whether or not the browser's tool bar is visible or not (can only
be set before the window is opened and you must have
UniversalBrowserWrite privilege)
top Returns the topmost ancestor window 4 1 9

Page 37
JAVASCRIPT Notes

Window Object Methods


Method Description IE F O
alert() Displays an alert box with a message and an OK button 4 1 9
blur() Removes focus from the current window 4 1 9
clearInterval() Cancels a timeout set with setInterval() 4 1 9
clearTimeout() Cancels a timeout set with setTimeout() 4 1 9
close() Closes the current window 4 1 9
confirm() Displays a dialog box with a message and an OK and a Cancel 4 1 9
button
createPopup() Creates a pop-up window 4 No No
focus() Sets focus to the current window 4 1 9
moveBy() Moves a window relative to its current position 4 1 9
moveTo() Moves a window to the specified position 4 1 9
open() Opens a new browser window 4 1 9
print() Prints the contents of the current window 5 1 9
prompt() Displays a dialog box that prompts the user for input 4 1 9
resizeBy() Resizes a window by the specified pixels 4 1 9
resizeTo() Resizes a window to the specified width and height 4 1.5 9
scrollBy() Scrolls the content by the specified number of pixels 4 1 9
scrollTo() Scrolls the content to the specified coordinates 4 1 9
setInterval() Evaluates an expression at specified intervals 4 1 9
setTimeout() Evaluates an expression after a specified number of milliseconds 4 1 9

Document Object

The Document object represents the entire HTML document and can be used to access all elements in a
page.

The Document object is part of the Window object and is accessed through the window.document
property.

IE: Internet Explorer, F: Firefox, O: Opera, W3C: World Wide Web Consortium (Internet Standard).

Document Object Collections


Collection Description IE F O W3C
anchors[] Returns a reference to all Anchor objects in the 4 1 9 Yes
document
forms[] Returns a reference to all Form objects in the 4 1 9 Yes
document
images[] Returns a reference to all Image objects in the 4 1 9 Yes
document
links[] Returns a reference to all Area and Link objects in 4 1 9 Yes

Page 38
JAVASCRIPT Notes

the document

Document Object Properties


Property Description IE F O W3C
body Gives direct access to the <body> element
cookie Sets or returns all cookies associated with the 4 1 9 Yes
current document
domain Returns the domain name for the current document 4 1 9 Yes
lastModified Returns the date and time a document was last 4 1 No No
modified
referrer Returns the URL of the document that loaded the 4 1 9 Yes
current document
title Returns the title of the current document 4 1 9 Yes
URL Returns the URL of the current document 4 1 9 Yes

Document Object Methods


Method Description IE F O W3C
close() Closes an output stream opened with the 4 1 9 Yes
document.open() method, and displays the
collected data
getElementById() Returns a reference to the first object with the 5 1 9 Yes
specified id
getElementsByName() Returns a collection of objects with the specified 5 1 9 Yes
name
getElementsByTagName() Returns a collection of objects with the specified 5 1 9 Yes
tagname
open() Opens a stream to collect the output from any 4 1 9 Yes
document.write() or document.writeln() methods
write() Writes HTML expressions or JavaScript code to a 4 1 9 Yes
document
writeln() Identical to the write() method, with the addition 4 1 9 Yes
of writing a new line character after each
expression

History Object

The History object is actually a JavaScript object, not an HTML DOM object.

The History object is automatically created by the JavaScript runtime engine and consists of an array of
URLs. These URLs are the URLs the user has visited within a browser window.

The History object is part of the Window object and is accessed through the window.history property.

IE: Internet Explorer, F: Firefox, O: Opera.

Page 39
JAVASCRIPT Notes

History Object Properties


Property Description IE F O
length Returns the number of elements in the history list 4 1 9

History Object Methods


Method Description IE F O
back() Loads the previous URL in the history list 4 1 9
forward() Loads the next URL in the history list 4 1 9
go() Loads a specific page in the history list 4 1 9

Form Object

The Form object represents an HTML form.

For each instance of a <form> tag in an HTML document, a Form object is created.

IE: Internet Explorer, F: Firefox, O: Opera, W3C: World Wide Web Consortium (Internet Standard).

Form Object Collections


Collection Description IE F O W3C
elements[] Returns an array containing each element in the form 5 1 9 Yes

Form Object Properties


Property Description IE F O W3C
acceptCharset Sets or returns a list of possible character-sets for the form data No No No Yes
action Sets or returns the action attribute of a form 5 1 9 Yes
enctype Sets or returns the MIME type used to encode the content of a 6 1 9 Yes
form
id Sets or returns the id of a form 5 1 9 Yes
length Returns the number of elements in a form 5 1 9 Yes
method Sets or returns the HTTP method for sending data to the server 5 1 9 Yes
name Sets or returns the name of a form 5 1 9 Yes
target Sets or returns where to open the action-URL in a form 5 1 9 Yes

Standard Properties
Property Description IE F O W3C
className Sets or returns the class attribute of an element 5 1 9 Yes
dir Sets or returns the direction of text 5 1 9 Yes
lang Sets or returns the language code for an element 5 1 9 Yes
title Sets or returns an element's advisory title 5 1 9 Yes

Page 40
JAVASCRIPT Notes

Form Object Methods


Method Description IE F O W3C
reset() Resets the values of all elements in a form 5 1 9 Yes
submit() Submits a form 5 1 9 Yes

Image Object

The Image object represents an embedded image.

For each instance of an <img> tag in an HTML document, an Image object is created.

IE: Internet Explorer, F: Firefox, O: Opera, W3C: World Wide Web Consortium (Internet Standard).

Image Object Properties


Property Description IE F O W3C
align Sets or returns how to align an image according to the 5 1 9 Yes
surrounding text
alt Sets or returns an alternate text to be displayed, if a browser 5 1 9 Yes
cannot show an image
border Sets or returns the border around an image 4 1 9 Yes
complete Returns whether or not the browser has finished loading the 4 1 9 No
image
height Sets or returns the height of an image 4 1 9 Yes
hspace Sets or returns the white space on the left and right side of the 4 1 9 Yes
image
id Sets or returns the id of the image 4 1 9 Yes
isMap Returns whether or not an image is a server-side image map 5 1 9 Yes
longDesc Sets or returns a URL to a document containing a description 6 1 9 Yes
of the image
lowsrc Sets or returns a URL to a low-resolution version of an image 4 1 9 No
name Sets or returns the name of an image 4 1 9 Yes
src Sets or returns the URL of an image 4 1 9 Yes
useMap Sets or returns the value of the usemap attribute of an client- 5 1 9 Yes
side image map
vspace Sets or returns the white space on the top and bottom of the 4 1 9 Yes
image
width Sets or returns the width of an image 4 1 9 Yes

Standard Properties
Property Description IE F O W3C
className Sets or returns the class attribute of an element 5 1 9 Yes
title Sets or returns an element's advisory title 5 1 9 Yes

Page 41
JAVASCRIPT Notes

Area Object

The Area object represents an area of an image-map (An image-map is an image with clickable regions).

For each instance of an <area> tag in an HTML document, an Area object is created.

IE: Internet Explorer, F: Firefox, O: Opera, W3C: World Wide Web Consortium (Internet Standard).

Area Object Properties


Property Description IE F O W3C
accessKey Sets or returns the keyboard key to access an area 5 1 No Yes
alt Sets or returns an alternate text to be displayed, if a browser 5 1 9 Yes
cannot show an area
coords Sets or returns the coordinates of a clickable area in an image- 5 1 9 Yes
map
hash Sets or returns the anchor part of the URL in an area 4 1 No No
host Sets or returns the hostname and port of the URL in an area 4 1 No No
href Sets or returns the URL of a link in an image-map 4 1 9 Yes
id Sets or returns the id of an area 4 1 9 Yes
noHref Sets or returns whether an area should be active or inactive 5 1 9 Yes
pathname Sets or returns the pathname of the URL in an area 4 1 9 No
protocol Sets or returns the protocol of the URL in an area 4 1 9 No
search Sets or returns the query string part of the URL in an area 4 1 9 No
shape Sets or returns the shape of an area in an image-map 5 1 9 Yes
tabIndex Sets or returns the tab order for an area 5 1 9 Yes
target Sets or returns where to open the link-URL in an area 4 1 9 Yes

Standard Properties
Property Description IE F O W3C
className Sets or returns the class attribute of an element 5 1 9 Yes
dir Sets or returns the direction of text 5 1 9 Yes
lang Sets or returns the language code for an element 5 1 9 Yes
title Sets or returns an element's advisory title 5 1 9 Yes

Navigator Object

The Navigator object is actually a JavaScript object, not an HTML DOM object.

The Navigator object is automatically created by the JavaScript runtime engine and contains information
about the client browser.

IE: Internet Explorer, F: Firefox, O: Opera.

Page 42
JAVASCRIPT Notes

Navigator Object Collections


Collection Description IE F O
plugins[] Returns a reference to all embedded objects in the document 4 1 9

Navigator Object Properties


Property Description IE F O
appCodeName Returns the code name of the browser 4 1 9
appMinorVersion Returns the minor version of the browser 4 No No
appName Returns the name of the browser 4 1 9
appVersion Returns the platform and version of the browser 4 1 9
browserLanguage Returns the current browser language 4 No 9
cookieEnabled Returns a Boolean value that specifies whether cookies are 4 1 9
enabled in the browser
cpuClass Returns the CPU class of the browser's system 4 No No
onLine Returns a Boolean value that specifies whether the system is in 4 No No
offline mode
platform Returns the operating system platform 4 1 9
systemLanguage Returns the default language used by the OS 4 No No
userAgent Returns the value of the user-agent header sent by the client to 4 1 9
the server
userLanguage Returns the OS' natural language setting 4 No 9

Navigator Object Methods


Method Description IE F O
javaEnabled() Specifies whether or not the browser has Java enabled 4 1 9
taintEnabled() Specifies whether or not the browser has data tainting enabled 4 1 9

ZIP CODE VALIDATION

<!-- TWO STEPS TO INSTALL ZIP CODE VALIDATION:

1. Copy the coding into the HEAD of your HTML document

2. Add the last code into the BODY of your HTML document -->

<!-- STEP ONE: Paste this code into the HEAD of your HTML document -->

<HEAD>

<SCRIPT LANGUAGE="JavaScript">

<!-- Original: Brian Swalwell -->

Page 43
JAVASCRIPT Notes

<!-- This script and many more are available free online at -->

<!-- The JavaScript Source!! http://javascript.internet.com -->

<!-- Begin

function validateZIP(field) {

var valid = "0123456789-";

var hyphencount = 0;

if (field.length!=5 && field.length!=10) {

alert("Please enter your 5 digit or 5 digit+4 zip code.");

return false;

for (var i=0; i < field.length; i++) {

temp = "" + field.substring(i, i+1);

if (temp == "-") hyphencount++;

if (valid.indexOf(temp) == "-1") {

alert("Invalid characters in your zip code. Please try again.");

return false;

if ((hyphencount > 1) || ((field.length==10) && ""+field.charAt(5)!="-")) {

alert("The hyphen character should be used with a properly formatted 5 digit+four zip code, like '12345-
6789'. Please try again.");

return false;

return true;

Page 44
JAVASCRIPT Notes

// End -->

</script>

</HEAD>

<!-- STEP TWO: Copy this code into the BODY of your HTML document -->

<BODY>

<center>

<form name=zip onSubmit="return validateZIP(this.zip.value)">

Zip: <input type=text size=30 name=zip>

<input type=submit value="Submit">

</form>

</center>

<p><center>

<font face="arial, helvetica" size="-2">Free JavaScripts provided<br>

by <a href="http://javascriptsource.com">The JavaScript Source</a></font>

</center><p>

Page 45
REGULAR EXPRESSIONS AND REGEXP OBJECT
http://www.tutorialspoint.com/javascript/javascript_regexp_object.htm Copyright © tutorialspoint.com

A regular expression is an object that describes a pattern of characters.

The JavaScript RegExp class represents regular expressions, and both String and RegExp define
methods that use regular expressions to perform powerful pattern-matching and search-and-
replace functions on text.

Syntax
A regular expression could be defined with the RegExp constructor, as follows −

var pattern = new RegExp(pattern, attributes);

or simply

var pattern = /pattern/attributes;

Here is the description of the parameters −

pattern − A string that specifies the pattern of the regular expression or another regular
expression.

attributes − An optional string containing any of the "g", "i", and "m" attributes that specify
global, case-insensitive, and multiline matches, respectively.

Brackets
Brackets [] have a special meaning when used in the context of regular expressions. They are used
to find a range of characters.

Expression Description

[...] Any one character between the brackets.

[^...] Any one character not between the brackets.

[0-9] It matches any decimal digit from 0 through 9.

[a-z] It matches any character from lowercase a through lowercase z.

[A-Z] It matches any character from uppercase A through uppercase Z.

[a-Z] It matches any character from lowercase a through uppercase Z.

The ranges shown above are general; you could also use the range [0-3] to match any decimal
digit ranging from 0 through 3, or the range [b-v] to match any lowercase character ranging from
b through v.

Quantifiers
The frequency or position of bracketed character sequences and single characters can be denoted
by a special character. Each special character has a specific connotation. The +, *, ?, and $ flags
all follow a character sequence.

Expression Description

p+ It matches any string containing at least one p.


p* It matches any string containing zero or more p's.

p? It matches any string containing one or more p's.

p{N} It matches any string containing a sequence of N p's

p{2,3} It matches any string containing a sequence of two or three p's.

p{2, } It matches any string containing a sequence of at least two p's.

p$ It matches any string with p at the end of it.

^p It matches any string with p at the beginning of it.

Examples
Following examples explain more about matching characters.

Expression Description

[^a-zA-Z] It matches any string not containing any of the characters ranging from a through
z and A through Z.

p.p It matches any string containing p, followed by any character, in turn followed by
another p.

^.{2}$ It matches any string containing exactly two characters.

<b>. ∗ It matches any string enclosed within <b> and </b>.


</b>

php* It matches any string containing a p followed by zero or more instances of the
sequence hp.

Literal characters

Character Description

Alphanumeric Itself

\0 The NUL character \u0000

\t Tab \u0009

\n Newline \u000A

\v Vertical tab \u000B

\f Form feed \u000C

\r Carriage return \u000D

\xnn The Latin character specified by the hexadecimal number nn; for example,
\x0A is the same as \n

\uxxxx The Unicode character specified by the hexadecimal number xxxx; for
example, \u0009 is the same as \t

\cX The control character ^X; for example, \cJ is equivalent to the newline
character \n
Metacharacters
A metacharacter is simply an alphabetical character preceded by a backslash that acts to give the
combination a special meaning.

For instance, you can search for a large sum of money using the '\d' metacharacter: /[\d] + 000/,
Here \d will search for any string of numerical character.

The following table lists a set of metacharacters which can be used in PERL Style Regular
Expressions.

Character Description

. a single character

\s a whitespace character space, tab, newline

\S non-whitespace character

\d a digit 0 − 9

\D a non-digit

\w a word character a-z, A-Z, 0-9, _

\W a non-word character

[\b] a literal backspace specialcase.

[aeiou] matches a single character in the given set

[^aeiou] matches a single character outside the given set

foo | bar | baz matches any of the alternatives specified

Modifiers
Several modifiers are available that can simplify the way you work with regexps, like case
sensitivity, searching in multiple lines, etc.

Modifier Description

i Perform case-insensitive matching.

m Specifies that if the string has newline or carriage return characters, the ^ and $
operators will now match against a newline boundary, instead of a string boundary

g Performs a global matchthat is, find all matches rather than stopping after the first
match.

RegExp Properties
Here is a list of the properties associated with RegExp and their description.

Property Description

constructor Specifies the function that creates an object's


prototype.

global Specifies if the "g" modifier is set.


ignoreCase Specifies if the "i" modifier is set.

lastIndex The index at which to start the next match.

multiline Specifies if the "m" modifier is set.

source The text of the pattern.

In the following sections, we will have a few examples to demonstrate the usage of RegExp
properties.

RegExp Methods
Here is a list of the methods associated with RegExp along with their description.

Method Description

exec Executes a search for a match in its string parameter.

test Tests for a match in its string parameter.

toSource Returns an object literal representing the specified object; you can use this
value to create a new object.

toString Returns a string representing the specified object.

In the following sections, we will have a few examples to demonstrate the usage of RegExp
methods.
Loading [MathJax]/jax/output/HTML-CSS/jax.js
eXtensible Markup Language (XML)
TOPICS
• Introduction
• The Syntax of XML
• XML Document Structure
• Document Type Definitions
• Namespaces
• XML Schemas
• Displaying Raw XML Documents
• Displaying XML Documents with CSS
• XSLT Style Sheets
INTRODUCTION
• XML is a meta-markup language (language for defining markup languages)
• In 1986, Standard Generalized Markup Language (SGML) was approved as
ISO standard
• In 1990, SGML was used as the basis for the development of HTML as the
standard markup language for Web documents
• In 1996, W3C began work on XML, another meta-markup language
• First XML standard, 1.0, was published in February 1998.
• The second, 1.1, was published in 2006
MOTIVATION
• HTML was defined to describe the layout of information without considering
the meaning of that information
• To describe a particular kind of information, it would be necessary to have
tags indicating the meaning of the element’s content
• If the price of a used car is stored as the content of an element named price,
an application could find all cars in the document that cost less than 6,00,000
INR
• XML was designed to be that simplified version of SGML that allow users to
define their own markup languages
INTRODUCTION
• XML was not meant to be a replacement for HTML
• HTML is a markup language that is meant to describe the layout of general
information where as XML is a meta-markup language that provides a
framework for defining specialized markup languages
INTRODUCTION
• XML is far more than a solution to the deficiencies of HTML:
• It provides a simple and universal way of storing any textual data
• Data stored in XML documents can be electronically distributed and processed by
any number of different applications => XML is a universal data interchange
language
• There are many XML-oriented text editors that assist with the creation and
maintenance of XML documents - Altova XMLSpy
• Data in an XML document can be displayed by browsers only if the presentation
styles are provided by style sheets of some kind
• XML processor, parses XML documents, (process that isolates the constituent parts
such as tags, attributes, and data strings) and provides them to an application
INTRODUCTION
• Exchanging data between incompatible systems (or upgraded systems) is a time-
consuming task for web developers. Large amounts of data must be converted, and
incompatible data is often lost.
• XML stores data in plain text format. This provides a software- and hardware-
independent way of storing, transporting, and sharing data.
• XML also makes it easier to expand or upgrade to new operating systems, new
applications, or new browsers, without losing data
• With XML, data can be available to all kinds of "reading machines" like people,
computers, voice machines, news feeds, etc.
SYNTAX OF XML
Syntax of XML can be thought of at two distinct levels:
• Low-level syntax of XML:
• which imposes its rules on all XML documents
• Specified by either document type definitions ( DTDs) or XML schemas
• specify the set of tags and attributes that can appear in a particular document or
collection of documents and also the orders and arrangements in which they can
appear
SYNTAX OF XML
An XML document can include several different kinds of statements:
• Data elements
• Markup declarations
• Instructions to the XML parser
• Processing instructions
• Instructions for an application program that will process the data described in the
document
SYNTAX OF XML
• All XML documents begin with an XML declaration
• Identifies the document as XML and provides the version number of the XML
standard used. It may also specify an encoding standard.
• Comments in XML are the same as in HTML
• XML names
• used to name elements and attributes
• must begin with a letter or an underscore and can include digits, hyphens, and
periods
• case sensitive
• no length limitation for XML names
SYNTAX OF XML
Set of syntax rules applies to all XML documents:
• Every XML document defines a single root element, whose opening tag must appear on the
first line of XML code
• All other elements of an XML document must be nested inside the root element
• The root element in XML has whatever name the author chooses
• XML tags are surrounded by angle brackets
• Every XML element that can have content must have a closing tag; Elements that do not
include content must use a tag with the following form: <element_name/>
• XML tags can have attributes, which are specified with name–value assignments. All attribute
values must be enclosed by either single or double quotation marks.
• An XML document that strictly adheres to these syntax rules is considered well formed
SYNTAX OF XML
• When designing an XML document, the designer is often faced with the choice
between adding a new attribute to an element or defining a nested element
• A nested element should be used-
• If the data in question has some substructure of its own
• If the data is subdata of the parent element’s content rather than information about
the data of the parent element
• An attribute should always be used:
• to identify numbers or names of elements, exactly as the id and name attributes
are used in HTML
• if the data in question is one value from a given set of possibilities
• if there is no substructure or if it is really just information about the element
SYNTAX OF XML
XML DOCUMENT STRUCTURE
An XML document often uses two auxiliary files:
• one defines its tag set and structural syntactic rules (given as either a DTD
or an XML schema)
• other that contains a style sheet to describe how the content of the
document is to be printed or displayed
XML DOCUMENT STRUCTURE
• An XML document consists of one or more entities (logically related
collections of information)
• XML entities are a way of representing an item of data within an XML
document, instead of using the data itself
• It is good to define a large document as a number of smaller parts to make it
more manageable
• If the same data appears in more than one place in the document, defining
that data as an entity allows any number of references to a single copy of it
XML DOCUMENT STRUCTURE
• When an XML processor encounters the name of a nonbinary entity in a
document it replaces the name with the value it references
• Binary entities can be handled only by applications that deal with the
document, such as browsers
XML DOCUMENT STRUCTURE
• Entity names can be of any length
• They must begin with a letter, a dash, or a colon. After the first character, a
name can have letters, digits, periods, dashes, underscores, or colons
• A reference to an entity is its name together with a prepended ampersand
and an appended semicolon
• For example, if apple_image is the name of an entity, &apple_image; is a
reference to it
XML DOCUMENT STRUCTURE
Use of Entities in xml document:
• Denoting special markup, such as the > and < tags
• Managing binary files and other data not native to XML
• Reducing the code in DTD by bundling declarations into entities
• Offering richer multilingual support
• Repeating frequently used names in a way that guarantees consistency in spelling
and use
• Providing for easier updates. By using entities in your markup for items you know will
be changed later-such as weather reports or software version changes-you greatly
improve dynamic document automation
• Merging multiple file links and interaction
XML DOCUMENT STRUCTURE
• Document entity: can be the entire document, but in many cases, it
includes references to the names of entities that are stored elsewhere
DOCUMENT TYPE DEFINITIONS
• DTD is a set of structural rules called declarations, which specify a set of
elements and attributes that can appear in a document, as well as how and
where these elements and attributes may appear
• Not all XML documents need a DTD
• DTDs are used when the same tag set definition is used by a collection of
documents and the documents must have a consistent and uniform structure,
as well as the same set of elements and attributes
DOCUMENT TYPE DEFINITIONS
Internal DTD
• DTD embedded in the XML document whose syntax rules it describes

External DTD
• DTD stored in a separate file
• Imposes structural rules uniformity across the documents
• Avoids two different notations(DTD and XML code) from appearing in the
same document
DOCUMENT TYPE DEFINITIONS
• A DTD is a sequence of declarations, each of which has the form of a markup
declaration:

<!keyword ... >


Possible keywords:
• ELEMENT - used to define tags
• ATTLIST - used to define tag attributes
• ENTITY - used to define entities
• NOTATION - used to define data type notations
DECLARING ELEMENTS
• The form of an element declaration for elements that contain elements is as
follows:
<!ELEMENT element_name(list of names of child elements)>

Example:
<!ELEMENT memo(from, to, date, re, body)>
DECLARING ELEMENTS
• Each element declaration in a DTD specifies the structure of one category of
elements
If an XML document is considered as a tree, then:
• An element is either a leaf node or an internal/root node in such a tree
• If the element is a leaf node, its syntactic description is its character pattern
• If the element is not a leaf node, its syntactic description is a list of its child
elements, each of which can be a leaf node or an internal node
DECLARING ELEMENTS
• In many cases, it is necessary to specify the number of times that a child element may
appear.
• This can be done in a DTD declaration by adding a modifier to the child element
specification
DECLARING ELEMENTS
• In many cases, it is necessary to specify the number of times that a child element may
appear.

• a person element is specified to have the following child elements:


• one or more parent elements
• one age element
• possibly a spouse element
• zero or more sibling elements
DECLARING ELEMENTS
• The leaf nodes of a DTD specify the data types of the content of their parent nodes,
which are elements
• In most cases, the content of an element is type PCDATA, for parsable character data.
Parsable character data is a string of any printable characters except “less than” (<),
greater than(>) and the ampersand (&)
• The EMPTY type specifies that the element has no content; it is used for elements
similar to the HTML img element.
• The ANY type is used when the element may contain literally any content.
DECLARING ATTRIBUTES
• Attributes of an element are declared separately from the element declaration
in a DTD
• General form of an attribute declaration:

• If more than one attribute is declared for a given element, the declarations can
be combined
DECLARING ATTRIBUTES
Attribute types:
• CDATA type : any string of characters that does not include >, < or &
• ENTITY type : used for declaring an entity attribute for a binary entity

default option:
• can specify either an actual value or a requirement for the value of the
attribute in the XML document
DECLARING ATTRIBUTES
DECLARING ENTITIES
The form of an entity declaration is:

• When the optional percent sign (%) is present in an entity declaration, it specifies
that the entity is a parameter entity rather than a general entity
• Example:

• Any XML document that uses a DTD that includes this declaration can specify the
complete name with just the reference &jfk;
DECLARING ENTITIES
External text entity:
When an entity is longer than a few words, such as a section of a technical article, its
text is defined outside the DTD

• The keyword SYSTEM specifies that the definition of the entity is in a different file,
which is specified as the string following SYSTEM
Example:
• <!ENTITY writer SYSTEM "entities.dtd">
• Reference: <author>&writer;</author>
DECLARING ENTITIES
Binary data (not text) can be included in an XML document as an entity

• NDATA, specifies that the entity value is not to be parsed


• Notation identifier specifies the encoding of the entity value, for example, JPEG, GIF,
MPEG, or WAV
DECLARING ENTITIES
• Binary entities also require special references.

• This requires that the photo element and its attribute ent have been previously
declared
DTD EXAMPLE
INTERNAL AND EXTERNAL DTD

Internal DTD:
• A DTD appearing inside an XML document
INTERNAL
DTD-
EXAMPLE
INTERNAL AND EXTERNAL DTD

External DTD:
• A DTD specified in a separate file
• The XML document refers to it with a DOCTYPE declaration as its second line
• General form:
EXAMPLE-EXTERNAL DTD

notes.xml notes.dtd
XML NAMESPACES
• XML namespace is a way to avoid element name conflicts
• Namespaces are used for providing uniquely named elements and attributes in an XML
document
• One problem with using different markup vocabularies in the same document is that
collisions between names that are defined in two or more of those tag sets could result

Example:
• Both the customer element and the product element could have a child element named id.
• References to the id element would therefore be ambiguous in a same xml document
• Placing them in different namespaces would remove the ambiguity
XML NAMESPACES
• An XML namespace is a collection of element and attribute names used in XML
documents
• The name of a namespace usually has the form of a URL, although XML processors
never reference the site whose URL is used as the name of a namespace.
• The name of a namespace for the elements and attributes of the hierarchy rooted at
a particular element is declared as the value of the attribute xmlns.
• A namespace declaration for an element is given as the value of the xmlns
attribute, as in the following:
EXAMPLE
DEFAULT NAMESPACES
• Defining a default namespace for an element saves us from using prefixes in all the
child elements
XML SCHEMA
Disadvantages of DTD:
• Syntax unrelated to XML => they cannot be analyzed with an XML processor
• DTDs do not allow restrictions on the form of data that can be the content of
a particular tag; e.g: DTD can only specify time as text
• No scope for sequencing of child elements
• No scope for including externally defined elements
XML SCHEMA

• Primary successor to DTD and has W3C support


• An XML schema is an XML document, so it can be parsed with an XML
parser
• Provides far more control over data types than do DTDs
• User can define new types with constraints on existing data types
XML SCHEMA
• XML Schema language is also referred to as XML Schema Definition (XSD)
• It describes the structure of an XML document
• XML documents that conform to a specific schema are considered instances
of that schema
• The purpose of an XML Schema is to define the legal building blocks of an
XML document:
• the elements and attributes that can appear in a document
• the number of (and order of) child elements
• data types for elements and attributes
DEFINING A SCHEMA
• Schemas themselves are written with the use of a collection of tags, or a
vocabulary, from a namespace
http://www.w3.org/2001/XMLSchema
• Some of the elements in the namespace are element, schema, sequence,
and string
DEFINING A SCHEMA
• Every schema has schema as its root element
• schema element specifies the namespace for the schema of schemas from
which the schema’s elements and attributes will be drawn.
• It often also specifies a prefix that will be used for the names in the schema
xmlns:xsd = "http://www.w3.org/2001/XMLSchema”
DEFINING A SCHEMA

• A schema defines a namespace in the same sense as a DTD defines a tag set
• The name of the namespace defined by a schema must be specified with
the targetNamespace attribute of the schema element
• The name of every top-level (not nested) element that appears in a schema
is placed in the target namespace, which is specified by assigning a
namespace to the target namespace attribute:
targetNamespace = "http://cs.uccs.edu/planeSchema"
DEFINING A SCHEMA
• If the names of the elements and attributes that are not defined directly in
the schema element (because they are nested inside top-level elements)
are to be included in the target namespace, schema’s elementFormDefault
must be set to qualified
elementFormDefault = "qualified“

• The default namespace, which is the source of the unprefixed names in the
schema, is given with another xmlns specification
xmlns = "http://cs.uccs.edu/planeSchema"
DEFINING A SCHEMA INSTANCE
• An instance of a schema must include specifications of the namespaces it
uses
• These specifications are given as attribute assignments in the tag for the
root element of the schema

• An instance document normally defines its default namespace to be the one


defined in its schema
DEFINING A SCHEMA INSTANCE
• An instance of a schema must include specifications of the namespaces it
uses
• These specifications are given as attribute assignments in the tag for the
root element of the schema

• An instance document normally defines its default namespace to be the one


defined in its schema
DEFINING A SCHEMA INSTANCE
• Second attribute is used to name the standard namespace for instances, which includes the
name XMLSchemainstance.
• This namespace corresponds to the XMLSchema namespace used for schemas
DEFINING A SCHEMA INSTANCE
• schemaLocation attribute specifies the file name of the schema in which the default
namespace is defined.
• It takes two values: the namespace of the schema and the file name of the schema
• This attribute is defined in the XMLSchemainstance namespace, so it must be named with
the proper prefix
DATA TYPES
• Categories of user-defined schema data types:
• Simple data type:
Cannot include nested elements or attributes
• Complex type:
can have attributes and include other data types as child elements.
SIMPLE TYPES
• Elements are defined in an XML schema with the element tag, which is from the
XMLSchema namespace
• prefix xsd is normally used for names from this namespace.
• An element that is named includes the name attribute for that purpose. The other attribute
that is necessary in a simple element declaration is type, which is used to specify the type
of content allowed in the element
SIMPLE TYPES
• An element can be given a default value with the default attribute:
• Constant values are given with the fixed attribute
COMPLEX TYPES
• Complex types are defined with the complexType tag
• The sequence element is used to contain an ordered group of elements

• A complex type whose elements are an unordered group is defined in an all element
• The choice element can contain any number of elements, only one of which can appear in
any XML document that complies with the schema.
COMPLEX TYPES
• minOccurs and maxOccurs attributes can be used to specify the numbers of occurrences of
elements
• The possible values of minOccurs are the nonnegative integers (including zero).
• The possible values for maxOccurs are the nonnegative integers plus the value
unbounded
DISPLAYING RAW XML DOCUMENTS

• If an XML document is displayed without a style sheet that defines


presentation styles for the document’s tags, the displayed document
will not have formatted content
• The display of such an XML document is only a somewhat stylized
listing of the XML markup
DISPLAYING XML DOCUMENTS WITH STYLESHEETS

Style-sheet information can be provided to the browser for an XML


document in two ways
• Using Cascading Style Sheet (CSS) file
• Using XSLT style-sheet technology
DISPLAYING XML DOCUMENTS WITH CSS
• The connection of an XML document to a CSS style sheet is established with the processing
instruction xml-stylesheet, which specifies the particular type of the style sheet via its type
attribute and the name of the file that stores the style sheet via its href attribute
XSLT STYLE SHEETS
• XSL (eXtensible Stylesheet Language) is a styling language for XML.
• XSLT stands for XSL Transformations
• XPath is a language for navigating in XML documents
• XSLT is used to transform an XML document into another XML document, or another
type of document that is recognized by a browser, like HTML and XHTML.
• In the transformation process, XSLT uses XPath to define parts of the source
document that should match one or more predefined templates. When a match is
found, XSLT will transform the matching part of the source document into the result
document.
• Templates:
• An XSL style sheet consists of one or more set of rules that are called templates.
• A template contains rules to apply when a specified node is matched.

• The <xsl:template> element is used to build templates.


• The match attribute is used to associate a template with an XML element. The match
attribute can also be used to define a template for the entire XML document. The
value of the match attribute is an XPath expression (i.e. match="/" defines the whole
document).
• The <xsl:value-of> element can be used to extract the value of an XML element and
add it to the output stream of the transformation
• The XSL <xsl:for-each> element can be used to select every XML element of a
specified node-set

• The <xsl:apply-templates> element applies a template rule to the current element or


to the current element's child nodes.
• If we add a "select" attribute to the <xsl:apply-templates> element, it will process
only the child elements that matches the value of the attribute. We can use the
"select" attribute to specify in which order the child nodes are to be processed.
JavaScript
THE JAVASCRIPT EXECUTION ENVIRONMENT
• The JavaScript Window object represents the window that displays the
document
• The properties of the Window object are visible to all JavaScript scripts
that appear either implicitly or explicitly in the window’s HTML
document
• When a global variable is created in a client-side script, it is created as
a new property of the Window object, which provides the largest
enclosing referencing environment for JavaScript scripts
THE JAVASCRIPT EXECUTION ENVIRONMENT
• The JavaScript Document object represents the displayed HTML document
• Every Window object has a property named document, which is a reference
to the Document object that the window displays
• Every Document object has a forms array, each element of which represents
a form in the document.
• Each forms array element has an elements array as a property, which
contains the objects that represent the HTML form elements, such as buttons
and menus
• Document objects also have property arrays for anchors, links, images
THE DOCUMENT OBJECT MODEL
• The actual DOM specification consists of a collection of interfaces, including
one for each document tree node type
• These interfaces are similar to Java interfaces and C++ abstract classes
• They define the objects, methods, and properties that are associated with
their respective node types
• With the DOM, users can write code in programming languages to create
documents, move around in their structures, and change, add, or delete
elements and their content
THE DOCUMENT OBJECT MODEL
• Documents in the DOM have a treelike structure, but there can be more than
one tree in a document
• Because the DOM is an abstract interface, it does not dictate that documents
be implemented as trees or collections of trees
• A language that is designed to support the DOM must have a binding to the
DOM constructs
• This binding amounts to a correspondence between constructs in the
language and elements in the DOM
THE DOCUMENT OBJECT MODEL
• In the JavaScript binding to the DOM, the elements of a document are objects,
with both data and operations.
• The data are called properties, and the operations are, naturally, called
methods
<input type = "text" name = "address">
• HTML element would be represented as an object with two properties, type
and name, with the values "text" and "address", respectively
• In most cases, the property names in JavaScript are the same as their
corresponding attribute names in HTML
ELEMENT ACCESS IN JAVASCRIPT
• The elements of an HTML document have corresponding objects that are
visible to an embedded JavaScript script
• The addresses of these objects are required, both by the event handling and
by the code for making dynamic changes to documents

• Approach 1:
• use the forms and elements arrays of the Document object, which is
referenced through the document property of the Window object
ELEMENT ACCESS IN JAVASCRIPT

var dom = document.forms[0].elements[0];


• DOM address is defined by the position of elements in the document, which
could change
ELEMENT ACCESS IN JAVASCRIPT
• Approach 2:
• Use element names

var dom = document.myForm.turnItOn;


ELEMENT ACCESS IN JAVASCRIPT
• Approach 3:
• Use the JavaScript method getElementById
• Because an element’s identifier (id) is unique in the document, this approach
works, regardless of how deeply the element is nested in other elements in
the document
• If the id attribute of our button is set to "turnItOn", the following could be used
to get the DOM address of that button element:
var dom = document.getElementById("turnItOn");
ELEMENT ACCESS IN JAVASCRIPT
• Buttons in a group of checkboxes often share the same name.
• The buttons in a radio button group always have the same name.
• In these cases, the names of the individual buttons obviously cannot be used
in their DOM addresses.
• Of course, each radio button and checkbox can have an id, which would make
them easy to address by using getElementById.
• However, this approach does not provide a convenient way to search a group
of radio buttons or checkboxes to determine which is checked.
ELEMENT ACCESS IN JAVASCRIPT
• An alternative to both names and ids is provided by the implicit arrays
associated with each checkbox and radio button group.
• Every such group has an array, which has the same name as the group name,
that stores the DOM addresses of the individual buttons in the group.
• These arrays are properties of the form in which the buttons appear.
ELEMENT ACCESS IN JAVASCRIPT
EVENTS AND EVENT HANDLING
• An event is a notification that something specific has occurred, either in
the browser, such as the completion of the loading of a document, or a
browser user action, such as a mouse click on a form button.
• Strictly speaking, an event is an object that is implicitly created by the
browser and the JavaScript system in response to something having
happened
• An event handler is a script that is implicitly executed in response to
the appearance of an event.
• Event handlers enable a Web document to be responsive to browser
and user activities
EVENTS AND EVENT HANDLING
• Event names are case sensitive-the names of all event objects have
only lowercase letters
• The process of connecting an event handler to an event is called
registration
• There are two distinct approaches to event handler registration- one
that assigns tag attributes and one that assigns handler addresses to
object properties
EVENTS, ATTRIBUTES, AND TAGS
• HTML provides a collection of events that browsers implement and
with which JavaScript can deal.
• These events are associated with HTML tag attributes, which can be
used to connect the events to handlers.
• The attributes have names that are closely related to their associated
events
• The same attribute can appear in several different tags.
EVENT REGISTRATION
• Approach1: Assigning the event handler script to an event tag attribute
<input type = "button" id = "myButton“ onclick = "alert('You clicked button!');" />

• If the handler consists of more than a single statement, a function is used


<input type = "button" id = "myButton“ onclick = "myButtonHandler();" />
EVENT REGISTRATION
• Approach2: assigning an event handler function’s name to the associated event
property on the object
document.getElementById("myButton").onclick = myButtonHandler;

• This statement must follow both the handler function and the form element so
that JavaScript has seen both before assigning the property
EVENT HANDLING
• Handling Events from Body Elements-Load
• Handling Events from Button Elements-Click
• Handling Events from Text Box and Password Elements-The Focus Event
• An HTML element is said to get focus when the user puts the mouse cursor over it
and clicks the left mouse button. An element can also get focus when the user tabs
to the element. When a text element has focus, any keyboard input goes into that
element. only one text element can have focus at one time
• An element becomes blurred when the user moves the cursor away from the
element and clicks the left mouse button or when the user tabs away from the
element
THE DOM 2 EVENT MODEL
• DOM 2 event model is more sophisticated and powerful than that of DOM 0
• The DOM 2 model is a modularized interface.
• One of the DOM 2 modules is Events, which includes several submodules
THE DOM 2 EVENT MODEL
• When an event occurs and an event handler is called, an object that
implements the event interface associated with the event type is implicitly
passed to the handler
• The properties of this object have information associated with the event
EVENT PROPAGATION
• The node of the document tree where the event is created is called the target
node
Three phases of event handling:
• Capturing phase
• Target node phase
• Bubbling phase
EVENT PROPAGATION
• Capturing phase:
• The event created at the target node starts at the document root node and
propagates down the tree to the target node.
• If there are any handlers for the event that are registered on any node
encountered in this propagation are checked to determine whether they are
Enabled
• Any enabled handler for the event that is found during capturing is executed.
EVENT PROPAGATION
• target node phase :
• When the event reaches the target node, the second phase takes place
• The handlers registered for the event at the target node are executed
EVENT PROPAGATION
• Bubbling phase :
• After execution of any appropriate handlers at the target node, the third phase
begins.
• The event bubbles back up the document tree to the document node.
• On this trip back up the tree, any handler registered for the event at any node
on the way is executed
EVENT PROPAGATION
EVENT REGISTRATION
• Event handler registration is done with the addEventListener method
• Three parameters:
• Name of the event, as a string literal
• The handler function
• A Boolean value that specifies whether the event is enabled during the
capturing phase
• node.addEventListener("change", chkName, false);
EVENT PROPAGATION
• Any handler can stop the event from further propagation by using the
stopPropagation method of the event object
• A method preventDefault prevents the default action of an event
• removeEventListener removes the event handler from an event
DOM TREE TRAVERSAL
• According to the W3C HTML DOM standard, everything in an HTML document
is a node:
• The entire document is a document node
• Every HTML element is an element node
• The text inside HTML elements are text nodes
• Every HTML attribute is an attribute node (deprecated)
• All comments are comment nodes
• With the HTML DOM, all nodes in the node tree
can be accessed by JavaScript
DOM TREE TRAVERSAL
• Node Relationships:
• The nodes in the node tree have a hierarchical relationship to each other
• The terms parent, child, and sibling are used to describe the relationships

• In a node tree, the top node is called the root (or root node)
• Every node has exactly one parent, except the root (which has no parent)
• A node can have a number of children
• Siblings (brothers or sisters) are nodes with the same parent
DOM TREE TRAVERSAL
DOM TREE TRAVERSAL
Navigating Between Nodes:
• parentNode
• childNodes[nodenumber]
• firstChild
• lastChild
• nextSibling
• previousSibling
DOM TREE MODIFICATION
Create a New Element:
• document.createElement() returns a new Node with the Element type takeing
an HTML tag name as a parameter
let div = document.createElement('div’);

• The innerHTML is a property of the Element allows us to get or set the HTML
markup contained within the element
element.innerHTML = 'new content’;
DOM TREE MODIFICATION
Append a Node to a List of Child Nodes of a Particular Parent Node
• appendChild() method allows us to insert a node at the end of the list of child
nodes of a particular parent node.
parentNode.appendChild(childNode);

Insert One Element Before an Existing Node as a Child Node of a Specified


Parent Node:
• insertBefore() JavaScript method takes two parameters, the newNode, and the
existingNode. insertBefore() returns the inserted child node.
parentNode.insertBefore(newNode, existingNode);
DOM TREE MODIFICATION
Replace a Child Element by a New Element
• replaceChild() JavaScript method takes two parameters to replace our first
element with the newly created one.
parentNode.replaceChild(newChild, oldChild);

Remove Child Elements of a Node:


• removeChild() JavaScript method takes just one parameter i.e the element you
want to remove.
let childNode = parentNode.removeChild(childNode);
THE NAVIGATOR OBJECT
• It indicates which browser is being used to view the HTML document
• The browser’s name is stored in the appName property of the object
• The version of the browser is stored in the appVersion property of the object
• These properties allow the script to determine which browser is being used
and to use processes appropriate to that browser
THE NAVIGATOR OBJECT
Dynamic documents with
JavaScript
DYNAMIC HTML
• Dynamic HTML:
• An HTML document that, in some way, can be changed while it is being displayed
by a browser
• The combination of HTML, style sheets and client-side scripts that enables the
creation of interactive and animated documents
• It is a collection of technologies that allows dynamic changes to documents defined
with HTML
• Specifically, a dynamic HTML document is an HTML 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.
POSITIONING ELEMENTS
• left and top properties dictate the distance from the left and top of some
reference point to where the element is to appear
• position interacts with left and top to provide a higher level of control of
placement and movement of elements
• position property has three possible values: absolute, relative, and static
POSITIONING ELEMENTS
• Absolute Positioning:
• The absolute value for position is specified when the element is to be placed
at a specific location in the document display without regard to the positions
of other elements

• When an element is absolutely positioned inside another positioned


element(one that has the position property specified), the top and left
property values are measured from the upper-left corner of the enclosing
element (rather than the upper-left corner of the browser window)
POSITIONING ELEMENTS
• Relative positioning:
• An element with position: relative; is positioned relative to its normal position
• Setting the top, right, bottom, and left properties of a relatively-positioned
element will cause it to be adjusted away from its normal position
• An element that has the position property set to relative, but does not specify
top and left property values, is placed in the document as if the position
attribute were not set at all. However, such an element can be moved later
• In both the case of an absolutely positioned element inside another element
and the case of a relatively positioned element, negative values of top and
left displace the element upward and to the left, respectively
POSITIONING ELEMENTS
• Static positioning:
• The default value for the position property is static
• Static positioned elements are not affected by the top, bottom, left, and right
properties
• A statically placed element initially cannot be displaced from its normal
position and cannot be moved from that position later
• An element with position: static; is not positioned in any special way; it is
always positioned according to the normal flow of the page
POSITIONING ELEMENTS
• Fixed positioning:
• An element with position: fixed; is positioned relative to the viewport, which
means it always stays in the same place even if the page is scrolled
• The top, right, bottom, and left properties are used to position the element
• Sticky positioning:
• An element with position: sticky; is positioned based on the user's scroll
position.
• A sticky element toggles between relative and fixed, depending on the scroll
position. It is positioned relative until a given offset position is met in the
viewport - then it "sticks" in place (like position:fixed).
MOVING ELEMENTS
ELEMENT VISIBILITY
• Document elements can be specified to be visible or hidden with the value
of their visibility property
• The two possible values for visibility are visible and hidden
CHANGING COLORS & FONTS
DYNAMIC CONTENT
STACKING ELEMENTS
• The placement of elements in this third dimension is controlled by the z-
index attribute of the element
• An element whose z-index is greater than that of an element in the same
space will be displayed over the other element, effectively hiding the
element with the smaller z-index value
• The JavaScript style property associated with the z-index attribute is zIndex
• Stack1.html, stack2.html
LOCATING THE MOUSE CURSOR
• Mouse-Event interface defines two pairs of properties that provide
geometric coordinates of the position of the element in the display that
created the event
• clientX and clientY, gives the coordinates of the element relative to the
upper-left corner of the browser display window in pixels.
• screenX and screenY gives coordinates of the element, but relative to the
client computer’s screen
• where.html
REACTING TO A MOUSE CLICK
• anywhere.html
SLOW MOVEMENT OF ELEMENTS
• The way to move an element slowly is to move it by small amounts many
times, with the moves separated by small amounts of time.
• JavaScript has two Window methods that are capable of this task: setTimeout
• and setInterval.
• setTimeout method takes two parameters: a string of JavaScript code
• to be executed and a number of milliseconds of delay before executing the
given code
• setTimeout("mover()", 20);
SLOW MOVEMENT OF ELEMENTS
• setInterval method has two forms:
• One form takes two parameters, exactly as does setTimeout.
• It executes the given code repeatedly, using the second parameter as the
interval, in milliseconds, between executions
• The second form of setInterval takes a variable number of parameters
• The first parameter is the name of a function to be called, the second is the
interval in milliseconds between the calls to the function, and the remaining
parameters are used as actual parameters to the function being called
• moveText.html,moveText2.html
DRAG AND DROP ELEMENTS
jQuery
INTRODUCTION
• jQuery is an open-source JavaScript library that simplifies the
interactions between an HTML/CSS document, or more precisely the
Document Object Model (DOM), and JavaScript.
• The purpose of jQuery is to make it much easier to use JavaScript on
website.
• It simplifies HTML document traversing and manipulation, browser
event handling, DOM animations, Ajax interactions, and cross-browser
JavaScript development
• Why to use jQuery?
• The jQuery library provides the following features:
• It helps us to manipulate HTML and CSS
• It helps us to manipulate DOM (Document Object Model) elements
• Provides event methods to trigger and respond to an events on a html
page such as mouse click, keypress etc.
• Effects and animations
• Implements AJAX calls.
ADDING JQUERY TO WEB PAGES
Downloading jQuery:
• There are two versions of jQuery available for downloading:
• Production version - this is for live website because it has been minified
and compressed
• Development version - this is for testing and development (uncompressed
and readable code)
ADDING JQUERY TO WEB PAGES
Downloading jQuery:
• The jQuery library is a single JavaScript file, and you reference it with the
HTML <script> tag

• Place the downloaded file in the same directory as the pages where you
wish to use it
ADDING JQUERY TO WEB PAGES
jQuery CDN
jQuery can be included from a CDN (Content Delivery Network)
Example: Google
JQUERY SYNTAX
• With jQuery we select (query) HTML elements and perform "actions" on
them
• The jQuery syntax is tailor-made for selecting HTML elements and
performing some action on the element(s)
$(selector).action()
• A $ sign to define/access jQuery
• A (selector) to "query (or find)" HTML elements
• A jQuery action() to be performed on the element(s)
JQUERY SYNTAX
• Examples:
THE DOCUMENT READY EVENT
• All jQuery methods are placed inside a document ready event

• This is to prevent any jQuery code from running before the document is
finished loading (is ready)
THE DOCUMENT READY EVENT
• It is good practice to wait for the document to be fully loaded and ready
before working with it.
• Failures:
• Trying to hide an element that is not created yet
• Trying to get the size of an image that is not loaded yet
• Shorter method for the document ready event:
JQUERY SELECTORS
• jQuery selectors allow us to select and manipulate HTML element(s)
• jQuery selectors are used to "find" (or select) HTML elements based on
their name, id, classes, types, attributes, values of attributes and much more
• It is based on the existing CSS Selectors, and in addition, it has some own
custom selectors
• All selectors in jQuery start with the dollar sign and parentheses: $()
JQUERY SELECTORS
• The element Selector:
• The jQuery element selector selects elements based on the element name
• Example: $("p")
JQUERY SELECTORS
• The #id Selector
• The jQuery #id selector uses the id attribute of an HTML tag to find the
specific element.
• An id should be unique within a page, so you should use the #id selector
when you want to find a single, unique element.
• $("#test")
JQUERY SELECTORS
• The .class Selector
• The jQuery .class selector finds elements with a specific class.
• To find elements with a specific class, write a period character, followed by
the name of the class:.
• $(“.test")
OTHER SELECTORS
• $("*") : Selects all elements

• $(this): Selects the current HTML element


OTHER SELECTORS
• $("p.intro") Selects all <p> elements with class="intro"

• $("p:first") Selects the first <p> element


OTHER SELECTORS
• $("ul li:first") Selects the first <li> element of the first <ul>
OTHER SELECTORS
• $("ul li:first-child") Selects the first <li> element of every <ul>
OTHER SELECTORS
• $("[href]") Selects all elements with an href attribute

• $("a[target='_blank']") Selects all <a> elements with a target attribute


value equal to "_blank“
OTHER SELECTORS
• $(":button") Selects all <button> elements and <input> elements of
type="button"

• $("tr:even") Selects all even <tr> elements


JQUERY SYNTAX FOR EVENT METHODS
• In jQuery, most DOM events have an equivalent jQuery method.
• To assign a click event to all paragraphs on a page:
• $("p").click();

• To define what should happen when the event fire we should spass a function
to the event: :
COMMONLY USED JQUERY EVENT METHODS
• $(document).ready()
• click()
• dblclick()
• mouseenter()
• mouseleave()
• mousedown()
• mouseup()
COMMONLY USED JQUERY EVENT METHODS
• hover()
• The hover() method takes two functions and is a combination of the
mouseenter() and mouseleave() methods.
COMMONLY USED JQUERY EVENT METHODS
• focus()
• blur()
• jQuery comes with a bunch of DOM related methods that make it easy
to access and manipulate elements and attributes
• text() - Sets or returns the text content of selected elements
• html() - Sets or returns the content of selected elements (including
HTML markup)
• val() - Sets or returns the value of form fields
• attr() -used to get attribute values
• jQuery methods that are used to add new content:
• append() - Inserts content at the end of the selected elements
• prepend() - Inserts content at the beginning of the selected elements
• after() - Inserts content after the selected elements
• before() - Inserts content before the selected elements
• To remove elements and content, there are mainly two jQuery methods:

• remove() - Removes the selected element (and its child elements)


• empty() - Removes the child elements from the selected element
• jQuery has several methods for CSS manipulation
• addClass() - Adds one or more classes to the selected elements
• removeClass() - Removes one or more classes from the selected elements
• toggleClass() - Toggles between adding/removing classes from the
selected elements
• css() - Sets or returns the style attribute for the selected elements.
• css("propertyname","value");
• css({"propertyname":"value","propertyname":"value",...});
• With jQuery, it is easy to work with the dimensions of elements and browser
window
• width() sets or returns the width of an element (excludes padding, border and
margin)
• height() sets or returns the height of an element (excludes padding, border and
margin)
• innerWidth() returns the width of an element (includes padding)
• innerHeight() returns the height of an element (includes padding)
• outerWidth() returns the width of an element (includes padding and border)
• outerHeight() returns the height of an element (includes padding and border)
JQUERY EFFECTS
• We can hide and show HTML elements with the hide() and show() methods

• The optional speed parameter specifies the speed of the hiding/showing, and
can take the following values: "slow", "fast", or milliseconds.
• The optional callback parameter is a function to be executed after the hide()
or show() method completes
• We can also toggle between hiding and showing an element with the toggle()
method
JQUERY EFFECTS
• We can hide and show HTML elements with the hide() and show() methods

• The optional speed parameter specifies the speed of the hiding/showing, and
can take the following values: "slow", "fast", or milliseconds.
• The optional callback parameter is a function to be executed after the hide()
or show() method completes
• We can also toggle between hiding and showing an element with the toggle()
method
JQUERY EFFECTS
We can fade an element in and out of visibility
• fadeIn() method is used to fade in a hidden element
• fadeOut() method is used to fade out a visible element
• fadeToggle() method toggles between the fadeIn() and fadeOut()
methods
JQUERY EFFECTS
We can create a sliding effect on elements using following slide methods
• slideDown() method is used to slide down an element
• slideUp() method is used to slide up an element.
• slideToggle() method toggles between the slideDown() and slideUp()
methods
JQUERY EFFECTS
• animate() method is used to create custom animations

• The required params parameter defines the CSS properties to be


animated
JQUERY EFFECTS
• stop() method is used to stop an animation or effect before it is finished

• The optional stopAll parameter specifies whether also the animation queue
should be cleared or not. Default is false, which means that only the active
animation will be stopped, allowing any queued animations to be performed
afterwards
• The optional goToEnd parameter specifies whether or not to complete the
current animation immediately. Default is false
• So, by default, the stop() method kills the current animation being performed
on the selected element
JQUERY CALLBACK FUNCTIONS
• JavaScript statements are executed line by line. However, with effects,
the next line of code can be run even though the effect is not finished.
This can create errors
• A callback function is executed after the current effect is finished
JQUERY - CHAINING
• Chaining allows us to run multiple jQuery methods (on the same
element) within a single statement
• To chain an action we append the action to the previous action
AngularJS
AngularJS is a discontinued free and open-source JavaScript-based web framework for
developing single-page applications. It was maintained mainly by Google and a community
of individuals and corporations. It aimed to simplify both the development and the testing
of such applications by providing a framework for client-side model–view–controller (MVC)
and model–view–viewmodel (MVVM) architectures, along with components commonly
used in web applications and progressive web applications.

AngularJS directives allowed the developer to specify custom and reusable HTML-like
elements and attributes that define data bindings and the behavior of presentation
components. Some of the most commonly used directives were:

ng-animate
A module provides support for JavaScript, CSS3 transition and CSS3 keyframe animation
hooks within existing core and custom directives.
ng-app
Declares the root element of an AngularJS application, under which directives can be used
to declare bindings and define behavior.
ng-aria
A module for accessibility support of common ARIA attributes.
ng-bind
Sets the text of a DOM element to the value of an expression. For example, <span ng-
bind="name"></span> displays the value of 'name' inside the span element. Any change to
the variable 'name' in the application's scope reflect instantly in the DOM.
ng-class
Conditionally apply a class, depending on the value of a Boolean expression.
ng-controller
Specifies a JavaScript controller class that evaluates HTML expressions.
ng-if
Basic if statement directive that instantiates the following element if the conditions are
true. When the condition is false, the element is removed from the DOM. When true, a
clone of the compiled element is re-inserted.
ng-init
Called once when the element is initialized.
ng-model
Similar to ng-bind, but establishes a two-way data binding between the view and the scope.
ng-model-options
Provides tuning for how model updates are done.
ng-repeat
Instantiate an element once per item from a collection.
ng-show & ng-hide
Conditionally show or hide an element, depending on the value of a Boolean expression.
Show and hide is achieved by setting the CSS display style.
ng-switch
Conditionally instantiate one template from a set of choices, depending on the value of a
selection expression.
ng-view
The base directive responsible for handling routes[12] that resolve JSON before rendering
templates driven by specified controllers.
Since ng-* attributes are not valid in HTML specifications, data-ng-* can also be used as a
prefix. For example, both ng-app and data-ng-app are valid in AngularJS.

AngularJS lets you extend HTML with new attributes called Directives.

AngularJS has a set of built-in directives which offers functionality to your


applications.

AngularJS also lets you define your own directives.

AngularJS Directives
AngularJS directives are extended HTML attributes with the prefix ng-.

The ng-app directive initializes an AngularJS application.

The ng-init directive initializes application data.


The ng-model directive binds the value of HTML controls (input, select,
textarea) to application data.

Read about all AngularJS directives in our AngularJS directive reference.

Example
<div ng-app="" ng-init="firstName='John'">

<p>Name: <input type="text" ng-model="firstName"></p>


<p>You wrote: {{ firstName }}</p>

</div>
Try it Yourself »

The ng-app directive also tells AngularJS that the <div> element is the
"owner" of the AngularJS application.

Data Binding
The {{ firstName }} expression, in the example above, is an AngularJS data
binding expression.

Data binding in AngularJS binds AngularJS expressions with AngularJS data.

{{ firstName }} is bound with ng-model="firstName".

In the next example two text fields are bound together with two ng-model
directives:

Example
<div ng-app="" ng-init="quantity=1;price=5">

Quantity: <input type="number" ng-model="quantity">


Costs: <input type="number" ng-model="price">

Total in dollar: {{ quantity * price }}

</div>
AngularJS Expressions
AngularJS expressions can be written inside double
braces: {{ expression }}.

AngularJS expressions can also be written inside a directive: ng-


bind="expression".

AngularJS will resolve the expression, and return the result exactly where the
expression is written.

AngularJS expressions are much like JavaScript expressions: They can


contain literals, operators, and variables.

Example {{ 5 + 5 }} or {{ firstName + " " + lastName }}

Example
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angu
lar.min.js"></script>
<body>

<div ng-app="">
<p>My first expression: {{ 5 + 5 }}</p>
</div>

</body>
</html

An AngularJS module defines an application.

The module is a container for the different parts of an application.

The module is a container for the application controllers.

Controllers always belong to a module.

Creating a Module
A module is created by using the AngularJS function angular.module
<div ng-app="myApp">...</div>

<script>

var app = angular.module("myApp", []);

</script>

The "myApp" parameter refers to an HTML element in which the application


will run.

Now you can add controllers, directives, filters, and more, to your AngularJS
application.

Adding a Controller
Add a controller to your application, and refer to the controller with the ng-
controller directive:

Example
<div ng-app="myApp" ng-controller="myCtrl">
{{ firstName + " " + lastName }}
</div>

<script>

var app = angular.module("myApp", []);

app.controller("myCtrl", function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
});

</script>
2. Setting up
AngularJS
Step 1: Create a New Folder
Step 2: Open Notepad
Step 3 : Paste the code below into notepad
<html ng-app> <head>
<title>KTG AngularJS Tutorial</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
</head>
<body> My First Program </body>
</html>
http://kindsonthegenius.blogspot.com/2018/06/angularjs-tutorial-for-beginers-course.html
Step 3: Save with a name test.html

Step 4: Open the location you saved the file. Right-click and open the file in internet explorer

If it displays a web page with the text KTG AngularJS Tutorial, the congrat. If not, let me
know in the comment box below.
Step 3: Download AngularJS and save it in the same folder with the file
https://ajax.googleapis.com/ajax/libs/angularjs/1.7.2/angular.min.js

Step 4: Replace the CDN link with the link to the local file
Step 5: Do a test.
3. Your First
AngularJS Application
In the First part, the user will enter his firstname and lastname, then when the button is clicked,
you will display a greeting like:
Hello <firstname> <lastname>

In the Second part we would allow user to enter two numbers into textboxes and then we show
the result

http://kindsonthegenius.blogspot.com/2018/08/angularjs-tutorial-for-beginners-3-your.html
Step 1: Open the Folder you created in Tutorial 2, which contains the two files:
angular.min.js and Lesson 2 .html

Step 2: Open notepad and paste the following code or you can decide to type it out by
yourself.

http://kindsonthegenius.blogspot.com/2018/06/angularjs-tutorial-for-beginers-course.html
var FirstApp = angular.module('FirstApp', []);
FirstApp.controller('MyController', function($scope){
$scope.Greet = function() {
var firstname = $scope.fname;
var lastname = $scope.lname;
$scope.greeting = "Hello, " + firstname + " " + lastname;
};
});
Step 3: Save it as Scripts.js in the same folder

Step 4: Open the html file you created and modify it with the following code
<!doctype html>
<html ng-app="FirstApp">
<head>
<title>KTG AngularJS Tutorial</title>
<script src="angular.min.js"></script>
<script src="Script.js"></script>
</head>
<body ng-controller="MyController">
Enter Firstname: <input ng-model="fname" type="" /> <br /> <br />
Enter Lastname: <input ng-model="lname" type ="" /> <br />
<button ng-click="Greet()"> Click</button> <br /> <br />
{{greeting}}
</body>
</html>
4. AngularJS
Modules and Controllers

http://kindsonthegenius.blogspot.com/2018/06/angularjs-tutorial-for-beginers-course.html
What is a Module in AngularJS?

• A module in AngularJS is a container that holds various parts of an AngularJS application


such as controller, directives, services and filters.
• It serves as the entry point to the application.
• A module specifies how the AngularJS starts.
• A module is the first thing you create in an AngularJS application.

http://kindsonthegenius.blogspot.com/2018/06/angularjs-tutorial-for-beginers-course.html

http://kindsonthegenius.blogspot.com/2018/06/angularjs-tutorial-for-beginers-course.html
How to Create a Model

To create a module, use the AngularJS syntax below and specify the name of the
module.

var FirstApp = angular.module('FirstApp', []);

In creating a module, you specify two parameters:


• the name of the module
• array of dependencies the module depends on.

http://kindsonthegenius.blogspot.com/2018/06/angularjs-tutorial-for-beginers-course.html
What is a Controller in AngularJS?

The next thing you create after creating a module, is a controller.

A controller in AngularJS is function that controls the communication between the


application logic and the view.
For example, a controller would manage retrieving data from the database and
displaying it in a html page.

http://kindsonthegenius.blogspot.com/2018/06/angularjs-tutorial-for-beginers-course.html
How to Create a Controller

To create a controller, simply create a function and assign it to a variable as shown below

var MyController = function($scope) { $scope.name =


"Welcome to AngularJS"; }

In this controller, we pass a parameter called $scope to the controller function.


$scope is used to make variables available in the view.
So any variable attached to the $scope is accessible from the view using the binding expression {{ }}.

http://kindsonthegenius.blogspot.com/2018/06/angularjs-tutorial-for-beginers-course.html
How Register a Controller with a Module
The next step after creating a module and a controller is to register the controller with a module.
To register a controller with a module, use the syntax below:
Name of controller
Name of controller function
FirstApp.Controller("MyController", MyController);

Now That we have created a module and a controller, and registered a controller with a module, we can now move
to the next step and that is how to use the module and controller in a view.

For this we need to discuss AngularJS directives in Tutorial 5.

http://kindsonthegenius.blogspot.com/2018/08/angularjs-tutorial-for-beginners-3-your.html

http://kindsonthegenius.blogspot.com/2018/06/angularjs-tutorial-for-beginers-course.html

You might also like