Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 160

Chapter 2,3,4

Client side Web programming


Using
HTML ,CSS & Javascript
Client-Side Web Development
 Web development is the process of implementing
(programming) web sites and applications that users can
access over the internet and web.
 However, the internet is a network involving many different
computers all communicating with one another. These computers
can be divided into two different groups: servers store (“host”)
content and provide (“serve”) it to other computers,
while clients request that content and then present it to the human
users.
 Client-Side Web Development involves implementing
programs (writing code) that are interpreted by the browser,
and are executed by the client. It is authoring the code that is
sent in the server’s response.
2
Client-Side Web Development …
 Client-side scripting is performed to generate a code that can
run on the client end (browser) without needing the server
side processing. 
 It is the web browser’s job to interpret and render the source code
files sent by a server as part of an HTTP response. As a client-side
web programmer, your task is to write this source code for the
browser to interpret. There are multiple different types of source
code files, including: HTML(.html), CSS(.css) and JS(.js).
 Using client side web development/front end development we
can design and develop a static web site. It works at the front
end and script are visible among the users, does not need
interaction with the server, can reduce the load to the server,
and less secure
3
Client-side scripting
 Client side options are: HTML, CSS, JavaScript, jQuery
& Node.js etc.
 HTML: It is the fundamental building blocks of web programming
which provides the frame to the website. It describes the
arrangement of the content.
 CSS: it provides the way to design the graphic elements which
help in making the appearance of the web application more
attractive.
 JavaScript: It is also a client-side scripting language which
essentially devised for the specific purpose, but currently there are
various JavaScript frameworks used as server-side scripting
technology.

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

 Can be created using


1. Text Editors
 Notepad, Notepad ++, WordPad
2. WYSIWYG Editors
 Micro Soft FrontPage
 Macromedia Dreamweaver
 Others

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}

 <a href=“url#anchor_name”link text</a> {on a different 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

 The data can be sent in two methods: GET & POST


 GET
 for small and non-secure data
 Is the default method
 Data is sent as part of the request URL
 Limitation in size of data

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

 a department field {select box with values:


1. Computer Science
2. Information Science
3. Computer Engineering
 a semester field {select box with values:
1. I
2. II
 an academic year field
{select box with values: 1998-2000, 2008 default}
 a button to submit the form
 a button to reset the form

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

 Refer to the following syntax:


<a href=”<URL>”>Text to Display</a>

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)

 In 1996 the W3C recommended the adoption of a standard set to


style sheets, Cascading Style Sheets level 1 (CSS1).
 The original purpose of CSS was to provide HTML authors with
more formatting support and give them a way to apply uniform
styles to multiple documents.
 Cascading Style Sheets level 2 (CSS2), introduced in 1998, included
additional features and functionality.
 Cascading Style Sheets level 3 (CSS3), was started in 1998 and like
HTML5 is still a standard in progress, but is supported (to some
extent) by most current web browsers.
 CSS4 began as a W3C working draft in September 2009 and is not
sufficiently developed yet to be supported by any major browser.
Why Use Cascading Style Sheets?

 The main reason for using CSS is:


 to separate a document’s content and structure from its presentation.
In so doing it provides the document author with much greater
control over the document’s format.
 to change your presentation layout or method without having to
modify the documents themselves, and allows you to apply one style
sheet to any number of documents.
 For example, an organization could produce a price list document and
then develop different style sheets depending on the type of user who is
viewing the content whether they are using a desktop browser or a
mobile device.
Advantages of CSS
 CSS saves time: will automatically apply the specified styles
whenever that element occurs.
Pages load faster: less code means faster download times.
 Easy maintenance: to change the style of an element, you
only have to make an edit in one place.
 Superior styles to HTML : CSS has a much wider array of
attributes than HTML.
 Better type and layout controls
 Reliable browser support
 More accessible sites
Defining Styles

 In order to use a style sheet with your HTML5 document, you


need to tell your document where to locate the style
definitions. There are three ways to define styles:
1. Inline Styles: Inline styles are applied to a single element
within the start tag of the element.
2. Global (Embedded or Internal) Style Sheets: Style
definitions in are stored in the HTML5 document global style
sheet itself within the <style> element in the <head> of
the document.
3. Linked (External) Style Sheets: Style definitions in linked
style sheets are stored in a file separate from the HTML5
document.
Style Sheet Syntax Explained
selector
property value rule

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

 Global Style Sheets: Style definitions in global style sheets


are stored in the HTML5 document itself within the
<style> element. They <style> element must be
contained within the <head> element.
 The syntax of a global style sheet is:
<style type=“text/css”>
<!-- style definitions go here
-->
Notice that the section where the global styles are defined is contained within an
HTML5 comment. This is to hide the actual contents of the style definition from older
</style> browsers that don’t support CSS. The comment tags are not necessary to make
CSS work, but if they are not provided in an XHTML document, older Web browsers
may actually display the style property definitions on the Web page!
Embedded Style Sheets
 this method can only specify style information for the current
document:
 1:1 relationship
 However, the same document may have other style definitions applied to it
 1:M relationship
 embedded style sheet rule will have higher precedence than
external style sheet rule, if there is a conflict between styles
 embedded style sheet rule will have lower precedence than an
inline style sheet rule

65
Global Style Sheet - Example

A global (internal) style sheet


External/Linked Style Sheets

 Linked Style Sheets: Style definitions in linked style sheets


are stored in a file separate from the HTML5 document.
Linked style sheets provide style definitions to many
documents – each document simply has to reference a single
style sheet.
 The syntax for a linked style sheet declaration in an HTML5
document is:
<link rel=“stylesheet” href=“mystyles.css” type=“text/css” />

 The <link> element is used to define the style sheet. The


<link> element is an empty element and must be contained
within the <head> element of an HTML5 document.
External Style Sheets
 External style sheets
 Applicable to more than document
 Documents can have more than one source for style
specification
 M:M relationship
 Can provide uniform look and feel to entire site
 Same CSS syntax rules for assigning and invoking style
properties apply

68
External Style Sheets

 The rel attribute specifies this <link> element to be a link


to a style sheet.
 The href attribute, like that for the <a> (anchor) element,
specifies the location of the style sheet file on the system.
Both relative and absolute URLs can be used as the value for
the href attribute.
 The type attribute declares this style sheet to be a plain-text
file containing CSS styles.
Linking External Style Sheets
 To make a style sheet persistent, set the rel attribute to
"stylesheet".

 To make a style sheet preferred, set the rel attribute to


"stylesheet" and name the style sheet with the additional
title attribute.

 To specify an alternate style sheet, set the rel attribute to


"alternate stylesheet" and name the style sheet with the
title attribute.

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)

 Rules of precedence application:


 Inline styles
 Internal styles
 External styles
 Browser default
 From highest to lowest
