0% found this document useful (0 votes)
94 views219 pages

HTML, Css & Js Guest

Uploaded by

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

HTML, Css & Js Guest

Uploaded by

Vinu B
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

CSS 3

Introduction to Hypertext
HTML: Hypertext Markup Language
 Hypertext
 links within and among Web documents
 connect one document to another
 Markup
• HTML is the set of "markup" symbols or codes inserted in a file intended
for display on a World Wide Web browser.
• The markup tells the Web browser how to display a Web page's text,
images, sound and video files for the user.
• The individual markup codes are referred to as elements (but many
people also refer to them as tags).
Web 2.0: Evolution Towards a Read/Write Platform

Web 1.0 Web 2.0


(1993-2003) (2003- beyond)

Pretty much HTML pages viewed through a browser Web pages, plus a lot of other “content” shared over the web,
with more interactivity; more like an application than a “page”

“Read” Mode “Write” & Contribute

“Page” Primary Unit of “Post / record”


content

“static” State “dynamic”

Web browser Viewed through… Browsers, RSS Readers,


anything

“Client Server” Architecture “Web Services”

Web Coders Content Created by… Everyone

Cuene.com/mima
“geeks” Domain of… “mass amatuerization”
This figure shows how topics can be related in a hypertext fashion,
as opposed to a linear fashion.
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
Elements or tags: surrounded with angle bracket, must be lowercase
<tagname> … </tagname>

Attributes are properties that extend or refine the tag’s functions,


tag has multiple attributes separated with space and value has max.
of 1024 characters.
<tagname attributename=“value”> … </tagname>
<img src="logo.jpg" alt=“Telerik Logo“/>

Tabs , multiple spaces will appear as a single space.
Example:
<p> Standalone tags
Hello,
How are you?” <img/> - to display an image
</p> <br/> - Line break
<hr/> - Creates a Horizontal Rule
The browser will ignore the blanks and new line:
Hello, How are you?

<!–- comments -->


First HTML Page
test.html
<!DOCTYPE html>
<html>
<head>
<title>My First HTML Page</title>
</head>
<body>
<p>This is some text...</p>
</body>
</html>

