Awt Notes
Awt Notes
- 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)
- Domain names
- Form: host-name.domain-names
- 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
- Web or Internet?
- The Web uses one of the protocols, http, that
runs on the Internet--there are several others
(telnet, mailto, etc.)
- Virtual hosts
ServerName
ServerRoot
ServerAdmin,
DocumentRoot
Alias
Redirect
DirectoryIndex
UserDir
- IIS
scheme:object-address
- Type specifications
- Form:
type/subtype
- Experimental types
- Request Phase
- Form:
HTTP method domain part of URL HTTP ver.
Header fields
blank line
Message body
Accept: text/plain
Accept: text/*
If-Modified_since: date
Content-length: 488
Content-type: text/html
- Response Phase
- Form:
Status line
Response header fields
blank line
Response body
1 => Informational
2 => Success
3 => Redirection
4 => Client error
5 => Server error
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
- Plug ins
- Filters
- XML(
- A meta-markup language
- No presentation details
- JavaScript
- Java
- Perl
- PHP
- An alternative to CGI
- Similar to JavaScript
- Recent versions:
- HTML 4.0 – 1997
- Introduced many new features and deprecated
many older features
- HTML 4.01 - 1999 - A cleanup of 4.0
- Tag format:
- Opening tag: <name>
- Closing tag: </name>
- Paragraph Elements
- Line breaks
<!-- 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>
- Blockquotes
- Content of <blockquote>
- Boldface - <b>
- Italics - <i>
- Larger - <big>
- Smaller - <small>
- Monospace - <tt>
Example: x<sub>2</sub><sup>3</sup>
Display: x23
- Character Entities
- Horizontal rules
- <hr /> draws a line across the display, after a
line break
<!-- 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>
- Ordered lists
- Nested lists
<tr>
<th colspan = "3"> Fruit Juice Drinks </th>
</tr>
<tr>
<th> Orange </th>
<th> Apple </th>
<th> Screwdriver </th>
</tr>
- Table Sections
- Header, body, and footer, which are the elements:
thead, tbody, and tfoot
action =
"http://www.cs.ucp.edu/cgi-bin/survey.pl"
- Widgets
1. Text
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>
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>
4. Menus (continued)
- Examples:
<frameset rows = "150, 200, 300">
→SHOW frames.html
→ SHOW nested_frames.html
- Closing tags
- Element nesting
• 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:
<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
• style=“property1:value1;propert2:value;..”
STYLE SPECIFICATION FORMATS
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}
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
• 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
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
• 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
• <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
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.
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>
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>
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.
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.
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
<output> tag
The HTML <output> tag is a container element that is used to store the output of a
<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
Google Maps:
<!DOCTYPE html>
<html>
<body>
<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:
2. function myMap() {
var mapProp = {
center:new google.maps.LatLng(51.508742,-0.120850),
zoom:5,
};
google.maps.Map(document.getElementById("googleMap"),mapProp);
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).
<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.
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.
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:
Applications:
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.
We can download ready-to-use compiled code to easily drop into the project, which
includes:
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:
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>
The grid system is responsive, and the columns will re-arrange automatically
depending on the screen size.
Grid Classes
The classes above can be combined to create more dynamic and flexible
layouts.
<!-- 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>
• 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.
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:
<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>
<div class="row">
<div class="col-sm-4">.col-sm-4</div>
<div class="col-sm-8">.col-sm-8</div>
</div>
Tables:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<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>
<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-hover class adds a hover effect (grey background color) on table
rows.
You can also decide when the table should get a scrollbar, depending on the
screen width:
Contextual Classes
Contextual classes can be used to color the whole table (<table>), the table
rows (<tr>) or table cells (<td>).
Example:
Images:
Float an image to the left with the .float-start class or to the right
with .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">
The .img-fluid class applies max-width: 100%; and height: auto; to the image:
Bootstrap Jumbotron:
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.
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":
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
• .btn-lg
• .btn-sm
• .btn-xs
A block level button spans the entire width of the parent element. Add
class .btn-block to create a block level button.
Badges
Badges are numerical indicators of how many items are associated with a
link. We use the .badge class for the same.
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.
<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
<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">
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>
To add form elements inside the navbar, add the .navbar-form class to a
form element and add an input(s).
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:
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".
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 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 data-slide-to attribute specifies which slide to go to, when clicking on the
specific dot.
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.
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 class="item">
<img src="chicago.jpg" alt="Chicago">
</div>
<div class="item">
<img src="ny.jpg" alt="New York">
</div>
</div>
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
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.) .
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.
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.
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>
echo $myvar;
?>
</P>
$bar = &$foo;
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.
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.
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.
In double-quoted string literals, escape sequences are recognized, and embedded variables are replaced by
their current values.
$sum=10;
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.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.
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
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
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.
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.
print "Apples are red <br /> Kumquats aren't <br />";
print( 47 ); produce 47
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.
%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.
<body>
<p>
<?php
8
?>
</p>
</body>
</html>
OUTPUT
Today is 2014/09/24
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 ===.
There are six Boolean operators: and, or, xor, !, &&, and | |. The and and && operators perform the same
operation, as do or and | |.
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:
{$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;
}
while
$fact=1;
$count=1
While($count<$n) {
$count++;
$fact *=$count;
do-while
$count = 1;
$sum = 0;
do
$sum += $count;
$count++;
for
10
for($count=1,$fact=1;$count<$n;$count++)
$fact *=$count;
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:
• 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
• In the following example the index is automatically assigned (the index starts at 0):
$list==array(17,24,45,91);
Array construct can be used to create empty array.in the following statement $list becomes an array
variable with no element.
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:
• 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
• This example is the same as the one above, but shows a different way of creating the array:
• 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
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:
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 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"];
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.
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.
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:
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.
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.
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.
$city = current($cities);
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);
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.
{$name = $employee["key"];
$salary = $employee["value"];
• 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.
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.
• 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:
• 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:
For example:
18
$lows = array("Mon" => 23, "Tue" => 18, "Wed" => 27);
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>
</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 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.
{$first = abs($first);
$second = abs($second);
return $first;
else
return $second;}
Pass-by-reference
• 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.
$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 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.
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))
else
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.
<!DOCTYPE html>
23
<html lang=”en”>
<head>
</head>
24
• 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.
• 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.
• > 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.
Wt12.php
<!DOCTYPE html>
<html lang=”en”>
<head>
</head>
<body>Insert two numbers in the form and hit submit button <br>
</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);
?></body></html>
<!DOCTYPE html>
<html lang=”en”>
<head>
<style type=”text/css”>
</style>
</head>
<body>
<table>
<tr>
<th>Product Name</th>
<th>Price</th>
<th>quantity</th>
</tr>
27
<tr>
<td>Unpopped Popcorn</td>
<td>$3.00</td>
</tr>
<tr>
<td>Caramel Popcorn</td>
<td>$3.50</td>
</form></body></html>
OUTPUT:
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>
</head>
<body>
<?php>
29
$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;
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
EXAMPLE:
REGISTRATION PAGE
<form method="post" action="">
<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>
11. FILES
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,
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.
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:
This statement reads characters from testdata.dat until it finds a newline character, encounters the end-of-file
marker, or has read 99 characters.
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.
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
<?php
$myfile = fopen(“test.txt", "r") or die("Unable to open file!");
{
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);
?>
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.
• LOCK_SH - Shared lock (reader). Allow other processes to access the file
• LOCK_EX - Exclusive lock (writer). Prevent other processes from accessing the file
<?php
$file = fopen("test.txt","w+");
// exclusive lock
if (flock($file,LOCK_EX))
{ fwrite($file,"Write something");
// release lock
flock($file,LOCK_UN);
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.
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
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).
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.
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>
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>
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"]) ;
The session_start function creates a session ID. Session variables are stored in the $_SESSION array.
<body>Insert two numbers in the form and hit submit button <br>
</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);
}?></body></html>
<?php
// PHP code to check whether a 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
1. What are the different ways to create an array in PHP? Explain with example?
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. What is the significance of cookies in web? How can a cookie be created and destroyed in PHP?
<html>
<head>
</head>
<body>
<form method="post">
</form>
<?php
41
$fact = 1;
$number = $_POST['number'];
//start loop
?>
</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
<?php
$a=10;
$b=20;
$temp=$a;
$a=$b;
$b=$temp;
?>
Output
Value of a: 10
Value of b: 20
Value of a: 20
Value of b: 10
$num=10;
if($num%2==0)
{
echo "Even number";
}
else
{
echo "Odd number";
}
?>
OUTPUT
Even number
43
<?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);
}
?>
OUTPUT
$string = "hitesh";
$length = strlen($string);
?>
OUTPUT
hsetih
<?php
44
function printFibonacci($n)
{
$first = 0;
$second = 1;
$first = $second;
$second = $third;
}
}
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
• 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
• 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)
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
• 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”];
• 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
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 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
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 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?
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++.
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.
A variable can have a short name, like x, or a more descriptive name, like carname.
Variable names are case sensitive (y and Y are two different variables)
Variable names must begin with a letter or the underscore character
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>
</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
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.
If you assign values to variables that have not yet been declared, the variables will automatically be
declared.
These statements:
x=5;
carname="Scorpio";
var x=5;
var carname="Scorpio";
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
y=x-5;
z=y+5;
JavaScript Operators
The operator = is used to assign values.
y=5;
z=2;
x=y+z;
Page 5
JAVASCRIPT Notes
Arithmetic operators are used to perform arithmetic between variables and/or values.
Given that y=5, the table below explains the arithmetic operators:
Given that x=10 and y=5, the table below explains the assignment operators:
The + operator can also be used to add string variables or text values together.
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;
After the execution of the statements above, the variable txt3 contains:
x=5+5;
document.write(x);
x="5"+"5";
document.write(x);
x=5+"5";
document.write(x);
x="5"+5;
document.write(x);
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:
Comparison operators can be used in conditional statements to compare values and take action depending
on the result:
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:
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.
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
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>
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>
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.
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
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
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 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
}
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 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
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.
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 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.
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:
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.
Page 20
JAVASCRIPT Notes
Places an Event Handler as an attribute within an <A HREF= > tag, like this:
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.
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.
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
This is just like the first line, but it uses an onMouseOver instead of an onClick.
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:
Nonetheless, the entire code for the function could appear in quotation marks rather than a function call:
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.
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>
function doit() {
// alert("Everything is \"loaded\" and loaded = " + loaded);
alert('Everything is "loaded" and loaded = ' + loaded);
}
</SCRIPT>
<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.
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.
Page 24
JAVASCRIPT Notes
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.
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,
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 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.:
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
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();
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.
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 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:
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:
Page 29
JAVASCRIPT Notes
The other properties listed here are either more advanced or seldom used. For now, we'll
stick to the basics.
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
Create an 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:
Page 32
JAVASCRIPT Notes
You could also pass an integer argument to control the array's size:
2:
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.
document.write(myCars[0]);
Saab
To modify a value in an existing array, just add a new value to the array with a specified index number:
myCars[0]="Opel";
document.write(myCars[0]);
Opel
Page 33
JAVASCRIPT Notes
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):
And in the following example we set a Date object to be 5 days into the future:
Note: If adding five days to a date shifts the month or year, the changes are handled automatically by the
Date object itself!
The following example compares today's date with the 14th January 2010:
Math Object
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));
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());
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));
String object
Examples of use:
The following example uses the length property of the String object to find the length of a string:
12
The following example uses the toUpperCase() method of the String object to convert a string to
uppercase letters:
HELLO WORLD!
Page 36
JAVASCRIPT Notes
Window Object
The Window object is the top level object in the JavaScript hierarchy.
A Window object is created automatically with every instance of a <body> or <frameset> tag.
Page 37
JAVASCRIPT Notes
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).
Page 38
JAVASCRIPT Notes
the document
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.
Page 39
JAVASCRIPT Notes
Form Object
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).
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
Image Object
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).
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).
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.
Page 42
JAVASCRIPT Notes
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">
Page 43
JAVASCRIPT Notes
<!-- This script and many more are available free online at -->
<!-- Begin
function validateZIP(field) {
var hyphencount = 0;
return false;
if (valid.indexOf(temp) == "-1") {
return false;
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>
</center>
<p><center>
</center><p>
Page 45
REGULAR EXPRESSIONS AND REGEXP OBJECT
http://www.tutorialspoint.com/javascript/javascript_regexp_object.htm Copyright © tutorialspoint.com
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 −
or simply
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
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
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.
php* It matches any string containing a p followed by zero or more instances of the
sequence hp.
Literal characters
Character Description
Alphanumeric Itself
\t Tab \u0009
\n Newline \u000A
\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 non-whitespace character
\d a digit 0 − 9
\D a non-digit
\W a non-word character
Modifiers
Several modifiers are available that can simplify the way you work with regexps, like case
sensitivity, searching in multiple lines, etc.
Modifier Description
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
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
toSource Returns an object literal representing the specified object; you can use this
value to create a new 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:
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.
• 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
• 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
• 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
• 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
• 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
• 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);
• 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
• 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:
• 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 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 Directives
AngularJS directives are extended HTML attributes with the prefix ng-.
Example
<div ng-app="" ng-init="firstName='John'">
</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.
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">
</div>
AngularJS Expressions
AngularJS expressions can be written inside double
braces: {{ expression }}.
AngularJS will resolve the expression, and return the result exactly where the
expression is written.
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
Creating a Module
A module is created by using the AngularJS function angular.module
<div ng-app="myApp">...</div>
<script>
</script>
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>
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?
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.
http://kindsonthegenius.blogspot.com/2018/06/angularjs-tutorial-for-beginers-course.html
What is a Controller in AngularJS?
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
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.
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