72
CSS Syntax for Assigning Style Properties
 The CSS syntax is made up of three parts: a selector, a property and a value:
 selector {property: value}
 A selector can be:
 the HTML element/tag you wish to define. In this example:
 body {color: black} , element body is the selector
 The class selector, which can be tied to a specific element, such as:
 p.right {text-align: right}
 The class selector applicable to any element, such as:
 .loud {font-family: fantasy; font-size:
xx-large}
 If a class selector is used, it has to be invoked in the body of the
HTML document:
 <p class="right"> or
 <table class=“loud”>
 Selectors can be grouped (separated by comma)
73
Ex. p, div, table { align: center }
CSS Syntax for Assigning Style Properties
 Group selectors are possible for a group of HTML elements. For example:
 h1,h2,h3,h4,h5,h6 {color: green} will make all header
elements text green
 When a class selector is defined for a particular element, it can
not be invoked on other elements. Using example from the
previous slide which of these uses of class styles in the
XHTML document is correct?
 <ul class = “loud”>
 <ul class = “right”>
 Pseudo-class selectors define the style for the parts of a
document based on some characteristics other than tag name,
attributes or content. They may be defined by a user action
such as:
 Mouseover (hover pseudoclass)
 Clicking (active pseudoclass)

74
CSS (cont’d)
 Types of selectors
 HTML tag names
 Class selectors
 Id selectors

 HTML tag names as selectors


 used to override the default attributes of HTML tags
Format: tag_name {property : value}
Ex. a { color: red;
text-decoration: overline
}

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 */

 Attaching a style definition


Can be done in three ways:

 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

 Before we go too much further in examining CSS,


let’s rework one of our earlier examples to include
CSS.
 The very first HTML document we created was a
course description document
 For this first example of CSS, we’ll use a linked