•An
7
HTML file must have an .htm or .html file
The <script> Tag – Example scripts-
<!DOCTYPE HTML> example.html
<html>
<head>
<title>JavaScript Example</title>
<script type="text/javascript">
function sayHello() {
document.write("<p>Hello
World!<\/p>");
}
</script>
</head>
<body>
<script type=
"text/javascript">
sayHello();
</script>
</body>
8 </html>
<head> Section: <style>
•The <style> element embeds formatting
information (CSS styles) into an HTML page
style-example.html
<html>
<head>
<style type="text/css">
p { font-size: 12pt; line-height: 12pt; }
p:first-letter { font-size: 200%; }
span { text-transform: uppercase; }
</style>
</head>
<body>
<p>Styles demo.<br />
<span>Test uppercase</span>.
</p>
</body>
9 </html>
Text Formatting
•Text formatting tags modify the text between the
opening tag and the closing tag
– Ex. <b>Hello</b> makes “Hello” bold
<b></b> bold
<i></i> italicized
<u></u> underlined
<sup></sup> Sample superscript
<sub></sub> Sample subscript
<strong></strong> strong
<em></em> emphasized
<pre></pre> Preformatted text
<blockquote></ Quoted text block
blockquote>
<del></del> Deleted text – strike through 10
Text Formatting – Example
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1>Notice</h1>
<p>This is a <em>sample</em> Web page.</p>
<p><pre>Next paragraph:
preformatted.</pre></p>
<h2>More Info</h2>
<p>Specifically, we’re using HTML5.<br />
Next line.</p>
</body>
</html>

11
Image tag with map
 <img src="planets.gif" width="145" height="126" alt="Planets"
usemap="#planetmap">

<map name="planetmap">
<area shape="rect" coords="0,0,82,126" href="sun.htm"
alt="Sun">
<area shape="circle" coords="90,58,3" href="mercur.htm"
alt="Mercury">
<area shape="circle" coords="124,58,8" href="venus.htm"
alt="Venus">
</map>
 Anchor tag

You can click on a link and jump to another


document.
<a href=“URL”> click me </a>

•Use the <a> element to define a link


•Use the href attribute to define the link address
•Use the target attribute to define where to open the linked
document
•Use the <img> element (inside <a>) to use an image as a
link
•Use the id attribute (id="value") to define bookmarks in a
page
•Use the href attribute (href="#value") to link to the
bookmark
Absolute URL and Relative URL

 UR
List tag : list the items in an order list or
un-order list

 <ul type=“disc | circle | square” >


 <li>Coffee</li>
 <li>Tea</li>
 <li>Coca Cola</li>
 </ul>

 <ol type=“a | A | i | I | 1” >


 <li>Coffee</li>
 <li>Tea</li>
 <li>Coca Cola</li>
 </ul>

 <dl>
<dt>Coffee</dt>
<dd>- black hot drink</dd>
<dt>Milk</dt>
<dd>- white cold drink</dd>
</dl>
Table tag

<table border="1" background="#00FF00 or green or rgb(0,255,0)”


cellspacing=“10px” cellpadding=“20px”>
<tr>
 <th>Column 1</th>
 <th>Column 2</th>
 <th>Column 3</th>
</tr>
<tr>
<td rowspan="2">Row 1 Cell 1</td>
<td bgcolor="red">Row 1 Cell 2</td>
<td>Row 1 Cell 3</td>
</tr>
<tr>
<td>Row 2 Cell 2</td>
<td>Row 2 Cell 3</td>
</tr>
<tr>
 Form tags: is used to allow a user to input
data on a web page
frameset Element

 Allow browser display more than one document


simultaneously

 Element: frameset
Attributes Description
cols Specifies the frameset’s column layout
rows Specifies the number of rows and the size of each row

 Sub-Element: frame
 Specifies the documents that will be loaded
 Attribute src: specifies URL of the page to display
18
Frame Tag

•Defines the content in each frame

• Placed between the <frameset> </frameset> tags

•The src attribute specifies the file that will appear in the
frame

<frameset rows="10%,*">
<frame src="first.html"/>
<frame src= “content.html" name= “content" frameborder="0"
scrolling="no"/>
</frameset>
Inline Frames
• The browser reads the <iframe> tag from the file, then makes a separate request

 to the server for the embedded file

• The frequently changed section can be an inline frame, which can be quickly modified

 when necessary without editing the entire page


 Simple HTML5 page with inline frame:
<h1>iFrame Example</h1>
<p>
<strong>This text is found in iframe.html</strong>
<p/>
<iframe src="embedded.html" scrolling= "yes">
Your browser does support frames.
</iframe>
<p>
<strong>This text is also found in iframe.html.
HTML 5
A semantic element clearly describes its
meaning to both the browser and the
developer.

Examples of non-semantic elements: <div>


and <span> - Tells nothing about its content.

Examples of semantic elements: <form>,


<table>, and <img> - Clearly defines its
content.
HTML 5

Header Figure

Navigation
Section
Article
Footer
Image, Video, Quote,
Article Table, etc…
Asid
Footer
e
Article
Footer

Legend
Footer
Form Enhancements
 Placeholder text
 Specific text input: email, URL, number,
search
 Slider
 Date picker
 User Agent validation
Se
ba
<input> types some examples
sti
an
Vie
rec

 <input type="datetime">
28.
12.
20
24
25

 <input type="number" min="18"


max="65" step="1">

 <input type="range" min="18" max="65"


step="10">
HTML Data Tag
 The HTML <data> tag is used to provide a
machine readable version of its own contents.
 It displays the data in a special format.

<ul>
<li><data value="101">Java Tutorial</data></li>
<li><data value="111">SQL tutorial</data></li>
<li><data value="121">HTML tutorial</data></li>
</ul>
HTML figure & figcaption tag

 HTML <figure> tag is used to mark up a photo in the

document on a web page.

 <figure> tag is used to handle the group of diagrams, photos,

code listing etc. with some embedded content.

 You can also add a caption for the photo with the help of

<figcaption> tag.

<figure>

<img src="htmlpages/images/

tajmahal.jpg" alt="Taj Mahal"/>


HTML figure & figcaption tag
HTML Audio Tag
 HTML audio tag is used to define sounds such as
music and other audio clips.
 Currently there are three supported file format for

HTML 5 audio tag.


 mp3
 Wav
 Ogg

<audio controls>
<source src="koyal.mp3" type="audio/mpeg">
Your browser does not support the html audio tag.
</audio>
HTML Video Tag
 HTML 5 supports <video> tag also.
 The HTML video tag is used for streaming video files
such as a movie clip, song clip on the web page.
 Currently, there are three video formats supported
for HTML video tag:
 mp4
 webM
 ogg

<video controls>
<source src="movie.mp4" type="video/mp4">
Your browser does not support the html video tag.
</video>
HTML Progress Tag
 HTML <progress> tag is used to display the
progress of a task.
 It provides an easy way for web developers to
create progress bar on the website.
 It is mostly used to show the progress of a file
uploading on the web page.
 Downloading progress:
<progress value="43" max="100"></
progress>
HTML Meter Tag
 HTML <meter> tag is used to measure data
within a given range.
 It defines a scalar measurement with range. It is

also known as a gause.


 It should be used to display disk usage, voting

population etc.
<p>Display a gauge:</p>
<meter value="30" min="1" max="100">30 out of 1
00</meter><br>
<meter value="0.8">80%</meter>
HTML Google Maps

<!DOCTYPE html>
<html>
<body>
<h1>My First Google Map</h1>

<div id="map" style="width:400px;height:4


00px">
</body>
<html>
HTML Google Maps
<script>
function myMap() {
var mapOptions = {
center: new google.maps.LatLng(51.5, -0.12),
zoom: 10, mapTypeId: google.maps.MapTypeId.HYBRID
}
var map = new google.maps.Map(document.getElementById("map"),
mapOptions);
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBu-
916DdpKAjTmJNIgngS6HL_kDIKU0aU&callback=myMap"></script>
</body>
</html>
HTML Google Maps
HTML5 SVG

 SVG stands for Scalable Vector Graphics


 SVG is used to define graphics for the Web
 SVG is a W3C recommendation
 The HTML <svg> element is a container for SVG
graphics.
 SVG has several methods for drawing paths, boxes,
circles, text, and graphic images.
HTML5 SVG

<svg width="100" height="100">


<circle cx="50" cy="50" r="40" stroke="green" stroke width="4"

fill="yellow" />

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


width:10;stroke:rgb(0,0,0)" />

<rect x="50" y="20" rx="20" ry="20" width="150" height="150"


style="fill:red;stroke:black;stroke-width:5;opacity:0.5" />

<polygon points="100,10 40,198 190,78 10,78 160,198"


style="fill:lime;stroke:purple;stroke-width:5;fill-rule:evenodd;" />

</svg>
<canvas> Element

 A canvas is a rectangular area on an HTML


page.
 By default, a canvas has no border and no
content.
 <canvas id="myCanvas" width="200" hei
ght="100“ style="border:1px solid
#000000;"></canvas>
Draw a line

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


solid #d3d3d3;"> our browser does not support the HTML5 canvas
tag.</canvas>

<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.moveTo(0,0);
ctx.lineTo(200,100);
ctx.linewidth=10;
ctx.strokeStyle = '#ff0000';
ctx.stroke();
Draw a Circle

<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.arc(95,50,40,0,2*Math.PI);
ctx.stroke();
</script>
Draw a text

var c =
document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.font = "30px Arial";
ctx.fillText("Hello World", 10, 50);
Draw a stroke text

var c =
document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.font = "30px Arial";
ctx.strokeText("Hello World", 10, 50);
Draw Image
<p>Image to use:</p>
<img id="scream" src="img_the_scream.jpg" alt="The Scream"
width="220" height="277">
<p>Canvas to fill:</p>
<canvas id="myCanvas" width="250" height="300"
style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
<p><button onclick="myCanvas()">Try it</button></p>
<script>
function myCanvas() {
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = document.getElementById("scream");
ctx.drawImage(img,10,10);
}
</script>
Draw Beizer Curve
<canvas id="myCanvas" width="578"
height="200"></canvas>
<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
context.beginPath();
context.moveTo(188, 130);
context.bezierCurveTo(140, 10, 388, 10, 388, 170);
context.lineWidth = 10;
// line color
context.strokeStyle = 'black';
context.stroke();
</script>
</body>
Why CSS?
Cascading Style Sheets (CSS) is a style sheet language used
for describing the look and formatting of a document
written in a mark up language. CSS is designed primarily to
enable the separation of document content from document
presentation, including elements such as the layout, colors,
and fonts. This separation can improve content
accessibility and provide more flexibility
HTML Without CSS
“HTML without CSS is like a
piece of candy without a
pretty wrapper.”

Without CSS, HTML elements


typically flow from top to
bottom of the page and
position themselves to the
left by default.
With CSS help, we can create
containers or DIVs to better
organize content and make a
Web page visually appealing.

12/28/2024
HTML & CSS
• HTML and CSS work together to produce beautiful and functional Web sites

• HTML = structure

• CSS = style

12/28/2024
How to insert CSS
Three Ways
- External Style Sheet
- Internal Style Sheet
- Inline Style Sheet
External Style Sheet
<head>
<link rel="stylesheet" type="text/css"
href="mystyle.css">
</head>
Internal Style Sheet
<Style>
body {
background-color: lightblue;
}
h1 {
color: navy;
margin-left: 20px;
}
</style>
Inline Style Sheet
<h1 style="color:blue;margin-
left:30px;">This is a heading.</h1>
CSS Rule Structure
A CSS RULE is made up of a selector
and a declaration. A declaration consists
of property and value.

selector {property: value;}

declaration

12/28/2024
CSS Syntax
 Parts of a style rule (or statement)
CSS Syntax:
Selector Strings

 Single element type:

 Multiple element types:

 All element types:

 Specific elements by id:


CSS Syntax:
Selector Strings
CSS Syntax:
Selector Strings

 Elements belonging to a style class:


class selector: begins with a period .
 Referencing a style class in HTML:

 Elements of a certain type and class:


CSS Syntax:
Selector Strings

 Elements belonging to a style class:


 Referencing a style class in HTML

 Elements of a certain type and class:

this span belongs to three style classes

Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C.


Jackson’s slides
CSS Syntax:
Selector Strings
 Elements belonging to a style class:

 Referencing a style class in HTML:

 Elements of a certain type and class:

this rule applies only to span’s belonging to class special


CSS Syntax:
Selector Strings

 Source anchor elements:

pseudo-classes
 Element types that are descendents:
CSS Syntax:
Selector Strings

 Source anchor elements:

 Element types that are descendants:

rule applies to li element that is


part of the content of an ol element
that is part of the content of a ul element
CSS Syntax
 Style rules covered thus far follow
ruleset syntax
 At-rule is a second type of rule

URL relative to style sheet URL

 Reads style rules from specified URL


 Must appear at beginning of style sheet
Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C.
Jackson’s slides
CSS Rule Cascade

 What if more than one style declaration


applies to a property of an element?

 The CSS rule cascade determines which


style rule’s declaration applies
CSS Rule Cascade
To find the value for an element/property
combination, user agents must apply the
following sorting order:
1- Find all declarations that apply to the
element and property in question, for
the target media type. Declarations
apply if the associated selector matches
the element in question.
CSS Rule Cascade
2- The primary sort of the
declarations is by weight and
origin: for normal declarations, Five origin/weight levels:
author style sheets override user1. user/important
style sheets which override the 2. author/important
default style sheet. For "! 3. author/normal
important" declarations, user 4. user/normal
5. user agent/normal
style sheets override author style
sheets which override the default
style sheet. "!important"
declaration override normal
declarations. An imported style
sheet has the same origin as the
style sheet that imported it.
CSS Rule Cascade
3- The secondary sort is by specificity of selector:
more specific selectors will override more general
ones. Pseudo-elements and pseudo-classes are
counted as normal elements and classes,
Specificity:
respectively. 1. style attribute
2. rule with selector:
1. ID
2. class/pseudo-class
3. descendant/element type
4. universal
3. HTML attribute
CSS Rule Cascade
4- Finally, sort by order specified: if two rules have
the same weight, origin and specificity, the latter
specified wins. Rules in imported style sheets are
considered to be before any rules in the style
sheet itself.

Conceptually, create one


long style sheet. Later
style rules have higher
priority than earlier rules.
CSS Inheritance
 What if no style declaration applies to a
property of an element?
 Generally, the property value is inherited
from the nearest ancestor element that
has a value for the property
 If no ancestor has a value (or the
property does not inherit) then CSS
defines an initial value that is used
CSS Inheritance
CSS Inheritance
 Property values:
 Specified: value contained in declaration
 Absolute: value can be determined without
reference to context (e.g., 2cm)
 Relative: value depends on context (e.g.,
larger)
 Computed: absolute representation of
relative value (e.g., larger might be 1.2 x
parent font size)
 Actual: value actually used by browser
(e.g., computed value might be rounded)
CSS Inheritance
 Most properties inherit computed value
 Exception discussed later: line-height
 A little thought can usually tell you
whether a property inherits or not
 Example: height does not inherit
CSS Font Properties

 Other ways to specify value for


font-size:
 Percentage (of parent font-size)

 Absolute size keyword: xx-small, x-small,


small, medium (initial value), large,
x-large, xx-large
 User agent specific; should differ by ~ 20%
 Relative size keyword: smaller, larger
 Relative to parent element’s font
CSS Font Properties
CSS Font Properties
 Text is rendered using line boxes

 Height of line box given by line-height


 Initial value: normal (i.e., cell height;
relationship with em height is font-specific)
 Other values (following are equivalent):
CSS Font Properties
 font shortcut property:
CSS Font Properties
 font shortcut property:

Initial values used if no value specified in font


property list (that is, potentially reset)
CSS Font Properties
 font shortcut property:

specifying line-height (here, twice cell height)

any order size and family required,


Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C.
Jackson’s slidesorder-dependent
CSS Text Formatting
CSS Text Color
 Font color specified by color property
 Two primary ways of specifying colors:
 Color name: black, gray, silver, white, red,
lime, blue, yellow, aqua, fuchsia, maroon,
green, navy, olive, teal, purple, full list at
http://www.w3.org/TR/SVG11/types.html#C
olorKeywords
 red/green/blue (RGB) values
CSS Text Color
CSS Text Color

Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C.


Jackson’s slides
CSS Box Model
 Every rendered element occupies a box:
Content
Text & web page
elements in the (or outer edge
container
Padding
Area between the
content and the
border
Border
Between the padding
and the margin
Margin
Determines the
empty space
between the element
and adjacent (or inner edge)
elements
CSS Box Model
CSS Box Model
CSS Box Model
CSS Box Model
CSS Box Model
CSS Box Model
CSS Box Model
CSS Box Model
Backgrounds
 background-color
 Specifies background color for content,
padding, and border areas
 Margin area is always transparent
 Not inherited; initial value transparent
 background-image
 Specifies (using url() function) image that
will be tiled over an element

Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C.


Jackson’s slides
Backgrounds

<body style="background-image:url('CucumberFlowerPot.png')">

Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C.


Jackson’s slides
Background Shorthand Property

 background: shorthand rule for setting


background properties at the same time:
background: #FFF0C0 url("back.gif") no-
repeat fixed top;
is equal to writing:
background-color: #FFF0C0;
background-image: url("back.gif");
background-repeat: no-repeat;
background-attachment: fixed;
background-position: top;
 Some browsers will not apply BOTH color and
image for background if using shorthand rule
Normal Flow Layout
 Browser display of elements in the order they
are coded in the Web page document
 In normal flow processing, each displayed
element has a corresponding box
 html element box is called initial containing
block and corresponds to entire document
 Boxes of child elements are contained in boxes
of parent
 inline elements are laid out one on top of the
other
 Sibling block elements are one after the other
Normal Flow Layout
(body)

(html)
Normal Flow Layout- Nested
Box

Block
elements
only
Normal Flow Layout

html
body
div d1
div d2
div d3

div d4

Top edges of
block boxes are
in document order

Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C.


Jackson’s slides
Normal Flow Layout
 What is a “block element”?
 Element with value block specified for its
display property
 User agent style sheet (not CSS) specifies
default values; typical block elements
include html, body, p, pre, div, form, ol,
ul, dl, hr, h1 through h6
 Most other elements except li and table-
related have inline specified for display
Display Property

Making a <span> behave like a <div>

Making a <div> behave like a <span>

Hiding any images of the class ‘hidden’


Margin Collapse
 When blocks stack, adjacent margins are
collapsed to the size of the larger margin
Width property
 Initial value of width property is auto,
which for block boxes means to make the
content area as wide as possible within
margin/padding constraints:

Width of block boxes


increases as browser
client area is widened

Guy-Vincent Jourdan :: CSI 3140 :: based on Jeffrey C.


Jackson’s slides
Block box width- change
 Can also specify CSS length or
percentage (of parent’s content width)
for width property

By default, width of right margin is adjusted


to accommodate a change to width
Block box - centered
 Can also specify CSS length or
percentage (of parent’s content width)
for width property

Centering can be achieved by setting


both margins to auto
Inline Box
 Boxes corresponding to character cells
and inline elements are laid out side by
side in line boxes that are stacked one
on top of the other

Heights based
on
content

Character cells aligned by baseline


Inline box – height is not
changed

Padding/borders/margins affect width


but not height of inline boxes
CSS Positioning: Relative Positioning

• A relatively positioned element will stay exactly where it is, in


relation to the normal flow.
• You can then offset its position “relative” to its starting point
in the normal flow:

Box 1 Box 2 Box 3

Containing box
CSS Positioning: Relative Positioning
• In this example, box 2 is offset 20px, top and left. The result is
the box is offset 20px from its original position in the normal
flow. Box 2 may overlap other boxes in the flow, but other
boxes still recognise its original position in the flow.

top: 20px

#myBox {
Left: 20px
position: relative;
Box 1 Box 3
left: 20px; Position: relative

top: 20px;
Box 2
}
Containing box
CSS Positioning: Absolute Positioning
• An absolutely positioned box is taken out of the normal flow,
and positioned in relation to its nearest positioned ancestor
(i.e. its containing box).
• If there is no ancestor box, it will be positioned in relation to
the initial containing block, usually the browser window.

top: 20px

Left: 20px

#myBox { Box 1 Box 3


Position: absolute
position: absolute;
left: 20px;
top: 20px; Box 2
}

Containing box (relatively positioned ancestor)


Float
 Allows block level elements to stack
horizontally on the page
 Elements stack inside a parent container
 Can float: left or float: right
 Clear: right, clear: left or clear: both
stops elements from stacking
Float
Beyond Normal flow box:

• Static Positioning is default by the normal flow


• Relative Positioning is “relative” to the element’s initial
position in the normal flow.
• Absolute Positioning is “relative” to the nearest
positioned ancestor, or (if one doesn’t exist) the initial
container block (usually the browser window)
• Fixed Positioning is fixed in one position “relative” to the
browser window only — does not scroll with content (Not
supported in IE5, IE6)
• Floats (also a form of positioning) takes boxes out of the
normal flow and “floats” them left or right edges of the
containing block float:left|right
Position:static |relative | absolute | fixed
clear:left | right | both
Top|bottom|left|right: length in px
Other useful style
properties
 Lists:
 list-style-{type|position|image}
• Tables: cursor:
 border-style (default,Text,pointer &
progress)
 border-collapse (move, resize)
 Border-spacing
 empty-cell
 caption-side
 border-color
Positioning Elements: Absolute
Positioning, z-index

 CSS introduced the position property and a capability


called absolute positioning, which gives you greater
control over how document elements are displayed.
 Elements are positioned on the page in the order in
which they appear in the HTML5 document.
 Specifying an element’s position as absolute removes
the element from the normal flow of elements on the
page, instead positioning it according to the distance
from the top, left, right or bottom margins of its
containing block-level element.
 The z-index property allows you to layer overlapping
elements.
 Elements that have higher z-index values are displayed
in front of elements with lower z-index values.
Absolute Positioning
Positioning Elements: Relative
Positioning, span

 Elements are positioned relative to other


elements.
 Setting the position property to relative,
lays out the element on the page and
offsets it by the specified top, bottom, left
or right value.
 Unlike absolute positioning, relative
Positioning Elements: Relative
Positioning, span
Inline and Block-Level
Elements
 Element span is a grouping element—by default, it does not
apply any formatting to its contents.
 Its primary purpose is to apply CSS rules or id attributes to a
section of text.
 Element span is an inline-level element—it does not change
the flow of elements in the document.
 Examples of inline elements include span, img, a, em and
strong.
 The div element is also a grouping element, but it’s a block-
level element.
Box Model and Text Flow

 All block-level HTML5 elements have a virtual box drawn


around them, based on what is known as the box model.
 When the browser renders an element using the box model, the
content is surrounded by padding, a border and a margin.
 CSS controls the border using three properties: border-width,
border-color and border-style.
 Content - The content of the box, where text and images
appear
 Padding - Clears an area around the content. The padding is
transparent
 Border - A border that goes around the padding and content
 Margin - Clears an area outside the border. The margin is
CSS Box Model
CSS Borders

 The CSS border properties allow you to specify the style, width,
and color of an element's border.

p{
border-left: 6px solid red;

border-bottom: 6px solid red;


background-color: lightgrey;

border-radius: 12px;

border-style: dotted solid;

border-width: 6px;

border-color: red;
CSS BORDERS

p
{
border-top-style: dotted;
border-right-style: solid;
border-bottom-style: dotted;
border-left-style: solid;
}
border-style property
 border-style: dotted solid double dashed;
 top border is dotted
 right border is solid
 bottom border is double
 left border is dashed
 border-style: dotted solid double;
 top border is dotted
 right and left borders are solid
 bottom border is double
 border-style: dotted solid;
 top and bottom borders are dotted
 right and left borders are solid
 border-style: dotted;
 all four borders are dotted
Floating Elements

 Floating allows you to move an element to


one side of the screen; other content in the
document then flows around the floated
element.
Floating Elements

 Floating allows you to move an element to


one side of the screen; other content in the
document then flows around the floated
element.
Floating Elements
CSS - Margins

 The margin property defines the space around an HTML


element.
 It is possible to use negative values to overlap content.
 The values of the margin property are not inherited by the
child elements.
 margin
 margin-bottom
 margin-top
 margin-left
 margin-right
CSS - Margins

p
{
margin-top: 100px;
margin-bottom: 100px;
margin-right: 150px;
margin-left: 80px;
}
CSS Padding

 The CSS padding properties are used to generate


space around an element's content, inside of any
defined borders.
 CSS has properties for specifying the padding for
each side of an element:
 padding-top
 padding-right
 padding-bottom
 padding-left
CSS Padding
<head>
<style>
div {
border: 1px solid black;
background-color: lightblue;
padding-top: 50px;
padding-right: 30px;
padding-bottom: 50px;
padding-left: 80px;
}
</style>
</head>
<body>
<div>This div element has a top padding of 50px, a right padding of 30px, a
bottom padding of 50px, and a left padding of 80px.</div>
</body>
Media Types and Media
Queries
 CSS media types allow you to decide what a page

should look like, depending on the kind of media being

used to display the page.

 The most common media type for a web page is the

screen media type, which is a standard computer

screen.

 Other media types in CSS include handheld, braille,

speech and print.


Media Types and Media
Queries
 Braille is for machines that can read or print web pages in

braille.

 Speech styles allow you to give a speech-synthesizing web

browser more information about the content of a page.

 The print media type affects a web page’s appearance when

it’s printed.

 Media types allow you to decide how a page should be

presented on any one of these media without affecting the

others.
Media Queries
 allow you to format your content to specific output
devices.
 Media queries include a media type and expressions
that check the media features of the output device.
 width—the width of the part of the screen on which the
document is rendered
 height—the height of the part of the screen on which the
document is rendered,
 device-width—the width of the screen of the output device
 device-height—the height of the screen of the output device
 orientation—if the height is greater than the width, orientation
is portrait, and if the width is greater than the height, orientation
is landscape
 aspect-ratio—the ratio of width to height
 device-aspect-ratio—the ratio of device-width to device-height
Drop-Down Menus

 Drop-down menus are a good way to provide navigation links without

using a lot of screen space.

 :hover pseudo-class used to change a link’s style when the mouse

hovers over it.

 It cause a menu to appear when the mouse hovers over a menu button.

 Another important property is display, which allows you to decide

whether an element is rendered on the page or not.

 Possible values include block, inline and none.

 The block and inline values display the element as a block element or

an inline element, while none stops the element from being rendered.
Drop-Down Menus
Box Shadows

 Horizontal offset of the shadow—the number of pixels that the box-

shadow will appear to the left or the right of the box.

 Vertical offset of the shadow—the number of pixels the box-shadow

will be shifted up or down from the box.

 Blur radius—A blur-radius of 0px would result in a shadow with a sharp

edge (no blur). The greater the value, the more the edges of the

shadow are blurred.

 Color—the box-shadow’s color (in this case, dimgrey).

 A negative horizontal offset value moves the box shadow to the left.

 A negative vertical offset value moves the shadow up.


Box Shadows

 box-shadow: 25px 25px 50px dimgrey;


 box-shadow: -25px -25px 50px
dimgrey;
Linear Gradients
 Linear gradients are a type of image that
gradually transitions from one color to the next
horizontally, vertically or diagonally.
 You can transition between as many colors as you
like and specify the points at which to change
colors, called color-stops, represented in pixels or
percentages along the gradient line—the angle at
which the gradient extends.
 You can use gradients in any property that
accepts an image.
 Create three linear gradients—vertical, horizontal
and diagonal—in separate rectangles.
Linear Gradients
Radial Gradient
 A radial gradient is defined by its center.
 To create a radial gradient you must also define at
least two color stops.
 Syntax
background: radial-gradient(shape size at position,
start-color, ..., last-color);
 By default, shape is ellipse, size is farthest-corner,
and position is center.
 background: radial-gradient(red, yellow, green);
Image Borders
 The CSS3 border-image property uses images to place a
border around any block-level element.
 border-image-source—the URL of the image to use in the
border
<style>
#borderimg {
border: 10px solid transparent;
padding: 15px;
border-image: url(border.png) 30 round;
}
</style>
<body>
<p id="borderimg">border-image: url(border.png) 30 round;</p>
CSS Transitions

 CSS transitions allows you to change property values


smoothly (from one value to another), over a given
duration.
 To create a transition effect, you must specify two
things:
 the CSS property you want to add an effect to
 the duration of the effect

 If the duration part is not specified, the transition will


have no effect, because the default value is 0.
div {
width: 100px;
height: 100px;
background: red;
-webkit-transition: width 2s; /* Safari */
transition: width 2s;
transition-timing-function: linear;
transition-delay: 1s;
}
Transition + Transformation

div {
transition: width 2s, height
2s,transform 2s;
transform: rotate(180deg);
}
CSS Animations

 An animation lets an element gradually change


from one style to another.
 You can change as many CSS properties you
want, as many times you want.
 To use CSS animation, you must first specify
some keyframes for the animation.
 Keyframes hold what styles the element will
have at certain times.
The @keyframes Rule

 When you specify CSS styles inside


the @keyframes rule, the animation will
gradually change from the current style to
the new style at certain times.
 To get an animation to work, you must bind
the animation to an element.
CSS Animations
<style>
div {
width: 100px;
height: 100px;
background-color: red;
-webkit-animation-name: example; /* Safari 4.0 - 8.0 */
-webkit-animation-duration: 4s; /* Safari 4.0 - 8.0 */
animation-name: example;
animation-duration: 4s;
}
@keyframes example {
from {background-color: red;}
to {background-color: yellow;}
}
</style>
CSS Animations

<body>
<p><b>Note:</b> This example does not work in
Internet
Explorer 9 and earlier versions.</p>
<div></div>
<p><b>Note:</b> When an animation is
finished, it changes \
back to its original style.</p>
</body>
CSS Multiple Columns

 column-count
 column-gap
 column-rule-style
 column-rule-width
 column-rule-color
 column-rule
 column-span
 column-width
CSS Multiple Columns
<head>
<style>
.newspaper {
-webkit-column-count: 3; /* Chrome, Safari, Opera */
-moz-column-count: 3; /* Firefox */
column-count: 3;
column-width: 100px;
}
</style>
</head>
<body>
<p><b>Note:</b> Internet Explorer 9, and earlier versions, does not support the column-width
property.</p>
<div class="newspaper">
Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut
laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation
ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in
hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros
et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te
feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id
quod mazim placerat facer possim assum.
</div>
</body>
CSS Multiple Columns
JAVASCRIPT
THE BASICS
Introduction
 JavaScript is a scripting language most
often used for client-side web
development.

 JavaScript is an implementation of the


ECMAScript standard.
 The ECMAScript only defines the syntax/characteristics of
the language and a basic set of commonly used objects
such as Number, Date, Regular Expression, etc.

 The JavaScript supported in the browsers


typically support additional objects.
JavaScript / JScript

 Different brands or/and different versions


of browsers may support different
implementation of JavaScript.
 They are not fully compatible

 JScript is the Microsoft version of


JavaScript.
What can we do with
JavaScript?
 To create interactive user interface in a web
page (e.g., menu, pop-up alert, windows,
etc.)
 Manipulating web content dynamically
 Change the content and style of an element
 Replace images on a page without page reload
 Hide/Show contents

 Generate HTML contents on the fly


 Form validation
 AJAX (e.g. Google complete)
 etc.
A Simple Script
<html>
<head><title>First JavaScript Page</title></head>
<body>
<h1>First JavaScript Page</h1>
<script type="text/javascript">
document.write("<hr>");
document.write("Hello World Wide Web");
document.write("<hr>");
</script>
</body>
</html>
Embedding JavaScript
<html>
<head><title>First JavaScript Program</title></head>
<body>
<script type="text/javascript"
src="your_source_file.js"></script>
</body> Inside your_source_file.js
</html> document.write("<hr>");
document.write("Hello World Wide Web");
document.write("<hr>");
 Use the src attribute to include JavaScript
codes from an external file.
 The included code is inserted in place.
Embedding JavaScript

 The scripts inside an HTML document is


interpreted in the order they appear in
the document.
 Scripts in a function is interpreted when the
function is called.

 So where you place the <script> tag


matters.
Hiding JavaScript from Incompatible
Browsers
<script type="text/javascript">
<!–
document.writeln("Hello, WWW");
// -->
</script>
<noscript>
Your browser does not support JavaScript.
</noscript>
alert(), confirm(), and prompt()
<script type="text/javascript">
alert("This is an Alert method");
confirm("Are you OK?");
prompt("What is your name?");
prompt("How old are you?","20");
</script>
alert() and confirm()
alert("Text to be displayed");
 Display a message in a dialog box.

 The dialog box will block the browser.

var answer = confirm("Are you sure?");


 Display a message in a dialog box with two buttons:
"OK" or "Cancel".
 confirm() returns true if the user click "OK".
Otherwise it returns false.
prompt()
prompt("What is your student id number?");
prompt("What is your name?”, "No name");
 Display a message and allow the user to enter a

value
 The second argument is the "default value" to be

displayed in the input textfield.


 Without the default value, "undefined" is shown in

the input textfield.

 If the user click the "OK" button, prompt() returns


the value in the input textfield as a string.
 If the user click the "Cancel" button, prompt()
returns null.
Identifier

 Same as Java/C++ except that it allows


an additional character – '$'.

 Contains only 'A' – 'Z', 'a' – 'z', '0' – '9', '_',


'$'
 First character cannot be a digit
 Case-sensitive
 Cannot be reserved words or keywords
Variable and Variable Declaration

<head><script type="text/javascript">
// We are in the default scope – the "window" object.
x = 3; // same as "window.x = 3"
var y = 4; // same as "y = 4" or "window.y = 4"
{ // Introduce a block to creat a local scope
x = 0; // Same as "window.x = 0"
var y = 1; // This is a local variable y
}
alert("x=" + x + ", y=" + y); // Print x=0, y=4
</script></head>

 Local variable is declared using the keyword 'var'.


 Dynamic binding – a variable can hold any type of value
 If a variable is used without being declared, the variable is
created automatically.
 If you misspell a variable name, program will still run (but works
Data Types
 Primitive data types
 Number: integer & floating-point numbers
 Boolean: true or false
 String: a sequence of alphanumeric characters

 Composite data types (or Complex data types)


 Object: a named collection of data
 Array: a sequence of values (an array is actually a
predefined object)

 Special data types


 Null: the only value is "null" – to represent nothing.
 Undefined: the only value is "undefined" – to represent the
value of an unintialized variable
Strings

 A string variable can store a sequence of


alphanumeric characters, spaces and special
characters.

 Each character is represented using 16 bit


 You can store Chinese characters in a string.

 A string can be enclosed by a pair of single quotes


(') or double quote (").

 Use escaped character sequence to represent


typeof operator
var x = "hello", y;
alert("Variable x value is " + typeof (x) );
alert("Variable y value is " + typeof (y) );

 An unary operator that tells the type of its


operand.
 Returns a string which can be "number",
"string", "boolean", "object", "function",
"undefined", and "null"

 An array is internally represented as an


object.
Object
 An object is a collection of properties.

 Properties can be variables (Fields) or


Functions (Methods)

 There is no "Class" in JavaScript.


Array
 An array is represented by the Array object.
To create an array of N elements, you can
write
var myArray = new Array(N);

 Index of array runs from 0 to N-1.


 Can store values of different types
 Property "length" tells the # of elements in
the array.
 Consists of various methods to manipulate
its elements. e.g., reverse(), push(),
Array Examples
var Car = new Array(3);
Car[0] = "Ford";
Car[1] = "Toyota";
Car[2] = "Honda";

// Create an array of three elements with initial


// values
var Car2 = new Array("Ford", "Toyota", "Honda");

// Create an array of three elements with initial


// values
var Car3 = ["Ford", "Toyota", "Honda"];
// An array of 3 elements, each element is undefined
var tmp1 = new Array(3);

// An array of 3 elements with initial values


var tmp2 = new Array(10, 100, -3);

// An array of 3 elements with initial values


// of different types
var tmp3 = new Array(1, "a", true);

// Makes tmp3 an array of 10 elements


tmp3.length = 10; // tmp[3] to tmp[9] are undefined.

// Makes tmp3 an array of 100 elements


tmp3[99] = "Something";
// tmp[3] to tmp[98] are undefined
Null & Undefined
 An undefined value is represented by the
keyword "undefined".
 It represents the value of an uninitialized
variable

 The keyword "null" is used to represent


“nothing”
 Declare and define a variable as “null” if
you want the variable to hold nothing.
 Avoid leaving a variable undefined.
Type Conversion (To
Boolean)
 The following values are treated as false
 null
 undefined
 +0, -0, NaN (numbers)
 "" (empty string)
Type Conversion
 Converting a value to a number
var numberVar = someVariable – 0;

 Converting a value to a string


var stringVar = someVariable + "";

 Converting a value to a boolean


var boolVar = !!someVariable;
Operators
 Arithmetic operators
 +, -, *, /, %
 Post/pre increment/decrement
 ++, --

 Comparison operators
 ==, !=, >, >=, <, <=
 ===, !== (Strictly equals and strictly not
equals)
 i.e.,
Type and value of operand must match / must
not match
== vs ===

// Type conversion is performed before comparison


var v1 = ("5" == 5); // true

// No implicit type conversion.


// True if only if both types and values are equal
var v2 = ("5" === 5); // false

var v3 = (5 === 5.0); // true

var v4 = (true == 1); // true (true is converted to 1)

var v5 = (true == 2); // false (true is converted to 1)

var v6 = (true == "1") // true


Logical Operators

 ! – Logical NOT
 && – Logical AND
 OP1 && OP2
 If OP1 is true, expression evaluates to the
value of OP2.
Otherwise the expression evaluates to the
value of OP1.
 Results may not be a boolean value.

 || – Logical OR
 OP1 || OP2
var tmp1 = null && 1000; // tmp1 is null

var tmp2 = 1000 && 500; // tmp2 is 500

var tmp3 = false || 500; // tmp3 is 500

var tmp4 = "" || null; // tmp4 is null

var tmp5 = 1000 || false; // tmp5 is 1000

// If foo is null, undefined, false, zero, NaN,


// or an empty string, then set foo to 100.
foo = foo || 100;
Operators (continue)
 String concatenation operator
 +
 If one of the operand is a string, the other
operand is automatically converted to its
equivalent string value.

 Assignment operators
 =, +=, -=, *=, /=, %=

 Bitwise operators
 &, |, ^, >>, <<, >>>
Conditional Statements
 “if” statement
 “if … else” statement

 "? :" ternary conditional statement

 “switch” statement

 The syntax of these statements are


similar to those found in C and Java.
Looping Statement
 “for” Loops
 “for/in” Loops
 “while” Loops
 “do … while” Loops
 “break” statement
 “continue” statement

 All except "for/in" loop statements have


the same syntax as those found in C and
Java.
“for/in” statement

for (var variable in object) {


statements;
}

 To iterate through all the properties in "object".

 "variable" takes the name of each property in


"object"

 Can be used to iterate all the elements in an


Array object.
var keys = "", values = "";
var mylist = new Array("Chinese", "English", "Jap");
mylist.newField1 = "Something";

for (var key in booklist) {


keys += key + " ";
values += booklist[counter] + " ";
}

// keys becomes "0 1 2 newField1"


// values becomes "Chinese English Jap Something"
var obj = new Object(); // Creating an object

// Adding three properties to obj


obj.prop1 = 123;
obj.prop2 = "456";
obj["prop3"] = true; // same as obj.prop3 = true

var keys = "", values = "";


for (var p in obj) {
keys += p + " ";
values += obj[p] + " ";
}
alert(keys);
// Show "prop1 prop2 pro3 "
alert(values);
// Show "123 456 true "
Functions (Return Values)
// A function can return value of any type using the
// keyword "return".

// The same function can possibly return values


// of different types
function foo (p1) {
if (typeof(p1) == "number")
return 0; // Return a number
else
if (typeof(p1) == "string")
return "zero"; // Return a string

// If no value being explicitly returned


// "undefined" is returned.
}

foo(1); // returns 0
foo("abc"); // returns "zero"
foo(); // returns undefined
Variable Arguments
// "arguments" is a local variable (an array) available
// in every function
// You can either access the arguments through parameters
// or through the "arguments" array.
function sum ()
{
var s = 0;
for (var i = 0; i < arguments.length; i++)
s += arguments[i];
return s;
}

sum(1, 2, 3); // returns 6


sum(1, 2, 3, 4, 5); // returns 15
sum(1, 2, "3", 4, 5); // returns ?
Built-In Functions
 eval(expr)
 evaluates an expression or statement
 eval("3 + 4"); // Returns 7 (Number)
 eval("alert('Hello')"); // Calls the function
alert('Hello')

 isFinite(x)
 Determines if a number is finite

 isNaN(x)
 Determines whether a value is “Not a
Built-In Functions
 parseInt(s)
 parseInt(s, radix)
 Converts string literals to integers
 Parses up to any character that is not part of a valid
integer
 parseInt("3 chances") // returns 3
 parseInt(" 5 alive") // returns 5
 parseInt("How are you") // returns NaN
 parseInt("17", 8) // returns 15

 parseFloat(s)
 Finds a floating-point value at the beginning of a string.
 parseFloat("3e-1 xyz") // returns 0.3
 parseFloat("13.5 abc") // returns 13.5
Creating objects using new
Object()

var person = new Object();

// Assign fields to object "person"


person.firstName = "John";
person.lastName = "Doe";

// Assign a method to object "person"


person.sayHi = function() {
alert("Hi! " + this.firstName + " " + this.lastName);
}

person.sayHi(); // Call the method in "person"


Creating objects using Literal
Notation

var person = {
// Declare fields
// (Note: Use comma to separate fields)
firstName : "John",
lastName : "Doe",

// Assign a method to object "person"


sayHi : function() {
alert("Hi! " + this.firstName + " " +
this.lastName);
}
}

person.sayHi(); // Call the method in "person"


Creating objects using Literal
Notation
(Nested notation is possible)
var triangle = {
// Declare fields (each as an object of two fields)
p1 : { x : 0, y : 3 },
p2 : { x : 1, y : 4 },
p3 : { x : 2, y : 5 }
}

alert(triangle.p1.y); // Show 3
Object Constructor and prototyping

function Person(fname, lname) {


// Define and initialize fields
this.firstName = fname;
this.lastName = lname;

// Define a method
this.sayHi = function() {
alert("Hi! " + this.firstName + " " +
this.lastName);
}
}

var p1 = new Person("John", "Doe");


var p2 = new Person("Jane", "Dow");

p1.sayHi(); // Show "Hi! John Doe"


p2.sayHi(); // Show "Hi! Jane Dow"
Adding methods to objects using
prototype

// Suppose we have defined the constructor "Person"


// (as in the previous slide).

var p1 = new Person("John", "Doe");


var p2 = new Person("Jane", "Dow");

// Aattaching a new method to all instances of Person


Person.prototype.sayHello = function() {
alert("Hello! " + this.firstName + " " +
this.lastName);
}

// We can also introduce new fields via "prototype"

p1.sayHello(); // Show "Hello! John Doe"


p2.sayHello(); // Show "Hello! Jane Dow"
Events

 An event occurs as a result of some


activity
 e.g.:
A user clicks on a link in a page
 Page finished loaded
 Mouse cursor enter an area
 A preset amount of time elapses
 A form is being submitted
Javascript functions: It contains set of statements that performs a
specific task or work or job based on the user action like clicking a
‘submit’ button and provides more reusability

<html>
<head>
<script type="text/javascript">
function sayHello()
{
document.write ("Hello there!");
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type="button" onclick="sayHello()" value="Say Hello">
</form>
<p>Use different text in write method and then try...</p>
</body>
Function Parameters
<html>
<head>
<script type="text/javascript">
function sayHello(name, age)
{
document.write (name + " is " + age + " years old.");
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type="button" onclick="sayHello('Zara', 7)" value="Say Hello">
</form>
<p>Use different parameters inside the function and then try...</p>
</body>
</html>
The return Statement
<head>
<script type="text/javascript">
function concatenate(first, last)
{
var full;
full = first + last;
return full;
}
function secondFunction()
{
var result;
result = concatenate('Zara', 'Ali');
document.write (result );
}
</script>
</head>
The return Statement

<body>
<p>Click the following button to call the
function</p>
<form>
<input type="button" onclick="secondFunction()"
value="Call Function">
</form>
<p>Use different parameters inside the function and
then
try...
</p>
</body>
Event Handlers

 Event Handler – a segment of codes


(usually a function) to be executed when
an event occurs

 We can specify event handlers as


attributes in the HTML tags.

 The attribute names typically take the


form "onXXX" where XXX is the event
name.
 e.g.:
Event Handlers

Event Handlers Triggered when


onChange The value of the text field, textarea, or a drop down list
is modified
onClick A link, an image or a form element is clicked once
onDblClick The element is double-clicked
onMouseDown The user presses the mouse button
onLoad A document or an image is loaded
onSubmit A user submits a form
onReset The form is reset
onUnLoad The user closes a document or a frame
onResize A form is resized by the user
For a complete list, see http://www.w3schools.com/htmldom/dom_obj_event.asp
onClick Event Handler
Example
<html>
<head>
<title>onClick Event Handler Example</title>
<script type="text/javascript">
function warnUser() {
return confirm("Are you a student?”);
}
</script>
</head>
<body>
<a href="ref.html" onClick="return warnUser()">
<!--
If onClick event handler returns false, the link
is not followed.
-->
Students access only</a>
</body>
</html>
onLoad Event Handler
Example
<html><head>
<title>onLoad and onUnload Event Handler Example</title>
</head>
<body
onLoad="alert('Welcome to this page')"
onUnload="alert('Thanks for visiting this page')"
>
Load and UnLoad event test.
</body>
</html>
onMouseOver & onMouseOut Event
Handler
<html>
<head>
<title>onMouseOver / onMouseOut Event Handler Demo</title>
</head>
<body>
<a href="http://www.cuhk.edu.hk"
onMouseOver="window.status='CUHK Home'; return true;"
onMouseOut="status=''"
>CUHK</a>
</body>
</html>
• When the mouse cursor is over the link, the browser displays the text
"CUHK Home" instead of the URL.
• The "return true;" of onMouseOver forces browser not to display the URL.
• window.status and window.defaultStatus are disabled in Firefox.
onSubmit Event Handler Example
<html><head>
<title>onSubmit Event Handler Example</title>
<script type="text/javascript">
function validate() {
// If everything is ok, return true
// Otherwise return false
}
</script>
</head>
<body>
<form action="MessageBoard" method="POST"
onSubmit="return validate();"
>

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

• If onSubmit event handler returns false, data is not submitted.


• If onReset event handler returns false, form is not reset
Build-In JavaScript Objects
Object Description
Array Creates new array objects
Boolean Creates new Boolean objects
Date Retrieves and manipulates dates and times
Error Returns run-time error information
Function Creates new function objects
Math Contains methods and properties for performing mathematical
calculations
Number Contains methods and properties for manipulating numbers.
String Contains methods and properties for manipulating text strings
• See online references for complete list of available methods in these
objects: http://javascript-reference.info/
String Object (Some useful methods)

 length
A string property that tells the number of character in the string
 charAt(idx)
 Returns the character at location "idx"
 toUpperCase(), toLowerCase()
 Returns the same string with all uppercase/lowercase
letters
 substring(beginIdx)
 Returns a substring started at location "beginIdx"
 substring(beginIdx, endIdx)
 Returns a substring started at "beginIdx" until "endIdx"
(but not including "endIdx"
 indexOf(str)

Error and Exception Handling in
JavaScript

 Javascript makes no distinction between


Error and Exception (Unlike Java)
 Handling Exceptions
 The onError event handler
 A method associated with the window object.
 It is called whenever an exception occurs
 The try … catch … finally block
 Similar to Java try … catch … finally block
 For handling exceptions in a code segment
 Use throw statement to throw an exception
 You can throw value of any type
 The Error object
 Default object for representing an exception
How to use “onError” event handler?

<html>
<head>
<title>onerror event handler example</title>
<script type="text/javascript">
function errorHandler(){
alert("Error Ourred!");
}
// JavaScript is casesensitive
// Don't write onerror!
window.onError = errorHandler;
</script>
</head>
<body>
<script type="text/javascript">
document.write("Hello there;
</script>
</body>
</html>
The addEventListener() method

 The addEventListener() method attaches an event handler to the

specified element.

 It attaches an event handler to an element without overwriting

existing event handlers.

 You can add many event handlers to one element.

 You can add many event handlers of the same type to one element,

i.e two "click" events.

 You can add event listeners to any DOM object not only HTML

elements. i.e the window object.

 The addEventListener() method makes it easier to control how the


Syntax

 element.addEventListener(event, function,
useCapture);
 The first parameter is the type of the event (like "click"
or "mousedown").
 The second parameter is the function we want to call
when the event occurs.
 The third parameter is a boolean value specifying
whether to use event bubbling or event capturing. This
parameter is optional.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript addEventListener()</h2>
<p>This example uses the addEventListener() method to attach a
click event to a button.</p>
<button id="myBtn">Try it</button>
<script>
document.getElementById("myBtn").addEventListener("click",
function(){
alert("Hello World!");
});
</script>
</body>
</html>
Add Many Event Handlers to the Same
Element

<html>
<body>
<h2>JavaScript addEventListener()</h2>
<p>This example uses the addEventListener() method to add two click
events to the same button.</p>
<button id="myBtn">Try it</button>
<script>
var x = document.getElementById("myBtn");
x.addEventListener("click", myFunction);
x.addEventListener("click", someOtherFunction);
function myFunction() { alert ("Hello World!"); }
function someOtherFunction() { alert ("This function was also
executed!"); }
</script>
</body>
Output
try … catch … finally

try {
// Contains normal codes that might throw an exception.

// If an exception is thrown, immediately go to


// catch block.

} catch ( errorVariable ) {
// Codes here get executed if an exception is thrown
// in the try block.

// The errorVariable is an Error object.

} finally {
// Executed after the catch or try block finish

// Codes in finally block are always executed


}
// One or both of catch and finally blocks must accompany the try block.
try … catch … finally
example
<script type="text/javascript">
try{
document.write("Try block begins<br>");
// create a syntax error
eval ("10 + * 5");

} catch( errVar ) {
document.write("Exception caught<br>");
// errVar is an Error object
// All Error objects have a name and message properties
document.write("Error name: " + errVar.name + "<br>");
document.write("Error message: " + errVar.message +
"<br>");
} finally {
document.write("Finally block reached!");
}
</script>
Throwing Exception

<script type="text/javascript">
try{
var num = prompt("Enter a number (1-2):", "1");
// You can throw exception of any type
if (num == "1")
throw "Some Error Message";
else
if (num == "2")
throw 123;
else
throw new Error ("Invalid input");
} catch( err ) {
alert(typeof(errMsg) + "\n" + err);
// instanceof operator checks if err is an Error object
if (err instanceof Error)
alert("Error Message: " + err.message);
}
</script>

You might also like