FIP Chap 2,3 and 4 - Client-Side Internet Programming
FIP Chap 2,3 and 4 - Client-Side Internet Programming
4
Client-side scripting Tasks
Client-side scripting
Validates user input
Accesses the browser
Enhances Web pages with ActiveX® controls, applets, etc.
Manipulates browser documents
Reduces number of requests that need to be passed to server
Browser dependency
Viewable to users through View Source command
JavaScript most popular client-side script
5
Chapter 2
Client side Programming Using HTML
Markup languages are designed for the processing,
definition and presentation of text.
The language specifies code for formatting, both the layout and
style, within a text file. The code used to specify the formatting are
called tags.
A markup language is a set of tags and/or a set of rules for
creating tags that can be embedded in digital text to provide
additional information about the text in order to facilitate
automated processing of it, including editing and formatting
for display or printing.
A markup language is a system for annotating a document in
a way that is syntactically distinguishable from the text.
6
Markup languages …history
Motivations: Gopher & the Internet Superhighway
Standard Generalized Markup Language (SGML)-1986
GML + Charles Goldfarb = SGML
eXtensible Markup Language=XML
HTML-1997
XML and XHTML -2000
HTML5 -2014
7
HyperText Markup Language (HTML)
A markup language, i.e. it’s used to markup content, in modern
usage, HTML describes the semantic meaning of content: it
marks what content is a heading, what content is
a paragraph, what content is a definition, what content is
an image, what content is a hyperlink, and so forth.
Used to tell the browser what to do, and what props to use and
having series of tags that are integrated into a text document
It is the lingua franca for publishing hypertext on the World Wide
Web
Allow to embed other scripting languages to manipulate design
layout, text and graphics
Not case sensitivity.
Current version is HTML5
8
HTML Document
Composed of several tags: the first tag turns the action on,
and the second turns it off and the second tag(off switch)
starts with a forward slash
Should have an .htm or .html file name extension
9
HTML Document (cont’d)
HTML content is normally written in .html files. By using
the .html extension, your editor, computer, and browser
should automatically understand that this file will contain
content marked up in HTML.
HTML pages are tag-based documents
Really plain ASCII text files
Don't look like documents they represent
Tags indicate how processing program should display text and graphics
Designed to describe hypertext, not paper
Processed by browsers "on the fly"
Tags usually appear in pairs
Most have reasonable names or mnemonics
Most can be modified by attributes/values
10
HTML Document Structure
The HTML document is divided into two major parts:
HEAD: contains information about the document:
Title of the page (which appears at the top of the browser window)
Meta tags: used to describe the content (used by Search engines)
JavaScript
and Style sheets generally require statements in the
document Head
BODY: Contains the actual content of the document
This is the part that will be displayed in the browser
window
HTML Elements
11
HTML Document Structure (cont’d)
General Structure of HTML files:
<html> Start Tag
<head>
<title> Web page title
</title>
</head>
<body>
statement
…….
</body>
</html> End Tag
12
HTML Document Structure (cont’d)
Example1 HTML code:
<HTML>
<head>
<title>Hello World</title>
</head>
<body bgcolor = “#000000”>
<font color = “#ffffff”>
<H1>Hello World</H1>
</font>
</body>
</HTML>
13
HTML Elements
Names enclosed in < and >
Commonly have a start tag and end tag
Start tag format: <tag_name>
End tag format: </tag_name> [ note the / after < ]
E.g. <strong>bold text</strong>
Some tags may not have end tags
E.g. <br>
Tags may have attributes
<tag_name attr1=“val1” attr2=“val2” …>…</tag_name>
E.g. <font face=“arial” size=“9”>Hello</font>
Not case sensitive
14
Type of tags
Metadata tags- <title> ,<base>, <link>,<meta>. <style>
Section tags: <body>, <head> , <div> ,<frameset> ,<frame>,
<h1>..<h6> ,<p>
Text-level appearance tags: <b>,<em> ,<strong>,
<del>,<sub>
Grouping tags: <dl>, <dt>, <ol>, <li>, <select>, <option>
Image tag: <img>
Anchor tag: <a>
Table tag: <table> ,<th> ,<tr> ,<td>
Script tag: <script>
Embeded content tags: <applet>,<object>
Other tags: <br> ,<hr>
15
Basic HTML Tags
Html- everything in the document should be within
<html> &</html>
Head- contains information which is not displayed in the
browser display area such as action-scripting (Javascript),
styles (CSS) and general information referenced in the
whole document
may contain other tags in it
format: <head>…</head>
Title- sets the title of the web page to be displayed in the
browser’s title bar.
found within the <head> tag.
format: <title>…</title>
16
HTML Tags (cont’d)--- Attributes
<tag attributeA="valueA" attributeB="valueB"> content </tag>
Body:
contains the visible part of the web page
displayed in the display area of the browser
contains several other tags and content in it
format: <body>…</body>
attributes:
bgcolor=“color”
background=“img url”
text=“text color”
link=“link color”
alink=“active link color”
vlink=“visited link color”
…
17
HTML Tags (cont’d)
Headings:
predefined formats for text presentation
six heading formats defined in HTML: <h1> up to <h6>
<h1> the largest font size
<h6> the smallest font size
Format:
<h1>…</h1>
E.g. <h2>a text in heading two</h2>
bold
makes a text appear in bold
Format: <b>…</b> or <strong>…</strong>
E.g. <b>a text in bold</b>
18
HTML Tags (cont’d)---Heading
HTML headings
Heading are defined with the <h1> to <h6> tags. Output
19
HTML Tags (cont’d)
italics
makes a text appear in italics
Format: <i>…</i> or <em>…</em>
E.g. <i>a text in italics</i>
underline
makes a text appear underlined
Format: <u>…</u>
E.g. <u>underlined text</u>
Paragraph:
defines a paragraph
Format: <p>…</p>
20
HTML Tags (cont’d)
E.g. <p>this is a paragraph of text. it has a new line before and
after it.</p>
The browser inserts a new line before and after the text in the
paragraph tag.
attribute:
align=“alignment” {left, right, center, justify}
line break:
inserts a new line
Format: <br>
E.g. line one <br> line two <br> line three <br> line four
21
HTML Tags (cont’d)
Lists
Unordered Lists (ul)
define bulleted lists
Format:
<ul>
<li>…</li>
<li>…</li>
…
</ul>
Atribute:
type=“bullet type” {disc, circle, square}
E.g.
<ul type=“square”>
<li>book</li><li>marker</li><li>chalk</li></ul>
22
HTML Tags (cont’d)
Ordered Lists (ol)
define numbered lists
Format:
<ol>
<li>…</li>
<li>…</li>
…
</ol>
Atribute:
type=“number type” {1, i, I, a, A}
E.g.
<ol type=“i”> <li>book</li><li>marker</li><li>chalk</li></ol>
23
HTML Tags (cont’d)
Images
insert images in an html document
Format: <img> {no end tag}
Attributes:
src=“img url”
alt=“alternate text”
border=“border width”
width=“image width”
height=“image height”
supported image formats:
gif, jpg/jpeg, png
E.g. <img src=“assets/images/logo.gif” alt=“Site Logo”>
24
HTML Tags (cont’d)
Anchor
defines a hyperlink or a named anchor
used for navigation
Format: <a>…</a>
Attributes:
href=“url”
target=“target” { _self, _blank }
name=“anchor name”
E.g.
<a href=“home.htm”>Go to home</a>
<a href=“http://www.google.com” target=“_blank”>Google</a>
25
HTML Tags (cont’d)
Navigation with anchors
named anchors
named places in an html document
Format: <a name=“anchor_name”></a>
E.g. <a name=“top”></a>
linking to anchors
Format:
<a href=“#anchor_name”>link text</a> {on the same page}
E.g.
<a href=“#top”>Top of page</a> {assuming the example above}
<a href=“http://www.hu.edu.et/history.htm#establishment”>
Establishment of HU</a>
26
HTML Tags (cont’d)
Tables
Insert tabular data
Design page layout
Powerful, flexible information delivery
Used to reflect or impart structure
A table is a container
<table> ... </table>
Tags involved: <table>, <tr>, <td>, <th>, <caption>
27
HTML Tags (cont’d)
Format:
<table>
<caption>table caption</caption>
<tr>
<td>…</td> <td>…</td> …
</tr>
<tr>
<td>…</td> <td>…</td> …
</tr>
…
</table>
28
HTML Tags (cont’d)
E.g.
<table>
<caption align=“center” valign=“bottom”>table 1.0</caption>
<tr>
<th>Column 1</th> <th>Column 2</th>
</tr>
<tr>
<td>Cell 1</td> <td>Cell2</td>
</tr>
<tr>
<td>Cell 3</td> <td>Cell 4</td>
</tr>
29
</table>
HTML Tags (cont’d)
Table attributes:
align=“alignment” {left, center, right}
bgcolor=“color”
width=“table width” {absolute or relative}
border=“border width”
bordercolor=“color”
cellspacing=“space amount” {in pixels}
cellpadding=“padding amount” {in pixels}
…
30
HTML Tags (cont’d)
Table row attributes:
align=“alignment” {left, center, right}
bgcolor=“color”
height=“height”
valign=“alignment” {top, middle, bottom}
Table data/heading attributes:
align=“alignment”
valign=“alignment”
width=“width”
bgcolor=“color”
Unless otherwise specified, <tr> and <td> inherit
attributes of <table> whenever it applies.
31
HTML Tags (cont’d)
Cells spanning multiple rows/columns
two additional attributes of <td> and <th>
colspan=“num columns”
rowspan=“num rows”
E.g. (colspan)
<table>
<tr> <td colspan=“2”>Cell 1</td> <td>Cell 2</td> <td>Cell 3</td> </tr>
<tr> <td>Cell 4</td> <td>Cell 5</td> <td>Cell 6</td> <td>Cell 7</td> </tr>
<tr> <td colspan=“4”>Cell 8</td> </tr>
</table>
32
HTML Tags (cont’d)
E.g. (rowspan)
<table>
<tr> <td rowspan=“3”>Cell 1</td> <td>Cell 2</td> <td>Cell 3</td> </tr>
<tr> <td>Cell 4</td> <td>Cell 5</td> </tr>
<tr> <td>Cell 6</td> <td>Cell 7</td> </tr>
</table>
E.g. (hybrid)
<table>
<tr> <th colspan=“3”>Title</th> </tr>
<tr> <th rowspan=“3”>Cell 1</th> <td>Cell 2</td> <td>Cell 3</td> </tr>
<tr> <td>Cell 4</td> <td>Cell 5</td> </tr>
<tr> <td>Cell 6</td> <td>Cell 7</td> </tr>
</table>
33
HTML Forms
Used to gather input from users
The input is usually sent to a server-side script for
processing
34
HTML Forms (cont’d)
POST
For large & secure data
Input is sent as a data stream after the request URL
Tags
The <form> tag
Contains all input elements in the form
Defines the method of sending data
Defines the server-side script responsible for accepting the data
35
HTML Forms (cont’d)
Attributes:
name=“name”
method=“method” {get, post}
action=“url” {url of the server-side script to post data to}
enctype=“enctype” {multipart/form-data, text/plain, … }
multipart/form-data – used when uploading files
Ex.
<form method=“post” action=“search.php”>
….
</form>
36
HTML Forms (cont’d)
<input> tag
used to define input fields in a form
several types of input fields
{textbox, listbox, checkbox, radio, button, …}
Attributes:
name=“name”
type=“type”
{text, hidden, password, file, submit, reset, button, checkbox, radio,
image}
value=“value”
disabled=“disabled”
checked=“checked”
37
HTML Forms (cont’d)
The possible input types:
text – input text box
hidden – a hidden field for storing values
password – password input box
file – input box for file uploading (browse)
submit – a button that submits the form
reset – a button that resets form fields to their original values
button – a general purpose button
checkbox – a check box
radio – a radio button (option button)
image – an image button that submits the form
38
HTML Forms (cont’d)
Other input fields
<textarea> tag
used to input a large block of text
Tag format: <textarea>…</textarea>
Attributes:
name=“name”
cols=“num_columns”
rows=“num_rows”
readonly=“readonly”
wrap=“wrap_type” {off, hard, soft, virtual, physical}
39
HTML Forms (cont’d)
<select> tag
used to create a select box
Tag format:
<select>
<option>…</option>
<option>…</option>
…
</select>
Attributes:
<select>
name=“name”
multiple=“multiple” {enables selection of multiple items}
disabled=“disabled”
40
HTML Forms (cont’d)
<option>
value=“value”
selected=“selected”
disabled=“disabled” {browser compatibility: Firefox ?}
Ex.
1. <select name=“department”>
<option value=“1”>Computer Science</option>
<option value=“2”>Information Science</option>
<option value=“3”>Computer Engineering</option>
</select>
2. Modify the above input so that Information Science is selected by
default.
41
HTML Forms (cont’d)
submit & reset buttons
the vlaue attribute is the caption of the buttons
Ex. <input type=“submit” value=“ok”>
inserts a button with the caption (label) ok.
file upload fields
Ex. <input type=“file” name=“doc”>
<label> tag
used to give labels to input fields
Ex.
<label>First Name:
<input type=“text” name=“fname”>
</label>
42
HTML Forms (cont’d)
Exercises:
1. Create an HTML page which displays a login screen with
a username field
a password field
a department field {select box with values:
1. Computer Science
2. Information Science
3. Information technology
a button to submit the form
a button to reset the content of the form
43
HTML Forms (cont’d)
2. Create an HTML page which displays student registration screen with
a name field
an ID field
44
HTML5
45
HTML5 Overview
HTML5 is the latest and the most enhanced version of html
that aims to make HTML more useful for creating internet
and web applications as well as semantically marked up
documents
It is the standard for structuring and presenting content on the
WWW
HTML5 offers new features (elements, attributes, event
handlers, and APIs) for easier web application development
and more sophisticated form handling.
New Features such as : Video and Audio playback, Drag-
and –Drop, Canvas, Server-sent Events ,etc are included.
46
Features of HTML5
New Semantic Elements – Some new elements such as <header>, <footer> and
<section> are added to HTML5.
Forms 2.0 – The web forms are improved by introducing some new attributes for
the <input> tag.
Persistent Local Storage – This storage is achieved without resorting to the third-
party plugins.
Server–Sent Events – Events introduced by HTML5 which flow from the web
servers to the web browsers and they are known as Server-Sent Events(SSE).
Canvas – It is a drawing surface which supports two-dimensional drawing that can
be programmed with JavaScript.
Audio & Video - Audios and videos can be added to the web pages without
resorting to the third-party plugins.
Geolocation - Physical location of the visitors can be shared with the web
applications.
Drag and drop – This feature helps in dragging and dropping items from one
location to the other on the same web page.
47
HTML5-Rules
New features should be based on HTML, CSS, DOM, and
JavaScript
The need for external plug-ins (like Flash) needs to be
reduced
Error handling should be easier than in previous versions
Scripting has to be replaced by more markup
HTML5 should be device-independent
The development process should be visible to the public
48
New in HTML5
HTML5 introduces the following new input and form
control types : calendar, date, time, email, url, search
APIs: With a growing demand for interactive content on web
pages,HTML5 introduces several APIs (Application
Programming Interfaces) for standardizing the creation of
web applications.
Drag and drop functionality (including the new draggable attribute)
Playing video and audio files, with video and audio element
Two-dimensional drawing in conjunction with the new canvas element
Registering applications for certain protocols or media types
Cross-document messaging
New content-specific elements, like <article>, <footer>, <header>, <nav>,
<section>
49
New HTML5- Global attributes
In addition to id, class, style, title, dir, lang, accesskey, and
tabindex carried over from HTML 4.01, HTML5 adds the
following global attributes that are applicable to all
elements:
contenteditable="true|false“
contextmenu="id of menu element“
draggable="true|false“
spellcheck="true|false"
50
Exercises
1. Create an HTML document with the following
elements:
At least one image
At least three links
Different background color and text colors.
Two different sizes of text
Some centered text.
A title
51
Exercises (cont’d)
2. For this exercise, you will familiarize yourself with
HTML by hand-writing a web site. You will develop at
least two web pages.
The first will provide a Google-like interface where a user can
perform a search query.
The "Search" button will link to the second page that displays
the results of a query.
You will not actually be generating results. Instead, your
"Search" button can simply link to another page that shows the
results for a static query.
The goal is really just to design the interface.
52
Exercises (cont’d)
3. Create a menu list of links to the following search
engines:
Yahoo: http://www.yahoo.com
Google: http://www.google.com
Alta Vista: http://www.altavista.com
Ask: http://www.ask.com
53
Chapter 3
Client Side Programming using CSS
Cascading Style Sheets (CSS): style sheet language
used to describe the presentation of a html document.
Define colors, fonts, layout, and other aspects of
document
Why CSS?
• more flexibility
• control the specification of presentational
characteristics
• reduce complexity and repetition in the structural
content.
54
Introduction
Cascading Style Sheets (CSS)
Separation of document structure from presentation
Styles define how to display HTML elements
Relationship between the style formatting and the
structure/content is no longer 1:1
multiple style sheets can be applied to the same Web
page
Same style sheet can be applied to the multiple Web
page
Clearly separates content from its presentation
Saves a lot of work
55 Especially in website maintenance and upgrading
Introduction (cont’ d)
An extension (addition) to HTML which allows us to style
our web pages, it is the language used to add style to
HTML elements.
Provides more detailed attributes to elements than the ones
defined in standard HTML
Styles are defined once and used any number of times and
in several contexts for the web docs
Cascading Style Sheets are simple text files saved in a
“.css” extension which contain style Rules.
56
Styling View – Web docs
57
Cascading Style Sheets (CSS)
62
Inline Styles
Inline Styles: Inline styles are applied to a single
element within the start tag of the element.
For example, if you wanted to assign certain
properties to the text within a paragraph, you would
include style definitions like the following:
<p style=“color:red; font-family:arial;”>
paragraph text
</p>
We’ve already used this style of CSS in a couple of
our earlier examples.
Embedded /Global Style Sheets
65
Global Style Sheet - Example
68
External Style Sheets
70
Style Precedence – The Cascade
Browser defaults
External styles
Embedded styles
Inline styles
HTML5 attributes
CSS (cont’d)
CSS styles can be specified:
Inside a single HTML element (inline)
Inside the <head> element of an HTML document (internal)
In an external CSS file (external)
74
CSS (cont’d)
Types of selectors
HTML tag names
Class selectors
Id selectors
75
CSS (cont’d)
The class selector
define generic styles that can be applied to different HTML elements
applied to the class attribute of HTML elements
Format:
1. Styles for a particular element
tag_name.style_name { property: value }
Ex. p.color { color: green }
<p class=“color”>some text</p>
2. Styles for all elements
.style_name { property: value }
Ex. .color { color: blue }
<div class=“color”>some text</div>
<table class=“color”>…</table>
76
CSS (cont’d)
The Id selector
unlike the class selector, the Id selector always applies to only
one element
Format:
1. Styles for a particular element
tag_name#style_name { property: value }
Ex. p#color { color: green }
<p id=“color”>some text</p>
2. Styles for all elements
#style_name { property: value }
Ex. #color { color: blue }
<div id=“color”>some text</div>
77 <table id=“color”>…</table> possible ???
CSS (cont’d)
CSS comments
Format:
/* comment text */
inline
<tag_name style=“property:value; property: value;”> … </tag_name>
Ex. <table style=“background-color: yellow”>… </table>
78
CSS (cont’d)
internal
defined in the <head> element
<style type=“text/css”>
property:value; ...
</style>
external
defined in a separate CSS file
linked to an HTML document using the <link> tag :
<link rel=“stylesheet” type=“text/css” href=“url”>
changes to the styles in the external CSS file will be automatically
reflected in all the HTML document in which the style is attached
79
CSS (cont’d)
some common CSS properties
Background
background-color: color
background-image: url(url)
background-repeat: repeat_type {repeat, repeat-x, repeat-y, no-repeat}
background-attachment: attachment_type {scroll, fixed}
Text
color: color
direction: direction {ltr, rtl} borwser issue??
letter-spacing: value
text-align: alignment {left, right, center, justify}
text-decoration: decoration {none, underline, overline, line-through,
blink}
text-indent: value
80
CSS Rules – Examples
h1 {
CSS rule applying to color: black;
a single element.
font-size: 12pt;
font-family: arial;
}
h1, h2, p {
CSS rule applying to color: red;
a three elements. font-size: 12pt;
font-family: arial;
}
CSS Example
Borders
Margins
Padding
List properties
91
Example –inline style
<html>
<head>
<title> Inline Style</title>
</head>
<body>
<p> this text doesn’t have any style applied to it</p>
<p style= “font-size:20pt”> this text
<emp>Font-Size</emp> syle appied to it making 20pt
</p>
<p style= “font-size=:20pt;color:#0000ff”> this text has
the<emp> Font-Size</emp> and <emp>color<emp> style
applied to it as 20pt and blue.</p>
92
Chapter 4
Client side Programming Using JavaScript
A client-side scripting language that allows Web page authors to
develop interactive Web pages and sites
JavaScript is considered a scripting language because it is
interpreted by the browser at runtime (when the web page is
actually opened) rather than compiled and stored on your
computer.
It provides a computational capability in web documents.
It is used in creating, accessing, modifying a document.
Used in most Web browsers including Firefox and Internet
Explorer
93
Introduction to scripting & classification
1. Client-Side Scripting
Client-side scripting enables interaction within a webpage.
The code required to process user-input is downloaded and
compiled by the browser or plug-in.
It is a language that runs on a local browser (on the
client tier) instead of on a Web server (on the processing
tier)
An example of a client-side interaction is a rollover
(typically triggered when choosing a navigation option).
94
Introduction to scripting classification
2. Server-Side Scripting
Refers to a scripting language that is executed from a
Web server
Used to develop more interactive Web sites
Is easy to learn
Includes object-oriented programming capabilities
Supports many types of databases (MySQL, Oracle, Sybase, ODBC-
compliant
Exists and executes solely on a Web server, where it performs
various types of processing or accesses databases or resources
Web Site Dynamic Web Site, distributed interactivity
95
Client-Side Scripting
Client-side scripts are placed within an HTML document in the
user’s web browser rather than the web server to allow greater
interactivity in a document. For example – client-side scripting
could check the user’s form for errors before submitting it
Enables web pages to change content according to user input and
other variables, including the time of day. Can also be stored in a
separate file that is referenced to the documents that use it.
HTML is good for developing static pages(static web sites)
can specify text/image layout, presentation, links, …
Web page looks the same each time it is accessed
in order to develop interactive/reactive pages, must integrate
programming in some form or another
96
Introduction to JavaScript
JavaScript scripting language
Easy Program development
Easy Program control structure
Client-side scripting enhances functionality and appearance
Makes pages more dynamic and interactive
Pages can produce immediate response without contacting
a server
Customization is possible on the basis of users’ explicit
and implicit input
Browser has to have a built-in (JavaScript) interpreter
97
Introduction to JavaScript …
JavaScript is an interpreted programming or script language
from Netscape.
Created by Netscape
Originally called Mocha, LiveWire then LiveScript, now
JavaScript
JavaScript is used in Web site development to such things as:
automatically change a formatted date on a Web page
cause a linked-to-page to appear in a popup window
cause text or a graphic image to change during a mouse
rollover
98
What can JavaScript do?
Giving the user more control over the browser
Detecting the user's browser, OS, screen size, etc.
Performing simple computations on the client side
Validating the user's input
Handling Events, Errors and exceptions
Generating HTML pages on-the-fly without accessing the
Web server.
99
Client-side Script can’t ...
Set or retrieve browser preferences
launch an application on client computer
read or write files on client computer
Extract text content from HTML page
Do much of anything on server computer including
accessing a database
100
How Does It Work?
Embedded within HTML page
View source
Executes on client
Fast, no connection needed once loaded
Simple programming statements combined with HTML
tags
Interpreted (not compiled)
No special tools required
101
Features of JavaScript
Designed for programming user events JavaScript is a
lightweight, interpreted language
Embedded within HTML, Complementary to and integrated
with HTML.
Minimal Syntax- Easy to learn
Mainly used for client side scripting because it is supported by
all the browsers.
Open source-free
Platform Independence/ Architecture Neutral
102
JavaScript – lexical structure
JavaScript is object based, action-oriented, &object orientation .
JavaScript is case sensitive.
A semicolon ends a JavaScript statement
C-based language developed by Netscape
Comments
Supports single line comments using //
and multi line comments using /*…..*/
103
JavaScript – lexical structure …
The Web browser runs a JavaScript program when the Web
page is first loaded, or in response to an event.
JavaScript programs can either be placed directly into the
HTML file or they can be saved in external files.
placing a program in an external file allows you to hide
the program code from the user
source code placed directly in the HTML file can be
viewed by anyone
104
JavaScript – lexical structure …
A JavaScript program can be placed anywhere within the
HTML file.
Many programmers favor placing their programs between
<head> tags in order to separate the programming code
from the Web page content and layout.
Some programmers prefer placing programs within the body
of the Web page at the location where the program output is
generated and displayed.
105
Using the <script> Tag
To embed a client-side script in a Web page, use the
element:
<script type=“text/javascript” >
script commands and comments
</script>
To access an external script, use:
<script src=“url” type=“text/javascript”>
script commands and comments
</script>
<SCRIPT LANGUAGE=“JavaScript”>
-----
(JavaScript code goes here)
----
</SCRIPT>
106
JavaScript as a referenced file
3 Ways of Using JavaScript in HTML
Embedded
External file
Inline
Embedded
Embedding JavaScript code into an html page using <script> tag.
Embedded code is not accessible from other pages.
External file
Enables a JavaScript script stored in a separate file to be included as part
of the current page.
The important use of the referenced file is
Reusable function can be placed in the .js file.
Multiple pages can use the same .js file.
Maintains will be easier.
107
External and Inline JavaScript
Can be achieved by using the SRC attribute of the <script> tag.
External Javascript file should have an extension .js
Should not use <script> tag inside the .js file
For example:
<script language=“JavaScript” src=“external.js”>
</script> <!– should have the closing </script> tag -->
Inline JavaScript
Scripts are included inside the HTML tag.
<html>
<body onLoad="alert('document loaded')";>
<h1>Inline JavaScript</h1>
<input type="button" name="but1" value="click"
onClick="window.close()">
</body></html>
108
JavaScript-Example 1
<html> directs the document object to
<head> write the given string
<script language=“JavaScript”>
document.write (“<b> This is first </b>);
</script>
</head>
<body>
Now where does this print on the web page???? <br />
<script language=“JavaScript”>
document.write ( “This might be last?”)
</script>
</body>
</html>
109
JavaScript-Example 2
Now, let JavaScript generate HTML for us…
<html>
<head><title>JavaScript HelloWorld!</title></head>
<body>
<script laguage="JavaScript">
document.write("<h2>Javascript-Generated
output:</h2> <p>This paragraph generated by
JavaScript</p>
<p>It can even insert an image</p>
<img src='../assigns/RayWeb/images/cathedral.jpg' />")
</script>
</body>
</html>
110
JavaScript –Variables
Declared using the keyword var. Declaring variables is not mandatory.
Must start with a letter or an underscore and can have digits.
Does not have explicit data types.
The Data type is automatically decided by the usage.
Scope is by default global. If a variable is prefixed by the keyword “var”
within a function then it is a local variable.
The formal parameters are local to the function.
function demo()
{
var inum1 = 10; // Local to the function
inum2 = 20; // Global to the document.
}
demo(); // Invoking function
inum1 = inum1+1; //Error because inum1 is local variable
inum2 = inum2+1; // no Error
111
JavaScript – Implicit data types
JavaScript recognizes the following implicit data types
a. Number
b. String
c. Logical
d. Object
e. The special value null
a. Type conversion
JavaScript automatically converts between data types
Consider
112
JavaScript – Operators
Arithmetic Operators
+, ++, -, --, *, /, %
Relational Operators
==, !=, ===, !==, >, >=, < , <=
Logical Operators ( and , or , not)
&&, ||, !
Assignment Operators
=, +=, -=, *=, /=, %=
Strict equal (===)
Returns true if the operands are equal and of the same type.
Strict not equal (!==)
Returns true if the operands are not equal and/or not of the same
type.
113
Special operators
typeof operator
Unary operator
Indicates the data type of the operand.
Eg
x=123;
alert(typeof(x)); // Number
x="Hello"
alert(typeof(x)); // String
new
Used for instantiation of objects.
Eg: today = new Date( )
this
used to refer to the current object
114
JavaScript -Simple Interactions
alert
Displays an Alert dialog box with a message and an OK button.
Syntax: alert("message");
Example: alert(“You’re in a Special Area …”);
alert(“count=“+count); // count is a variable to be traced here
confirm
Displays a Confirm dialog box with the specified message and OK
and Cancel buttons.
Syntax: confirm("message");
Example: ans = confirm(“Are you sure you want to continue?”);
ans will be true if OK is clicked or false if Cancel is clicked
115
JavaScript -Simple Interactions …
eval
The eval function evaluates a string and returns a value.
Syntax: eval(stringExpression)
Example: eval(1+2*3) // gives 7 here
prompt
The prompt function prompts for a string value.
Syntax: prompt(“message”) or prompt(“message”, default value)
Example:
aString1 = prompt(“Enter Name”);
aString2 = prompt(“Enter Salary”, 0);
Note: The return value is a string. Need to convert if a numeric value is desired.
Use parseInt() or parseFloat().
Example: numSalary = parseInt(aString2);
numSalary = numSalary + 500;
116
JavaScript-Exercise 1
Create a web page that contains
A title of “My first JavaScript Page”
A Javascript to ask the user for their name
A personalized welcome message to the user.
117
JavaScript – Control structures
Control structure in JavaScript, as follows:
if
Is used to conditionally execute a single block of code
if .. else
a block of code is executed if the test condition evaluates to a boolean
true else another block of code is executed.
switch …. case
switch statement tests an expression against a number of case options
executes the statements associated with the first match.
118
JavaScript – Loop
while loop
The while statement is used to execute a block of code while a certain
condition is true
Syntax : while ( test condition)
{
zero or more statements
}
for loop
Iterate through a block of statements for some particular range of values
Syntax : for(initstmt; condstmt; updstmt ){
zero or more statements
}
do while loop
block of statements is executed first and then condition is checked
Syntax : do
{
zero or more statements
}while ( test condition)
119
JavaScript – Control structures
break
Terminates the current loop, switch, or label statement and transfers
program control to the statement following the terminated loop.
continue
In contrast to the break statement, continue does not terminate the
execution of the loop entirely.
In a for loop, it jumps to the update expression.
In a while loop, it jumps back to the condition.
for(i=0; i<5; i++)
{
inner : /*JS Comments : label */
for(j=0;j<5;j++)
{
if(i==j){ break inner;}
document.write(j+" ");
}
document.write("<br>");
}
120
JavaScript Functions
Key issues about using functions
Naming functions
Passing in parameters
Using local variables within functions
How to call (i.e., invoke) functions
How to handle a function’s return value
Where to put JS functions in your webpage
121
JavaScript Functions – Basic Principles
Reasons to use functions
Ease of communication
Problem simplification
Easier construction
Code readability
Reusability
Maintainability
122
JavaScript Functions -User defined
A function is a block of code that has a name.
Way to organize your code. User can write his own functions
JavaScript functions is to link actions on a web page with the JavaScript code.
JavaScript has some in-built functions.
To create a function you define its name, any values ("arguments"), and some
statements:
function myfunction(argument1,argument2,etc)
{
some statements;
}
123
More user defined functions
JavaScript functions can return any value and explicit return type is not
used in JavaScript.
124
More User defined Functions
/* Function to validate an email id
name : checkEmail()
parameter : String (email id)
returns : true(success), false ( fail)*/
function checkEmail(email){
/* checking for the length */
if(email.length<=0) {
return false;
}
/* checking the occurance of @ */
if(email.indexOf("@")==-1) {
return false;
}
return true;}
125
JavaScript Functions - Built-in
Built-In Functions
Prompt
Alert
Confirm
126
Other Top-Level functions
eval
Evaluates a string of JavaScript code without reference to a particular
object.
Syntax eval( string)
isNaN
Evaluates an argument to determine if it is “NaN” (not a number).
Syntax isNaN( testValue)
isFinite
evaluates an argument to determine whether it is a finite number
Syntax isFinite( number)
127
JavaScript Function-Example
<script langauge="JavaScript">
<!-- hide me
function announceTime( ) {
// show me -->
</script> </head> <body> ... </body> </html>
128
JavaScript Function in Action ...
FORMS
function IsFormComplete(FormName)
{ var x =0
var FormOk = true
130
Using Arrays, syntax
An array is an ordered collection of values referenced by a
single variable name.
The syntax for creating an array variable is:
var variable = new Array(size);
variable is the name of the array variable
size is the number of elements in the array (optional)
To populate the array with values, use:
variable[i]=value;
where i is the ith item of the array. The 1st item has an index
value of 0.
131
Array ways
In general, you can create array in three different ways in JavaScript. The syntax
is:
1. arrayName = new Array(arrayLength);
2. arrayName = new Array(element0, element1, ..., elementN);
3. arrayName = [element0, element1, ..., elementN];
Access an Array
document.write(planet); // Display all elements
document.write(planet[4]); // 4th element of array
for (var i=0; i < myArray1.length; i++) {
document.write(planet[i] + "<BR>");
}
Array Object Methods
array.concat(array2) toString()
array.sort([compareFunction]) reverse();
pop() filter()
push(value) join(separator)
reverse()
132
Arrays: Example
<body>
<script language="JavaScript">
function arrayFunction() {
var grade = new Array("70", "60", "80", "90", "20");
document.write("<br> Popped: " + grade.pop());
grade.reverse();
document.write("<br>Reversed: ");
for(var i=0;i<grade.length; i++)
document.write(" " + grade[i]);
document.write("<br>Converted to string: " + grade.toString());
</script>
</head>
<body onLoad="arrayFunction();">
</body>
133
Using Arrays …
Methods Description
push( element1, ..., Add / removes the last element to/from an array
elementN) and returns that element.
134
Objects
JavaScript is based on object-based paradigm.
Once instantiated, the properties and methods of the object can be used
accordingly.
135
Creating objects
Using keyword new
Any Object should be instantiated before being used.
Once instantiated, the properties and methods of the object can be used
accordingly.
Example
var newDateObj = new Date();
alert(“Today Date is :” +
newDateObj.getDate());
alert(“And the Month is :” +
newDateObj.getMonth());
136
Example- Window Object methods
(Dialog boxes )
Alert dialog box - alert( message)
Takes in a string argument and displays an alert box.
137
Window Objects
window - the current browser window
window.history - the Netscape history list
window.document - the html document currently in the
browser client area
window.location - the browser location field
window.toolbar - the browser toolbar
window.document.link - an array containing all of the links in
the document
window.document.anchor - an array of all the anchor points in
the document
138
Window Objects (more…)
Window.document.layer - a named document layer
window.document.applet - a named java applet area
window.document.image- a named image tag
window.document.area - a named area
window.document.form - a named form or the default form
ect, ect
139
Generally: -Object Hierarchy
window
password submit
140
JavaScript Event Handling
Events are occur usually as a result of some action by the user/system.
With an event handler you can do some action when an event occurs.
141
Events and Functions
Many event handlers are supported
onmouseover, onmouseout, onclick
…/swap image.html
142
JavaScript: Form Validation
Forms are widely used on the Internet. The form input is
often sent back to the server or mailed to a certain e-mail
account. But how can you be certain that a valid input was
filled by the user? With the help of JavaScript the form
input can easily be checked before sending it over the
Internet. It is sent only if the input is valid.
form validation may be:
Form data that typically are checked by a JavaScript could be:
has the user left required fields empty?
has the user entered a valid e-mail address?
has the user entered a valid date?
has the user entered text in a numeric field?
143
JavaScript Events and HTML Forms
<HTML>
<HEAD>
<SCRIPT LANGUAGE=JavaScript>
function changecolor()
{
document.bgColor="#ff0000";
}
</HEAD>
<BODY>
FORM >
<INPUT TYPE=“button” VALUE="Click Me"
onclick="changecolor()">
</FORM>
</BODY></HTML>
144
JavaScript Events and HTML Forms …
Form Object
Window.document.form
A form is a property of the document but is also an object
Form elements are properties of a form and are also objects
Access to form’s properties is done through the NAME
attribute of the FORM tag
Access to the properties of the form elements is done through
the NAME attributes of the particular form element
145
JavaScript Events and HTML Forms …
Methods
Behavior associated with an object
Essentially functions that perform an action
Some are built in and others user made
Built-In Methods of the window object
Confirm
Alert
Prompt
146
JavaScript Events and HTML Forms …
User Events
An event occurs when a user makes a change to a form element
Ex. Click a button, mouseover an image
Detection of an event done by event handlers
Event handler is an attribute of the HTML button
<form>
<input type=button value=“please click” onclick=“function name()”>
</form>
147
Example
148
Example: a script that creates and validates the above form:
alert("Email oK!");
<html> if(form.urmessage.value=="")
<head> alert("No message written");
<script language="JavaScript"> else
function check(form) alert("Message ok");
}
{ </script>
if (form.urname.value == "") </head
alert("Please enter a string as your name!") <body>
<h2> <u> Form validation </u> </h2>
else
<form name="first">
alert("Hi " + form.urname.value + "! Name ok!"); Enter your name: <input type="text"
if(form.age.value < 0 || form.age.value=="") name="urname"> <br>
Enter your age: <input type="text" name="age">
alert("Age should be number and greater than 0");
<br>
else
Enter your e-mail address: <input type="text"
alert("Age ok"); name="email"> <br>
if (form.email.value == "" || write message: <textarea name="urmessage"
form.email.value.indexOf('@', 0) == -1) cols=40 rows=10></textarea><br><br>
alert("No valid e-mail address!"); <input type="button" name="validate"
value="Check Input" onClick="check(this.form)">
else
</body>
</html>
149
JavaScript Events Example
<HTML> //--></SCRIPT>
<HEAD> </HEAD>
<SCRIPT LANGUAGE=JavaScript><!-- <BODY BGCOLOR="#FFFFCC">
<P><FORM name=addmult>
function plus(){
<P>Enter a number in each field:
var n1; var n2;
<INPUT TYPE=text NAME=num1 VALUE=""
n1=document.addmult.num1.value; SIZE=5>
n2=document.addmult.num2.value; <INPUT TYPE=text NAME=num2 VALUE=""
SIZE=5><BR>
n1=parseFloat(n1);
<INPUT TYPE=button VALUE="+"
n2=parseFloat(n2); onclick="plus()">
document.addmult.result.value=n1+n2; } <INPUT TYPE=button VALUE="*"
function times(){ onclick="times()"><BR>
<INPUT TYPE=reset VALUE="Reset Form"><BR>
var n1; var n2;
<TEXTAREA NAME=result ROWS=3 COLS=27
n1=document.addmult.num1.value; WRAP=virtual></TEXTAREA>
n2=document.addmult.num2.value; </FORM>
n1=parseFloat(n1); </BODY>
n2=parseFloat(n2); </HTML>
document.addmult.result.value=n1*n2; }
150
JavaScript-Exercise
In this exercise, you will:
-- use css & a table to create a menu bar
-- handle “onmouseover” events
-- display information in an alert
-- update the window.status
-- create & call 2 functions
-- work with several Math Methods
151
JavaScript-Exception handling
Exception handling in JavaScript is almost the same as in
Java throw expression creates and throws an exception
The expression is the value of the exception, and can be of any type
(often, it's a literal String)
• try {
statements to try
}
• catch (e) { // Notice: no type declaration for e
exception-handling statements
}
• finally { // optional, as usual
code that is always executed
}
With this form, there is only one catch clause
152
JS-Exception handling …
• try { statements to try
}
• catch (e if test1) {
exception-handling for the case that test1 is true
}
• catch (e if test2) {
exception-handling for when test1 is false and test2 is true
}
• catch (e) {
exception-handling for when both test1and test2 are false
} finally { // optional, as usual
code that is always executed
}
Typically, the test would be something like
e == "InvalidNameException“
153
JS DOM
The DOM (Document Object Model) gives generic access to most elements, their
styles and attributes in a Web document. Each HTML document loaded into a
browser window becomes a Document object handled by the browser. It is a
language to access, modify and manipulate web content objects. The DOM
structure is:
154
State maintenance in JavaScript: Cookie
A cookie is a small file that the server embeds on the
user's computer. Each time the same computer
requests for a page with a browser, it will send the
cookie too. With JS, you can both create and retrieve
cookie values.
Cookies are a mechanism for storing data in the remote browser
and thus tracking or identifying return users.
It is user controled and act as local storage.
155
JS Cookies
Web Browsers and Servers use HTTP protocol to
communicate and HTTP is a stateless protocol. But for a
commercial website, it is required to maintain session
information among different pages.
For example, one user registration ends after completing many
pages. But how to maintain users' session information across all
the web pages.
In many situations, using cookies is the most efficient method
of remembering and tracking preferences, purchases,
commissions, and other information required for better
visitor experience or site statistics.
156
How It Works?
Cookies are a plain text data record of 5 variable-length fields:
Expires: The date the cookie will expire. If this is blank, the
cookie will expire when the visitor quits the browser.
Domain: The domain name of your site.
Path: The path to the directory or web page that set the cookie.
This may be blank if you want to retrieve the cookie from any
directory or page.
Secure: If this field contains the word "secure", then the cookie
may only be retrieved with a secure server. If this field is blank,
no such restriction exists.
Name=Value: Cookies are set and retrieved in the form of key-
value pairs.
157
How It Works? …
Your server sends some data to the visitor's browser in the
form of a cookie. The browser may accept the cookie. If it
does, it is stored as a plain text record on the visitor's hard
drive. Now, when the visitor arrives at another page on
your site, the browser sends the same cookie to the server
for retrieval. Once retrieved, your server
knows/remembers what was stored earlier
158
How to Creating, & Storing Cookie
Storing Cookies:he simplest way to create a cookie is
to assign a string value to the document.cookie object,
which looks like this.
document.cookie =
"key1=value1;key2=value2;expires=date";
This sets a cookie named "uname" - that expires after ten hours.
<script>
setcookie("uname", $name, time()+36000);
</script>
<html> <body> …
159
Thank You