style sheet. Recall that this means the style
definitions are stored in a file separate from the
HTML document. So let’s create the CSS file and
name it “firstCSS.css”.
firstCSS.css
CSS Properties
There are many types of CSS properties:
1. Font properties define font styles such as font family or type, size,
weight, and variant.
2. Text properties define the layout of blocks of text, words, or characters,
including spacing, alignment, transformation (forced uppercase or
lowercase), and decoration (such as underline, overline, strikethrough,
and blinking).
3. Color and image properties define the color and background formatting
of text and images. These properties can also define the position of a
background image and whether the image is repeated (tiled).
4. Border properties define the style of borders for elements like tables and
images, as well as for the entire document. Border properties include
width, height, style, color, margins, and padding.
5. Display properties define the style for the structure of the document.
These properties can define the placement of elements within the
document, such as block or inline, and how whitespace is formatted
within the document.
Font Properties

Property Description Value Example(s)


Global font declaration. Can font-family, font-
define all font properties in one style, font-weight,
font font-size, font-style
property.

Font type to display text. arial, courier


font-family
Size of font in pixels or as a small, x-small,
font-size percentage. medium, large,
x-large
Style of font. italic, bold, oblique
font-style
normal, small-caps
font-variant Font rendering.
Darkness of font. Uses name or normal, light, bold,
font-weight number. bolder, 100, 200,
300, 400, etc.
Text Properties
Property Description Value Example(s)
Amount of space between words in an normal, number of pixels
word-spacing element.
letter-spacing Amount of space between letters. normal, number of pixels
text-align Horizontal alignment of text on page. right, left, center
baseline, sub, super,
top, text-top, middle,
vertical-align Vertical alignment of text on page. bottom, text-bottom,
percentage
How much first line is indented. 0, number of pixels (i.e. 10 px),
text-indent percentage (i.e. 10%)
Change case of text. uppercase, lowercase,
text-transform capitalize, none
Amount of space between lines of text. normal, number of pixels
line-height
Special controls of text appearance underline, overline,
text-decoration blink, line-through,
none
Color Properties
Property Description Value Example(s)
color Text color red, blue, color code

Global background declaration. Can background-color, background-


define all background properties in one image, background-position,
background property. background-repeat, background-
attachment

background- Color of element’s background color name, transparent,


color inherit

background- URL, name of local file.


Image to be used as a background.
image
background- Scrolling of background image with the scroll, fixed, inherit
attachment element.

Position of element’s background. top, center, bottom,


background- left, right, percentage,
position number of pixels
background- Repeat pattern for background image repeat, repeat-x,
repeat (tiling). repeat-y, no-repeat
Border Properties
Property Description Value Example(s)
Color of the border element. red, blue, color code
border-color
Width of the border. medium, thin, thick,
border-width
number of pixels.
border-style Style of the border. none, solid, double
0, number of pixels, percentage.
margin-top Width of margin at the top of element.

Width of margin at the bottom of 0, number of pixels, percentage.


margin-bottom element.
Width of margin at the left side of 0, number of pixels, percentage.
margin-left element.
Width of margin at the right side of 0, number of pixels, percentage.
margin-right element.
Amount of padding at top of element. 0, number of pixels, percentage.
padding-top
Border Properties (continued)

Property Description Value Example(s)


Amount of padding at bottom of 0, number of pixels, percentage.
padding-bottom element.
Amount of padding on left side of 0, number of pixels, percentage.
padding-left element.
Amount of padding on right side of 0, number of pixels, percentage.
padding-right element.

Whether an element permits other none, left, right


clear
elements on its sides.

float Floating element. none, left, right

Height of an element. auto, number of pixels,


height
percentage
Width of section auto, number of pixels,
width percentage
Display Properties

Property Description Value Example(s)


Controls display of an element. block, inline, list-
display item

white-space Whitespace formatting. normal, pre, nowrap

Controls visibility of element. inherit, visible,


visibility hidden
CSS (cont’d)
 text-transform: transform {none, capitalize, uppercase, lowercase}
 word-spacing: value
 Fonts
 font-style: style {normal, italic, oblique}
 font-weight: weight {normal, bold, bolder, lighter, 100, 200, …}
 font-size: size
 font-family: font_list (in order of precedence, separated by comma)

 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).

 Web site  Static Web site, limited interactivity

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

str = “100”, num1 = 10, num2 = 20


num3 = num1+ num2 30
10020
strsum = str + num2
20100
strsum = num2 + str

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.

 Create another page that combines image swap and


function example
 Have the function called from the button switch the images

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

 In JS, functions are the primary encapsulation mechanism


which is one of object oriented concepts.

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.

/* function to add two numbers


function names are following Camel Casing
No explicit return type declaration
*/
function addNumber(num1,num2)
{
return num1+num2;
}
/* Invoking the function */
total=addNumber(10,20);

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)

 parseInt and parseFloat


 Return a numeric value when given a string as an argument.
 Syntax parseInt( string) , Syntax
parseFloat( 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( ) {

//get the date, the hour, minutes, and seconds

var the_date = new Date();


var the_hour = the_date.getHours();
var the_minute = the_date.getMinutes();
var the_second = the_date.getSeconds();

//put together the string and alert with it

var the_time = the_hour + ":" + the_minute + ":" + the_second;

alert("The time is now: " + the_time); }

// show me -->
</script> </head> <body> ... </body> </html>

128
JavaScript Function in Action ...
FORMS
function IsFormComplete(FormName)
{ var x =0
var FormOk = true

while ((x < document.forms[FormName].elements.length) && (FormOk))


{ if (document.forms[FormName].elements[x].value == '')
{ alert('Please enter the
+ document.forms[FormName].elements[x].name
+' and try again.')
document.forms[FormName].elements[x].focus()
FormOk = false
}
x ++
}
return FormOk
} 129
Arrays
 Arrays are objects in JavaScript which is used to store a set of values in a
single variable name.
 You create an instance of the Array object with the "new" keyword.
 The length property specifies the number of elements in an array.
var myArray = new Array(n)
var family_names=new Array(3)
var family_names=new Array(“Mulat",“Shife",“Siyoum")
 Data can be of any type, and there can be mixed data types within the same
array if it makes sense for your data requirements
var ad= [10, “Ethiopia", “Hawassa", “Atote"]
var planet = new Array(9);
planet= new Array(“Mercury”,”Venus”,”Earth”,”Mars”,“Jupiter”,“Saturn”,”Uranus”, ”Neptune”,”Pluto”);
or
var planet= [“Mercury”, ”Venus”, ”Earth”, ”Mars”, “Jupiter”, “Saturn”, ”Uranus”, ”Neptune”, ”Pluto”];

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

concat( array1,arr2) joins two arrays and returns a new array.

join( separator) joins all elements of an array into a string.

pop() Removes the last element from an array and


returns that element.

push( element1, ..., Add / removes the last element to/from an array
elementN) and returns that element.

reverse() transposes the elements of an array: the first array


element becomes the last and the last becomes
the first.

134
Objects
 JavaScript is based on object-based paradigm.

 Object is a construct with properties and methods.

 Any object should be instantiated before being used.

 Once instantiated, the properties and methods of the object can be used
accordingly.

 HTML elements become objects in JavaScript and Attributes become


properties in JavaScript.

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());

 Where Date is an inbuilt object template.

136
Example- Window Object methods
(Dialog boxes )
 Alert dialog box - alert( message)
 Takes in a string argument and displays an alert box.

 Prompt dialog box – prompt(message[, inputDefault])


 Displays a message and a data entry field

 Confirm dialog box – confirm(message )


 Serves as a technique for confirming user actions

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

history document location link

link anchor layer form applet image area

text radio button fileUpload select

textarea checkbox reset option

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.

Event Occurs when Event Handler


Click User Clicks onClick
Blur Removes Input Focus onBlur
Change Changes value onChange
KeyDown Depresses a Key onKeyDown
KeyPress Holds down a Key onKeyPress
KeyUp Releases a Key onKeyUp
Load Loads the page onLoad
UnLoad Unloads the page onUnload
MouseDown Depresses a Mouse Button onMouseDown
MouseMove Moves the mouse onMouseMove
MouseOut Mouse out onMouseOut
MouseOver Mouse Over onMouseOver
MouseUp Releases a mouse Button onMouseUp
Submit Submit a form onSubmit

141
Events and Functions
 Many event handlers are supported
 onmouseover, onmouseout, onclick
 …/swap image.html

 Functions have Three parts


 The function keyword
 Parenthesized, comma-separated list of arguments
 Statements enclosed in curly brackets
 …/function ex.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";

Creating Cookie: The setcookie() function is used to


create cookies.
Note: The setcookie() function must appear BEFORE the
<html> tag.

setcookie(name, [value], [expire], [path], [domain], [secure]);

This sets a cookie named "uname" - that expires after ten hours.
<script>
setcookie("uname", $name, time()+36000);
</script>
<html> <body> …

159
Thank You

You might also like