Nothing Special   »   [go: up one dir, main page]

HTML

Download as pdf or txt
Download as pdf or txt
You are on page 1of 104

HTML

After Vannevar Bush first proposed the basics of hypertext in 1945, it laid the foundation for Tim Berners-Lee
and others to invent the World Wide Web, HTML (hypertext markup language), HTTP (HyperText Transfer
Protocol) and URLs (Universal Resource Locators) in 1990.
Definition of HTML
HTML stands for HyperText Markup Language, it is the authoring language used to create documents on the
World Wide Web. HTML is used to define the structure and layout of a Web page, how a page looks and any
special functions. HTML does this by using what are called tags that have attributes. For example <p> means a
paragraph break. As the viewer of a web page you don't see the HTML, it is hidden from your view, however,
you do the results.
Tim Berners-Lee & HTML
Tim Berners-Lee was the primary author of html, assisted by his colleagues at CERN, an international scientific
organization based in Geneva, Switzerland. Tim Berners-Lee is currently the Director of the World Wide Web
Consortium, the group that sets technical standards for the Web.

Above view is a Tim Berners-Lee's Browser Editor as developed in 1991-92. This was a true browser editor for
the first version of HTML and ran on a NeXt workstation. Implemented in Objective-C, it made it easy to create,
view and edit web documents. Hypertext Markup Language (First Version of HTML) was formally published on
June 1993.
Definition: HTML is Hypertext Markup Language, the computer language used to create pages on the World
Wide Web. HTML was created by a physicist named Tim Berners-Lee, and introduced to the world in 1989. HTML
is related to SGML (Structured General Markup Language), JavaScript (a Netscape scripting language), and Java
(a Sun Microsystems language). HTML is used to define web pages by using "tags" and "attributes". Tags are the
programmatic commands that appear between < > symbols. The regular structure for an HTML document
contains this kind of tag appearance: <HTML><HEAD> (Welcome to my web page) </HEAD><BODY> (hundreds
of lines of text go here) </BODY></HTML>.

HTML5
HTML 5 is the newest version of HTML (hypertext markup language,) which is special code used to create and
format web pages. The HTML formatting or markup language has gone through multiple revisions, and its
specifications are set by a group known as the W3C for World Wide Web Consortium. Another group called
WHATWG (Web Hypertext Application Technology Working Group) actually started the work on HTML5, but it's
now working separate (though partly in parallel) to the work of the W3C.
HTML 5 adds a lot of new features to the HTML specification. And what's even better, there is already some
limited browser support for these new features. If there is a feature you're interested in, watch the WHATWG
Wiki Implementations page for information on browsers that support various parts of the specification.
HTML 5 New Doctype and Charset
The nice thing about HTML 5 is how easy it is to implement. You use the HTML 5 doctype, which is very simple
and streamlined:
<!doctype html>
Yes, that's it. Just two words "doctype" and "html". It can be this simple because HTML 5 is no longer part of
SGML, but is instead a markup language all on its own.
The character set for HTML 5 is streamlined as well. It uses UTF-8 and you define it with just one Meta tag:
<meta charset="UTF-8">
HTML 5 New Structure
HTML 5 recognizes that Web pages have a structure, just like books have a structure or other XML documents.
In general, Web pages have navigation, body content, and sidebar content plus headers, footers, and other
features. And HTML 5 has created tags to support those elements of the page.
<section> - to define sections of pages
<header> - defines the header of a page
<footer> - defines the footer of a page
<nav> - defines the navigation on a page
<article> - defines the article or primary content on a page
<aside> - defines extra content like a sidebar on a page
<figure> - defines images that annotate an article
HTML 5 New Inline Elements
These inline elements define some basic concepts and keep them semantically marked up, mostly to do with
time:
<mark> - to indicate content that is marked in some fashion
<time> - to indicate content that is a time or date
<meter> - to indicate content that is a fraction of a known range - such as disk usage
<progress> - to indicate the progress of a task towards completion
HTML 5 New Dynamic Pages Support
HTML 5 was developed to help Web application developers, so there are a lot of new features to make it easy
to create dynamic HTML pages:
Context menus - HTML 5 will support the creation and use of context menus within Web pages and
applications
href is not required on a tag - this allows you to use the a tag with scripts and in Web applications
without needing a place to send that anchor
async attribute - This is added to the script tag to tell the browser that the script should be loaded
asynchronously so that it doesn't slow down the load and display of the rest of the page.
<details> - provides details about an element. This would be like tooltips in non-Web applications.
<datagrid> - creates a table that is built from a database or other dynamic source
<menu> - an old tag brought back and given new life allowing you to create a menu system on your
Web pages
<command> - defines actions that should happen when a dynamic element is activated

HTML 5 New Form Types


HTML 5 supports all the standard form input types, but it adds a few more:
datetime
datetime-local
date
month
week
time
number
range
email
url
HTML 5 New Elements
There are a few exciting new elements in HTML 5:
<canvas> - an element to give you a drawing space in JavaScript on your Web pages. It can let you add
images or graphs to tool tips or just create dyanmic graphs on your Web pages, built on the fly.
<video> - add video to your Web pages with this simple tag.
<audio> - add sound to your Web pages with this simple tag.
HTML 5 Removes Some Elements
There are also some elements in HTML 4 that will no longer be supported by HTML 5. Most are already
deprecated, and so shouldn't be surprising, but a few might be difficult:
acronym
frameset
applet
isindex
basefont
noframes
big
noscript
center
s
dir
strike
font
tt
frame
u
HTML Elements
Legend: Optional, Forbidden, Empty, Deprecated, Loose DTD, Frameset DTD
Name

Start Tag End Tag Empty Depr. DTD Description

A
ABBR
ACRONYM
ADDRESS
APPLET
AREA
B
BASE
BASEFONT
BDO
BIG
BLOCKQUOTE
BODY
O
BR
BUTTON
CAPTION
CENTER
CITE

anchor
abbreviated form (e.g., WWW, HTTP, etc.)

F
F

E
E

O
F

information on author
Java applet
client-side image map area
bold text style
document base URI
base font size
I18N BiDi over-ride
large text style
long quotation
document body
forced line break
push button
table caption
shorthand for DIV align=center
citation

CODE
COL
COLGROUP
DD
DEL
DFN
DIR
DIV
DL
DT
EM
FIELDSET
FONT
FORM
FRAME
FRAMESET
H1
H2
H3
H4
H5
H6
HEAD
HR
HTML
I
IFRAME
IMG
INPUT
INS
ISINDEX
KBD
LABEL
LEGEND
LI
LINK
MAP
MENU
META
NOFRAMES
NOSCRIPT
OBJECT
OL
OPTGROUP
OPTION
P
PARAM
PRE

F
O
O

O
O

O
F
O

F
F

L
F
F

E
E

O
F

E
F

O
O
F

computer code fragment


table column
table column group
definition description
deleted text
instance definition
directory list
generic language/style container
definition list
definition term
emphasis
form control group
local change to font
interactive form
subwindow
window subdivision
heading
heading
heading
heading
heading
heading
document head
horizontal rule
document root element
italic text style
inline subwindow
Embedded image
form control
inserted text
single line prompt
text to be entered by the user
form field label text
fieldset legend
list item
a media-independent link
client-side image map
menu list
generic metainformation
alternate content container for non frame-based rendering
alternate content container for non script-based rendering
generic embedded object
ordered list
option group
selectable choice
paragraph
named property value
preformatted text

Q
S
D
L
SAMP
SCRIPT
SELECT
SMALL
SPAN
STRIKE
D
L
STRONG
STYLE
SUB
SUP
TABLE
TBODY
O
O
TD
O
TEXTAREA
TFOOT
O
TH
O
THEAD
O
TITLE
TR
O
TT
U
D
L
UL
VAR
Index of Attributes
Legend: Deprecated, Loose DTD, Frameset DTD
Name
Related Elements
Type

short inline quotation


strike-through text style
sample program output, scripts, etc.
script statements
option selector
small text style
generic language/style container
strike-through text
strong emphasis
style info
subscript
superscript
table body
table data cell
multi-line text field
table footer
table header cell
table header
document title
table row
teletype or monospaced text style
underlined text style
unordered list
instance of a variable or program argument

Default

Depr.

abbr

TD, TH

%Text;

#IMPLIED

acceptcharset

FORM

%Charsets;

#IMPLIED

accept

FORM, INPUT

%ContentTypes;

#IMPLIED

accesskey

A, AREA, BUTTON, INPUT, LABEL,


%Character;
LEGEND, TEXTAREA

#IMPLIED

action

FORM

%URI;

#REQUIRED

align

CAPTION

%CAlign;

#IMPLIED

align

APPLET, IFRAME, IMG, INPUT, OB


%IAlign;
JECT

#IMPLIED

align

LEGEND

%LAlign;

#IMPLIED

align

TABLE

%TAlign;

#IMPLIED

align

HR

align

DIV, H1, H2, H3, H4, H5, H6, P

(left | center | right) #IMPLIED


(left | center | right |
#IMPLIED
justify)

DTD Comment
abbreviation for
header cell
list of supported
charsets
list of MIME types
for file upload
accessibility key
character
server-side form
handler
L
relative to table
vertical
or
L
horizontal
alignment
L
relative to fieldset
table
position
L
relative
to
window
L
align,
text
L
alignment

align

COL, COLGROUP, TBODY, TD, TFO (left | center | right |


#IMPLIED
OT, TH, THEAD, TR
justify | char)

alink

BODY

%Color;

#IMPLIED

alt
alt
alt

APPLET
AREA, IMG
INPUT

%Text;
%Text;
CDATA

#IMPLIED
D
#REQUIRED
#IMPLIED

archive

APPLET

CDATA

#IMPLIED

archive

OBJECT

CDATA

#IMPLIED

axis

TD, TH

CDATA

#IMPLIED

background BODY

%URI;

#IMPLIED

bgcolor

TABLE

%Color;

#IMPLIED

bgcolor

TR

%Color;

#IMPLIED

bgcolor

TD, TH

%Color;

#IMPLIED

bgcolor

BODY

%Color;

#IMPLIED

border

TABLE

%Pixels;

#IMPLIED

border

IMG, OBJECT

%Pixels;

#IMPLIED

cellpadding TABLE

%Length;

#IMPLIED

cellspacing TABLE

%Length;

#IMPLIED

char
charoff

COL, COLGROUP, TBODY, TD, TFO


%Character;
OT, TH, THEAD, TR
COL, COLGROUP, TBODY, TD, TFO
%Length;
OT, TH, THEAD, TR

#IMPLIED
#IMPLIED

color of selected
links
short description
short description
short description
comma-separated
archive list
space-separated
list of URIs
comma-separated
list of related
headers
texture tile for
document
background
background color
for cells
background color
for row
cell background
color
document
background color
controls
frame
width
around
table
link border width
spacing
within
cells
spacing between
cells
alignment char,
e.g. char=':'
offset
for
alignment char
char encoding of
linked resource
for radio buttons
and check boxes
URI for source
document or msg
info on reason for
change

charset

A, LINK, SCRIPT

%Charset;

#IMPLIED

checked

INPUT

(checked)

#IMPLIED

cite

BLOCKQUOTE, Q

%URI;

#IMPLIED

cite

DEL, INS

%URI;

#IMPLIED

class

All
elements but BASE, BASEFONT, H
CDATA
EAD, HTML, META, PARAM, SCRIP
T, STYLE, TITLE

#IMPLIED

space-separated
list of classes

classid

OBJECT

#IMPLIED

identifies
an
implementation

%URI;

clear

BR

code

APPLET

(left | all | right |


none
none)
CDATA
#IMPLIED

codebase

OBJECT

%URI;

#IMPLIED

codebase

APPLET

%URI;

#IMPLIED

codetype

OBJECT

%ContentType;

#IMPLIED

color

BASEFONT, FONT

%Color;

#IMPLIED

cols

FRAMESET

%MultiLengths;

#IMPLIED

cols

TEXTAREA

NUMBER

#REQUIRED

colspan

TD, TH

NUMBER

compact

DIR, DL, MENU, OL, UL

(compact)

#IMPLIED

content

META

CDATA

#REQUIRED

coords

AREA

%Coords;

#IMPLIED

coords

%Coords;

#IMPLIED

data

OBJECT

%URI;

#IMPLIED

datetime

DEL, INS

%Datetime;

#IMPLIED

declare

OBJECT

(declare)

#IMPLIED

defer

SCRIPT

(defer)

#IMPLIED

dir
dir
disabled

All
elements but APPLET, BASE, BASE
(ltr | rtl)
FONT, BDO, BR, FRAME, FRAMES
ET, IFRAME,PARAM, SCRIPT
BDO
(ltr | rtl)
BUTTON, INPUT, OPTGROUP, OPT
(disabled)
ION, SELECT, TEXTAREA

L
F

#REQUIRED

directionality
unavailable in this
context

#IMPLIED

enctype

FORM

%ContentType;

face

BASEFONT, FONT

CDATA

#IMPLIED

for

LABEL

IDREF

#IMPLIED

frame

TABLE

%TFrame;

#IMPLIED

number of cols
spanned by cell
reduced interitem
spacing
associated
information
comma-separated
list of lengths
for
use
with
client-side image
maps
reference
to
object's data
date and time of
change
declare but don't
instantiate flag
UA may defer
execution of script
direction
for
weak/neutral text

#IMPLIED

"application
/x-wwwformurlencoded"

control of text
flow
applet class file
base URI for
classid,
data,
archive
optional base URI
for applet
content type for
code
text color
list of lengths,
default: 100% (1
col)

comma-separated
list of font names
matches field ID
value
which parts of
frame to render

frameborde
FRAME, IFRAME
r

(1 | 0)

headers

TD, TH

IDREFS

#IMPLIED

height
height
height
height

IFRAME
TD, TH
IMG, OBJECT
APPLET

%Length;
%Length;
%Length;
%Length;

#IMPLIED
#IMPLIED
D
#IMPLIED
#REQUIRED D

href

A, AREA, LINK

%URI;

#IMPLIED

href

BASE

%URI;

#IMPLIED

hreflang
hspace

A, LINK
APPLET, IMG, OBJECT

%LanguageCode;
%Pixels;

#IMPLIED
#IMPLIED

NAME

#IMPLIED

http-equiv META

L
L
L

id

All
elements but BASE, HEAD, HTML, ID
META, SCRIPT, STYLE, TITLE

#IMPLIED

ismap

IMG, INPUT

(ismap)

#IMPLIED

label

OPTION

%Text;

#IMPLIED

label

OPTGROUP

%Text;

#REQUIRED

lang

All
elements but APPLET, BASE, BASE
%LanguageCode;
FONT, BR, FRAME, FRAMESET, IFR
AME,PARAM, SCRIPT

#IMPLIED

language

SCRIPT

CDATA

#IMPLIED

link

BODY

%Color;

#IMPLIED

longdesc

IMG

%URI;

#IMPLIED

longdesc

FRAME, IFRAME

%URI;

#IMPLIED

%Pixels;

#IMPLIED

%Pixels;

#IMPLIED

maxlength INPUT

NUMBER

#IMPLIED

media

STYLE

%MediaDesc;

#IMPLIED

media

LINK

%MediaDesc;

#IMPLIED

marginheig
FRAME, IFRAME
ht
marginwidt
FRAME, IFRAME
h

request
frame
borders?
list of id's for
header cells
frame height
height for cell
override height
initial height
URI for linked
resource
URI that acts as
base URI
language code
horizontal gutter
HTTP
response
header name
document-wide
unique id
use
server-side
image map
for
use
in
hierarchical
menus
for
use
in
hierarchical
menus

language code
predefined script
language name
color of links
link
to
long
description
(complements alt)
link
to
long
description
(complements
title)
margin height in
pixels
margin widths in
pixels
max chars for text
fields
designed for use
with these media
for rendering on
these media

HTTP
method
used to submit
the form
default is single
selection

method

FORM

(GET | POST)

GET

multiple

SELECT

(multiple)

#IMPLIED

name

BUTTON, TEXTAREA

CDATA

#IMPLIED

name

APPLET

CDATA

#IMPLIED

name

SELECT

CDATA

#IMPLIED

name

FORM

CDATA

#IMPLIED

name

FRAME, IFRAME

CDATA

#IMPLIED

name

IMG

CDATA

#IMPLIED

name

CDATA

#IMPLIED

name

INPUT, OBJECT

CDATA

#IMPLIED

name

MAP

CDATA

#REQUIRED

name

PARAM

CDATA

#REQUIRED

name

META

NAME

#IMPLIED

nohref

AREA

(nohref)

#IMPLIED

noresize

FRAME

(noresize)

#IMPLIED

noshade

HR

(noshade)

#IMPLIED

nowrap

TD, TH

(nowrap)

#IMPLIED

object

APPLET

CDATA

#IMPLIED

onblur

A, AREA, BUTTON, INPUT, LABEL,


%Script;
SELECT, TEXTAREA

#IMPLIED

onchange

INPUT, SELECT, TEXTAREA

#IMPLIED

%Script;

All
elements but APPLET, BASE, BASE
FONT, BDO, BR, FONT, FRAME, FR
onclick
%Script;
AMESET,HEAD, HTML, IFRAME, IS
INDEX, META, PARAM, SCRIPT, ST
YLE, TITLE
All
elements but APPLET, BASE, BASE
FONT, BDO, BR, FONT, FRAME, FR
ondblclick
%Script;
AMESET,HEAD, HTML, IFRAME, IS
INDEX, META, PARAM, SCRIPT, ST
YLE, TITLE
A, AREA, BUTTON, INPUT, LABEL,
onfocus
%Script;
SELECT, TEXTAREA
All
onkeydown
%Script;
elements but APPLET, BASE, BASE

allows applets to
find each other
field name
name of form for
scripting
name of frame for
targetting
name of image for
scripting
named link end
submit as part of
form
for reference by
usemap
property name
metainformation
name
this region has no
action
allow users to
resize frames?
suppress
word
wrap
serialized applet
file
the element lost
the focus
the element value
was changed

#IMPLIED

a pointer button
was clicked

#IMPLIED

a pointer button
was
double
clicked

#IMPLIED
#IMPLIED

the element got


the focus
a key was pressed
down

FONT, BDO, BR, FONT, FRAME, FR


AMESET,HEAD, HTML, IFRAME, IS
INDEX, META, PARAM, SCRIPT, ST
YLE, TITLE
All
elements but APPLET, BASE, BASE
FONT, BDO, BR, FONT, FRAME, FR
onkeypress
%Script;
AMESET,HEAD, HTML, IFRAME, IS
INDEX, META, PARAM, SCRIPT, ST
YLE, TITLE
All
elements but APPLET, BASE, BASE
FONT, BDO, BR, FONT, FRAME, FR
onkeyup
%Script;
AMESET,HEAD, HTML, IFRAME, IS
INDEX, META, PARAM, SCRIPT, ST
YLE, TITLE

#IMPLIED

a key was pressed


and released

#IMPLIED

a key was released

onload

FRAMESET

%Script;

#IMPLIED

onload

BODY

%Script;

#IMPLIED

onmousedo
wn

onmousem
ove

onmouseou
t

onmouseov
er

onmouseup

All
elements but APPLET, BASE, BASE
FONT, BDO, BR, FONT, FRAME, FR
%Script;
AMESET,HEAD, HTML, IFRAME, IS
INDEX, META, PARAM, SCRIPT, ST
YLE, TITLE
All
elements but APPLET, BASE, BASE
FONT, BDO, BR, FONT, FRAME, FR
%Script;
AMESET,HEAD, HTML, IFRAME, IS
INDEX, META, PARAM, SCRIPT, ST
YLE, TITLE
All
elements but APPLET, BASE, BASE
FONT, BDO, BR, FONT, FRAME, FR
%Script;
AMESET,HEAD, HTML, IFRAME, IS
INDEX, META, PARAM, SCRIPT, ST
YLE, TITLE
All
elements but APPLET, BASE, BASE
FONT, BDO, BR, FONT, FRAME, FR
%Script;
AMESET,HEAD, HTML, IFRAME, IS
INDEX, META, PARAM, SCRIPT, ST
YLE, TITLE
All
elements but APPLET, BASE, BASE
FONT, BDO, BR, FONT, FRAME, FR
%Script;
AMESET,HEAD, HTML, IFRAME, IS
INDEX, META, PARAM, SCRIPT, ST
YLE, TITLE

all the frames


have been loaded
the document has
been loaded

#IMPLIED

a pointer button
was pressed down

#IMPLIED

a pointer was
moved within

#IMPLIED

a pointer was
moved away

#IMPLIED

a pointer was
moved onto

#IMPLIED

a pointer button
was released

onreset

FORM

%Script;

#IMPLIED

onselect

INPUT, TEXTAREA

%Script;

#IMPLIED

the form
reset
some text
selected

was
was

onsubmit

FORM

%Script;

#IMPLIED

onunload

FRAMESET

%Script;

#IMPLIED

onunload

BODY

%Script;

#IMPLIED

profile

HEAD

%URI;

#IMPLIED

prompt
readonly

ISINDEX
TEXTAREA

%Text;
(readonly)

#IMPLIED
#IMPLIED

readonly

INPUT

(readonly)

#IMPLIED

rel
rev

A, LINK
A, LINK

%LinkTypes;
%LinkTypes;

#IMPLIED
#IMPLIED

rows

FRAMESET

%MultiLengths;

#IMPLIED

rows

TEXTAREA

NUMBER

#REQUIRED

rowspan

TD, TH

NUMBER

rules

TABLE

%TRules;

#IMPLIED

scheme

META

CDATA

#IMPLIED

scope

TD, TH

%Scope;

#IMPLIED

scrolling
selected

FRAME, IFRAME
OPTION

(yes | no | auto)
(selected)

auto
#IMPLIED

shape

AREA

%Shape;

rect

shape

%Shape;

rect

size

HR

%Pixels;

#IMPLIED

size

FONT

CDATA

#IMPLIED

size

INPUT

CDATA

#IMPLIED

size

BASEFONT

CDATA

#REQUIRED D

size

SELECT

NUMBER

#IMPLIED

span

COL

NUMBER

span

COLGROUP

NUMBER

src

SCRIPT

%URI;

#IMPLIED

the form was


submitted
all the frames
have
been
removed
the document has
been removed
named dictionary
of meta info
prompt message
for
text
and
passwd
forward link types
reverse link types
list of lengths,
default: 100% (1
row)
number of rows
spanned by cell
rulings between
rows and cols
select form of
content
scope covered by
header cells
scrollbar or none
controls
interpretation of
coords
for
use
with
client-side image
maps
[+|-]nn
e.g.
size="+1",
size="4"
specific to each
type of field
base font size for
FONT elements
rows visible
COL
attributes
affect N columns
default number of
columns in group
URI
for
an
external script

src

INPUT

%URI;

#IMPLIED

src

FRAME, IFRAME

%URI;

#IMPLIED

src

IMG

%URI;

#REQUIRED

standby

OBJECT

%Text;

#IMPLIED

start

OL

NUMBER

#IMPLIED

style

All
elements but BASE, BASEFONT, H
%StyleSheet;
EAD, HTML, META, PARAM, SCRIP
T, STYLE, TITLE

#IMPLIED

summary

TABLE

#IMPLIED

tabindex

A, AREA, BUTTON, INPUT, OBJECT


NUMBER
, SELECT, TEXTAREA

#IMPLIED

target

A, AREA, BASE, FORM, LINK

%FrameTarget;

#IMPLIED

text

BODY

%Color;

#IMPLIED

title

All
elements but BASE, BASEFONT, H
%Text;
EAD, HTML, META, PARAM, SCRIP
T, TITLE

#IMPLIED

type

A, LINK

%ContentType;

#IMPLIED

type

OBJECT

%ContentType;

#IMPLIED

type

PARAM

%ContentType;

#IMPLIED

type

SCRIPT

%ContentType;

#REQUIRED

type

STYLE

%ContentType;

#REQUIRED

type

INPUT

%InputType;

TEXT

type
type
type

LI
OL
UL

type

BUTTON

%LIStyle;
#IMPLIED
%OLStyle;
#IMPLIED
%ULStyle;
#IMPLIED
(button | submit |
submit
reset)

usemap

IMG, INPUT, OBJECT

valign

COL, COLGROUP, TBODY, TD, TFO (top | middle |


#IMPLIED
OT, TH, THEAD, TR
bottom | baseline)

value

INPUT

%Text;

%URI;

CDATA

#IMPLIED

#IMPLIED

for fields with


images
source of frame
content
URI of image to
embed
message to show
while loading
starting sequence
number
associated
info

L
D

style

purpose/structur
e for speech
output
position
in
tabbing order
render in this
frame
document
text
color
advisory title

D
D
D

L
L
L

advisory content
type
content type for
data
content type for
value
when
valuetype=ref
content type of
script language
content type of
style language
what kind of
widget is needed
list item style
numbering style
bullet style
for use as form
button
use
client-side
image map
vertical alignment
in cells
Specify for radio
buttons
and
checkboxes

value

OPTION

CDATA

#IMPLIED

value

PARAM

CDATA

#IMPLIED

value

BUTTON

CDATA

#IMPLIED

value

LI

NUMBER

#IMPLIED

valuetype

PARAM

(DATA |
OBJECT)

version

HTML

vlink

CDATA

%HTML.Vers
D
ion;

BODY

%Color;

#IMPLIED

vspace
width
width
width
width
width
width

APPLET, IMG, OBJECT


HR
IFRAME
IMG, OBJECT
TABLE
TD, TH
APPLET

%Pixels;
%Length;
%Length;
%Length;
%Length;
%Length;
%Length;

#IMPLIED
#IMPLIED
#IMPLIED
#IMPLIED
#IMPLIED
#IMPLIED
#REQUIRED

D
D

L
L
L

width

COL

%MultiLength;

#IMPLIED

width

COLGROUP

%MultiLength;

#IMPLIED

width

PRE

NUMBER

#IMPLIED

REF

DATA

Basic HTML Examples


First.html
<html>
<body>
<h1>This is heading 1</h1>
<h2>This is heading 2</h2>
<h3>This is heading 3</h3>
<h4>This is heading 4</h4>
<h5>This is heading 5</h5>
<h6>This is heading 6</h6>
<p>My first paragraph.</p>
<p>
This paragraph
contains a lot of spaces
in the source code,
but the browser
ignores it.
</p>
<p>This is<br>a para<br>graph with line breaks</p>
<!--This comment will not be displayed-->
<hr> <!--This HR tag generates horizontal rule over you documents -->
<b>This text is bold</b>
<strong>This text is strong</strong>
<em>This text is emphasized</em>

D
D

L
L

defaults
to
element content
property value
sent to server
when submitted
reset
sequence
number
How to interpret
value
Constant
color of visited
links
vertical gutter
frame width
override width
table width
width for cell
initial width
column
width
specification
default width for
enclosed COLs

<i>This text is italic</i>


<small>This text is small</small>
<p>This is<sub> subscript</sub> and <sup>superscript</sup></p>
<pre>
This is
preformatted text.
It preserves both spaces
and line breaks.
</pre>
<pre>
for i = 1 to 10
print i
next i
</pre>
<code>Computer code</code> <br>
<kbd>Keyboard input</kbd> <br>
<samp>Sample text</samp> <br>
<var>Computer variable</var> <br>
<p><b>Note:</b> These tags are often used to display computer/programming code.</p>
<p>The <abbr title="World Health Organization">WHO</abbr> was founded in 1948.</p>
<p> try to keep mouse over <abbr title="as soon as possible">ASAP</abbr> and see the effects</p>
<p>
If your browser supports bi-directional override (bdo), the next line will be written from the right to the left
(rtl):
</p>
<bdo dir="rtl">
Here is some Hebrew text
</bdo>
<h2>The &lt;blockquote&gt; tag</h2>
<p>The &lt;blockquote&gt; tag specifies a section that is quoted from another source.</p>
<p>Here is a quote from WWF's website:</p>
<blockquote cite="http://www.worldwildlife.org/who/index.html">
For 50 years, WWF has been protecting the future of nature. The worlds leading conservation organization,
WWF works in 100 countries and is supported by 1.2 million members in the United States and close to 5
million globally.
</blockquote>
<p><b>Note:</b> Browsers usually indent &lt;blockquote&gt; elements.</p>
<h2>The &lt;q&gt; tag</h2>
<p>The &lt;q&gt; tag defines a short quotation.</p>
<p>WWF's goal is to:
<q>Build a future where people live in harmony with nature.</q>
We hope they succeed.</p>
<p><b>Note:</b> Browsers insert quotation marks around the &lt;q&gt; tag.</p>
<p>My favorite color is <del>blue</del> <ins>red</ins>!</p>
<p>Notice that browsers will strikethrough deleted text and underline inserted text.</p>
<address>
Written by W3Schools.com<br>
<a href="mailto:us@example.org">Email us</a><br>

Address: Box 564, Disneyland<br>


Phone: +12 34 56 78
</address>
<a href="http://www.meropalo.com">This is a link to MeroPalo</a>
<img src="pictures.jpg" width="104" height="142" alt=this is image />
</body>
</html>
HTML Styles
Division Styles
<html>
<body>
<div style="opacity:0.5;position:absolute;left:50px;width:300px;height:150px;backgroundcolor:#40B3DF"></div>
<div style="font-family:verdana;padding:20px;border-radius:10px;border:10px solid #EE872A;">
<div style="opacity:0.3;position:absolute;left:120px;width:100px;height:200px;backgroundcolor:#8AC007"></div>
<h3>Look! Styles and colors</h3>
<div style="letter-spacing:12px;">Manipulate Text</div>
<div style="color:#40B3DF;">Colors
<span style="background-color:#B4009E;color:#ffffff;">Boxes</span>
</div>
<div style="color:#000000;">and more...</div>
</div>
</body>
</html>
Background Color
<html>
<body style="background-color:yellow;">
<h2 style="background-color:red;">This is a heading</h2>
<p style="background-color:green;">This is a paragraph.</p>
</body>
</html>
Paragraph Styles
<html>
<body>
<h1 style="font-family:verdana;">A heading</h1>
<p style="font-family:arial;color:red;font-size:20px;">A paragraph.</p>
</body>
</html>
Text Align
<html>
<body>
<h1 style="text-align:center;">Center-aligned heading</h1>
<p>This is a paragraph.</p>
</body>
</html>

Anchor/Link
<html>
<body>
<a href="http://www.w3schools.com" style="text-decoration:none;">Visit W3Schools.com!</a>
</body>
</html>
Anchor with Images
<html>
<body>
<p>Create a link of an image:
<a href="default.asp">
<img src="smiley.gif" alt="HTML tutorial" width="32" height="32"></a></p>
<p>No border around the image, but still a link:
<a href="default.asp">
<img border="0" src="smiley.gif" alt="HTML tutorial" width="32" height="32"></a></p>
</body>
</html>
Anchor with Target
<html>
<body>
<a href="http://www.w3schools.com" target="_blank">Visit W3Schools.com!</a>
<p>If you set the target attribute to "_blank", the link will open in a new browser window/tab.</p>
</body>
</html>
In page Anchor Navigation
<html>
<body>
<p><a href="#C4">See also Chapter 4.</a></p>
<h2>Chapter 1</h2>
<p>This chapter explains ba bla bla</p>
<h2>Chapter 2</h2>
<p>This chapter explains ba bla bla</p>
<h2>Chapter 3</h2>
<p>This chapter explains ba bla bla</p>
<h2><a id="C4">Chapter 4</a></h2>
<p>This chapter explains ba bla bla</p>
<h2>Chapter 5</h2>
<p>This chapter explains ba bla bla</p>
<h2>Chapter 6</h2>
<p>This chapter explains ba bla bla</p>
<h2>Chapter 7</h2>
<p>This chapter explains ba bla bla</p>
<h2>Chapter 8</h2>
<p>This chapter explains ba bla bla</p>
<h2>Chapter 9</h2>

<p>This chapter explains ba bla bla</p>


<h2>Chapter 10</h2>
<p>This chapter explains ba bla bla</p>
<h2>Chapter 11</h2>
<p>This chapter explains ba bla bla</p>
<h2>Chapter 12</h2>
<p>This chapter explains ba bla bla</p>
<h2>Chapter 13</h2>
<p>This chapter explains ba bla bla</p>
<h2>Chapter 14</h2>
<p>This chapter explains ba bla bla</p>
<h2>Chapter 15</h2>
<p>This chapter explains ba bla bla</p>
<h2>Chapter 16</h2>
<p>This chapter explains ba bla bla</p>
<h2>Chapter 17</h2>
<p>This chapter explains ba bla bla</p>
</body>
</html>
Links Email(Mailto Links)
<!DOCTYPE html>
<html>
<body>
<p>This is an email link:
<a href="mailto:someone@example.com?Subject=Hello%20again">Send Mail</a>
</p>
<p><b>Note:</b> Spaces between words should be replaced by %20 to ensure that the browser will display the
text properly.</p>
</body>
</html>
Mailto Links Examples
<!DOCTYPE html>
<html>
<body>
<p>This is another mailto link:<a href="mailto:som1@no1.com? &subject=Summer&body=You!">
Send mail!</a>
</p>
<p><b>Note:</b> Spaces between words should be replaced by %20 to ensure that the browser will display the
text properly.</p>
</body>
</html>
Aligning Images
<html>
<body>
<h4>Image with default alignment (align="bottom"):</h4>
<p>This is some text. <img src="smiley.gif" alt="Smiley face" width="32" height="32"> This is some text.</p>

<h4>Image with align="middle":</h4>


<p>This is some text. <img src="smiley.gif" alt="Smiley face" align="middle" width="32" height="32"> This is
some text.</p>
<h4>Image with align="top":</h4>
<p>This is some text. <img src="smiley.gif" alt="Smiley face" align="top" width="32" height="32"> This is some
text.</p>
<p><b>Note:</b> The align attribute is deprecated in HTML 4, and is not supported in HTML5. Use CSS
instead.</p>
</body>
</html>
Float of Images
<p><img src="smiley.gif" alt="Smiley face" style="float:left" width="32" height="32"> A paragraph with an
image. The image will float to the left of this text.</p>
<p><img src="smiley.gif" alt="Smiley face" style="float:right" width="32" height="32"> A paragraph with an
image. The image will float to the right of this text.</p>
<p><b>Note:</b> Here we have used the CSS "float" property to align the image; as the align attribute is
deprecated in HTML 4, and is not supported in HTML5.</p>
Image Mapping
<p>Click on the sun or on one of the planets to watch it closer:</p>
<img src="planets.gif" width="145" height="126" alt="Planets" usemap="#planetmap">
<map name="planetmap">
<area shape="rect" coords="0,0,82,126" alt="Sun" href="sun.htm">
<area shape="circle" coords="90,58,3" alt="Mercury" href="mercur.htm">
<area shape="circle" coords="124,58,8" alt="Venus" href="venus.htm">
</map>
Tables with Caption
<table border="1">
<caption>Monthly savings</caption>
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
<tr>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td>February</td>
<td>$50</td>
</tr>
</table>
Cell Spanning
<h4>Cell that spans two columns:</h4>
<table border="1">
<tr>
<th>Name</th>
<th colspan="2">Telephone</th>
</tr>
<tr>
<td>Bill Gates</td>

<td>555 77 854</td>
<td>555 77 855</td>
</tr>
</table>
<h4>Cell that spans two rows:</h4>
<table border="1">
<tr>
<th>First Name:</th>
<td>Bill Gates</td>
</tr>
<tr>
<th rowspan="2">Telephone:</th>
<td>555 77 854</td>
</tr>
<tr>
<td>555 77 855</td>
</tr>
</table>
Tags Inside of Tables and Nesting of Tables
<table border="1">
<tr>
<td>
<p>This is a paragraph</p>
<p>This is another paragraph</p></td>
<td>
This cell contains a table:
<table border="1">
<tr>
<td>A</td>
<td>B</td>
</tr>
<tr>
<td>C</td>
<td>D</td>
</tr>
</table></td>
</tr>
<tr>
<td>This cell contains a list
<ul>
<li>apples</li>
<li>bananas</li>
<li>pineapples</li>
</ul>
</td>
<td>HELLO</td>
</tr>
</table>
Cellpadding
<h4>Without cellpadding:</h4>
<table border="1">
<tr>
<td>First</td>
<td>Row</td>
</tr>
<tr>
<td>Second</td>

<td>Row</td>
</tr>
</table>
<h4>With cellpadding:</h4>
<table border="1" cellpadding="10">
<tr>
<td>First</td>
<td>Row</td>
</tr>
<tr>
<td>Second</td>
<td>Row</td>
</tr>
</table>
Cellspacing
<h4>Without cellspacing:</h4>
<table border="1">
<tr>
<td>First</td>
<td>Row</td>
</tr>
<tr>
<td>Second</td>
<td>Row</td>
</tr>
</table>
<h4>With cellspacing="0":</h4>
<table border="1" cellspacing="0">
<tr>
<td>First</td>
<td>Row</td>
</tr>
<tr>
<td>Second</td>
<td>Row</td>
</tr>
</table>
<h4>With cellspacing="10":</h4>
<table border="1" cellspacing="10">
<tr>
<td>First</td>
<td>Row</td>
</tr>
<tr>
<td>Second</td>
<td>Row</td>
</tr>
</table>
Ordered & Unordered Lists
<h4>An Ordered List:</h4>
<ol>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>

<h4>Letters list:</h4>
<ol type="A">
<li>Apples</li>
<li>Bananas</li>
<li>Lemons</li>
<li>Oranges</li>
</ol>
<h4>Lowercase letters list:</h4>
<ol type="a">
<li>Apples</li>
<li>Bananas</li>
<li>Lemons</li>
<li>Oranges</li>
</ol>
<h4>Roman numbers list:</h4>
<ol type="I">
<li>Apples</li>
<li>Bananas</li>
<li>Lemons</li>
<li>Oranges</li>
</ol>
<h4>Lowercase Roman numbers list:</h4>
<ol type="i">
<li>Apples</li>
<li>Bananas</li>
<li>Lemons</li>
<li>Oranges</li>
<h4>An Unordered List:</h4>
<ul>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
<h4>Circle bullets list:</h4>
<ul style="list-style-type:circle">
<li>Apples</li>
<li>Bananas</li>
<li>Lemons</li>
<li>Oranges</li>
</ul>
<h4>Square bullets list:</h4>
<ul style="list-style-type:square">
<li>Apples</li>
<li>Bananas</li>
<li>Lemons</li>
<li>Oranges</li>
</ul>
Nested Lists
<h4>A nested List:</h4>
<ul>
<li>Coffee</li>
<li>Tea
<ul>
<li>Black tea</li>
<li>Green tea</li>
</ul>

</li>
<li>Milk</li>
</ul>
<h4>A nested List:</h4>
<ul>
<li>Coffee</li>
<li>Tea
<ul>
<li>Black tea</li>
<li>Green tea
<ul>
<li>China</li>
<li>Africa</li>
</ul></li>
</ul></li>
<li>Milk</li>
</ul>
Definition List
<h4>A Definition List:</h4>
<dl>
<dt>Coffee</dt>
<dd>- black hot drink</dd>
<dt>Milk</dt>
<dd>- white cold drink</dd>
</dl>
Meta Tags
<!DOCTYPE html>
<html>
<head>
<meta name="description" content="Free Web tutorials">
<meta name="keywords" content="HTML,CSS,XML,JavaScript">
<meta name="author" content="Hege Refsnes">
<meta charset="UTF-8">
</head>
<body>
<p>All meta information goes in the head section...</p>
</body>
</html>
HTML Forms
Text Fields
<form action="">
First name: <input type="text" name="firstname"><br>
Last name: <input type="text" name="lastname">
</form>
<p><b>Note:</b> The form itself is not visible. Also note that the default width of a text field is 20
characters.</p>
Password Field
<form action="">
Username: <input type="text" name="user"><br>
Password: <input type="password" name="password">
</form>
<p><b>Note:</b> The characters in a password field are masked (shown as asterisks or circles).</p>

Checkboxes
<form action="">
<input type="checkbox" name="vehicle" value="Bike">I have a bike<br>
<input type="checkbox" name="vehicle" value="Car">I have a car
</form>
Radio Buttons
<form action="">
<input type="radio" name="sex" value="male">Male<br>
<input type="radio" name="sex" value="female">Female
</form>
<p><b>Note:</b> When a user clicks on a radio-button, it becomes checked, and all other radio-buttons with
equal name become unchecked.</p>
Dropdown Lists
<form action="">
<select name="cars">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
</select>
</form>
Dropdown List with Preselected Value
<form action="">
<select name="cars">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="fiat" selected>Fiat</option>
<option value="audi">Audi</option>
</select>
</form>
Multiline Text Area
<textarea rows="10" cols="30">The cat was playing in the garden.</textarea>
Buttons
<form action="">
<input type="button" value="Hello world!">
</form>
Draw a Border on a Form Data
<form action="">
<fieldset>
<legend>Personal information:</legend>
Name: <input type="text" size="30"><br>
E-mail: <input type="text" size="30"><br>
Date of birth: <input type="text" size="10">
</fieldset>
</form>
Email Form
<h3>Send e-mail to som1@no1.com:</h3>
<form action="MAILTO:someone@example.com" method="post" enctype="text/plain">
Name:<input type="text" name="name" value="your name"><br>
E-mail:<input type="text" name="mail" value="your email"><br>

<input type="radio" name="sex" value="male">Male<br>


<input type="radio" name="sex" value="female">Female<br>
<input type="checkbox" name="vehicle" value="Bike">I have a bike<br>
<input type="checkbox" name="vehicle" value="Car">I have a car<br>
Comment:<input type="text" name="comment" value="your comment" size="50"><br><br>
<input type="submit" value="Send">
<input type="reset" value="Reset">
</form>
HTML iFrame
<iframe src="demo_iframe.htm"></iframe>
<p>Some older browsers don't support iframes.</p>
<p>If they don't, the iframe will not be visible.</p>
HTML 5 New Elements
Canvas
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #000000;">
Your browser does not support the HTML5 canvas tag.
</canvas>
Scalable Vector Graphics
What is SVG?
SVG stands for Scalable Vector Graphics
SVG is used to define vector-based graphics for the Web
SVG defines the graphics in XML format
SVG graphics do NOT lose any quality if they are zoomed or resized
Every element and every attribute in SVG files can be animated
SVG is a W3C recommendation
SVG Advantages
Advantages of using SVG over other image formats (like JPEG and GIF) are:
SVG images can be created and edited with any text editor
SVG images can be searched, indexed, scripted, and compressed
SVG images are scalable
SVG images can be printed with high quality at any resolution
SVG images are zoomable (and the image can be zoomed without degradation)
Examples
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" height="190">
<polygon points="100,10 40,180 190,60 10,60 160,180"
style="fill:lime;stroke:purple;stroke-width:5;fill-rule:evenodd;">
</svg>
Drag and Drop
Drag and drop is a very common feature. It is when you "grab" an object and drag it to a different location.
In HTML5, drag and drop is part of the standard, and any element can be draggable.
<!DOCTYPE
<html>
<head>

HTML>

<script>
function allowDrop(ev){
ev.preventDefault();
}
function drag(ev){

ev.dataTransfer.setData("Text",ev.target.id);
}
function drop(ev){
ev.preventDefault();
var data=ev.dataTransfer.getData("Text");
ev.target.appendChild(document.getElementById(data));
}
</script>
</head>
<body>
<div
id="div1"
> ><img id="drag1" src="img_logo.gif" draggable="true" width="336"
height="69">
</body>
</html>
Video on the Web
Until now, there has not been a standard for showing a video/movie on a web page.
Today, most videos are shown through a plug-in (like flash). However, different browsers may have different
plug-ins.
HTML5 defines a new element which specifies a standard way to embed a video/movie on a web page: the
<video> element.
<video width="320" height="240" controls>
<source src="movie.mp4" type="video/mp4">
<source src="movie.ogg" type="video/ogg">Your browser does not support the video tag.
</video>
Browser Support (Audio/Video)
Browser
Internet Explorer 9+
Chrome 6+
Firefox 3.6+
Safari 5+
Opera 10.6+
Mime types for Video
Format
MP4
WebM
Ogg
Video Tags
Tag
<video>
<source>
<track>

MP4
YES
YES
NO
YES
NO

WebM
NO
YES
YES
NO
YES

Ogg
NO
YES
YES
NO
YES

MIME-type
video/mp4
video/webm
video/ogg

Description
Defines a video or movie
Defines multiple media resources for media elements, such as <video> and <audio>
Defines text tracks in media players

Audio on the Web


Until now, there has not been a standard for playing audio files on a web page.

Today, most audio files are played through a plug-in (like flash). However, different browsers may have different
plug-ins.
HTML5 defines a new element which specifies a standard way to embed an audio file on a web page: the <audio>
element.
<audio controls>
<source src="horse.ogg" type="audio/ogg">
<source src="horse.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
Mime types for Audio
Format
MP3
Ogg
Wav
Audio Tags
Tag
<audio>
<source>

MIME-type
audio/mpeg
audio/ogg
audio/wav

Description
Defines sound content
Defines multiple media resources for media elements, such as <video> and <audio>

HTML5 New Input Types


HTML5 has several new input types for forms. These new features allow better input control and validation. This
chapter covers the new input types:
color
range
date
search
datetime
tel
datetime-local
time
email
url
month
week
number
Note: Not all major browsers support all the new input types. However, you can already start using them; if they
are not supported, they will behave as regular text fields.
<form action="demo_form.asp">
Select your favorite color: <input type="color" name="favcolor"><br>
Birthday: <input type="date" name="bday">
Birthday (date and time): <input type="datetime" name="bdaytime">
Birthday (date and time): <input type="datetime-local" name="bdaytime">
E-mail: <input type="email" name="email">
Birthday (month and year): <input type="month" name="bdaymonth">
Quantity (between 1 and 5): <input type="number" name="quantity" min="1" max="5">
<input type="range" name="points" min="1" max="10">
Search Google: <input type="search" name="googlesearch">
Telephone: <input type="tel" name="usrtel">
Select a time: <input type="time" name="usr_time">
Add your homepage: <input type="url" name="homepage">
Select a week: <input type="week" name="week_year">
<input type="submit">
</form>

Use the following attributes to specify restrictions (for Number & Range):
max - specifies the maximum value allowed
min - specifies the minimum value allowed
step - specifies the legal number intervals
value - Specifies the default value
HTML5 New Form Elements
HTML5 has the following new form elements:
<datalist>
<keygen>
<output>
Note: Not all major browsers support all the new form elements. However, you can already start using them; If
they are not supported, they will behave as regular text fields.
<input list="browsers">
<datalist id="browsers">
<option value="Internet Explorer">
<option value="Firefox">
<option value="Chrome">
<option value="Opera">
<option value="Safari">
</datalist>
Tag
<datalist>
<keygen>
<output>

Description
Specifies a list of pre-defined options for an <input> element
Specifies a key-pair generator field in a form
Represents the result of a calculation

HTML5 Semantic Elements


Semantic = Meaning.
Semantic elements = Elements with meaning.
What are Semantic Elements?
A semantic element clearly describes its meaning to both the browser and the developer. Examples of nonsemantic elements: <div> and <span> - Tells nothing about its content. Examples of semantic elements: <form>,
<table>, and <img> - Clearly defines its content.
New Semantic Elements in HTML5
Many of existing web sites today contains HTML code like this: <div id="nav">, <div
class="header">, or <div id="footer">, to indicate navigation links, header, and footer.
HTML5 offers new semantic elements to clearly define different parts of a web page:
<header>
<aside>
<nav>
<figcaption>
<section>
<figure>
<article>
<footer>
Tag
<article>
<aside>
<figcaption>
<figure>
<footer>
<header>
<hgroup>

Description
Defines an article
Defines content aside from the page content
Defines a caption for a <figure> element
Specifies self-contained content, like illustrations, diagrams, photos, code listings etc.
Defines a footer for a document or section
Specifies a header for a document or section
Groups heading (<h1> to <h6>) elements

<mark>
<nav>
<section>
<time>

Defines marked/highlighted text


Defines navigation links
Defines a section in a document
Defines a date/time

HTML5 <section> Element


The <section> element defines a section in a document. According to W3C's HTML5 documentation: "A section
is a thematic grouping of content, typically with a heading."
<section>
<h1>WWF</h1>
<p>The World Wide Fund for Nature (WWF) is....</p>
</section>
HTML5 <article> Element
The <article> element specifies independent, self-contained content. An article should make sense on its own
and it should be possible to distribute it independently from the rest of the web site. Examples of where an
<article> element can be used:
Forum post
Blog post
News story
Comment
<article>
<h1>Internet Explorer 9</h1>
<p>Windows Internet Explorer 9 (abbreviated as IE9) was released to the public on March 14, 2011 at
21:00 PDT.....</p>
</article>
HTML5 <nav> Element
The <nav> element defines a set of navigation links. The <nav> element is intended for large blocks of navigation
links. However, not all links in a document should be inside a <nav> element!
<nav>
<a href="/html/">HTML</a> |
<a href="/css/">CSS</a> |
<a href="/js/">JavaScript</a> |
<a href="/jquery/">jQuery</a>
</nav>
HTML5 <aside> Element
The <aside> element defines some content aside from the content it is placed in (like a sidebar). The aside
content should be related to the surrounding content.
<p>My family and I visited The Epcot center this summer.</p>
<aside>
<h4>Epcot Center</h4>
<p>The Epcot Center is a theme
</aside>

park

in

Disney

World,

Florida.</p>

HTML5 <header> Element


The <header> element specifies a header for a document or section. The <header> element should be used as a
container for introductory content. You can have several <header> elements in one document. The following
example defines a header for an article:
<article>
<header>
<h1>Internet Explorer 9</h1>

<p><time pubdate datetime="2011-03-15"></time></p>


</header>
<p>Windows Internet Explorer 9 (abbreviated as IE9) was released to the public on March 14, 2011
at 21:00 PDT.....</p>
</article>
HTML5 <footer> Element
The <footer> element specifies a footer for a document or section. A <footer> element should contain
information about its containing element. A footer typically contains the author of the document, copyright
information, links to terms of use, contact information, etc. You can have several <footer> elements in one
document.
<footer>
<p>Posted by: Hege Refsnes</p>
<p><time pubdate datetime="2012-03-01"></time></p>
</footer>
HTML5 <figure> and <figcaption> Elements
The <figure> tag specifies self-contained content, like illustrations, diagrams, photos, code listings, etc. While
the content of the <figure> element is related to the main flow, its position is independent of the main flow, and
if removed it should not affect the flow of the document. The <figcaption> tag defines a caption for a <figure>
element. The <figcaption> element can be placed as the first or last child of the <figure> element.
<figure>
<img src="img_pulpit.jpg" alt="The Pulpit Rock" width="304" height="228">
<figcaption>Fig1. - The Pulpit Pock, Norway.</figcaption>
</figure>
Can We Start Using These Semantic Elements?
The elements explained above are all block elements (except <figcaption>). To get these elements to work
properly in all (older) major browsers, set the display property to block in your style sheet (this causes older
browsers to render these elements correctly):
header, section, footer, aside, nav, article, figure {
display: block;
}
What is HTML5 Web Storage?
With HTML5, web pages can store data locally within the user's browser.
Earlier, this was done with cookies. However, Web Storage is more secure and faster. The data is not included
with every server request, but used ONLY when asked for. It is also possible to store large amounts of data,
without affecting the website's performance.
The data is stored in key/value pairs, and a web page can only access data stored by itself.
Web storage is supported in Internet Explorer 8+, Firefox, Opera, Chrome, and Safari.
There are two new objects for storing data on the client:
localStorage - stores data with no expiration date
sessionStorage - stores data for one session
The localStorage Object
The localStorage object stores the data with no expiration date. The data will not be deleted when the browser
is closed, and will be available the next day, week, or year.
<!DOCTYPE html>
<html>

<head>
<script>
function clickCounter(){
if(typeof(Storage)!=="undefined") {
if (localStorage.clickcount) {
localStorage.clickcount=Number(localStorage.clickcount)+1;
}
else {
localStorage.clickcount=1;
}
document.getElementById("result").innerHTML="You have clicked the button " +
localStorage.clickcount + " time(s).";
}
else {
document.getElementById("result").innerHTML="Sorry, your browser does not support web
storage...";
}
}
</script>
</head>
<body>
<p><button type="button">Click me!</button></p>
<div id="result"></div>
<p>Click the button to see the counter increase.</p>
<p>Close the browser tab (or window), and try again, and the counter will continue to count
(is not reset).</p>
</body>
</html>
The sessionStorage Object
The sessionStorage object is equal to the localStorage object, except that it stores the data for only one session.
The data is deleted when the user closes the browser window. The following example counts the number of
times a user has clicked a button, in the current session:
<html>
<head>
<script>
function clickCounter(){
if(typeof(Storage)!=="undefined"){
if (sessionStorage.clickcount){
sessionStorage.clickcount=Number(sessionStorage.clickcount)+1;
}
else {
sessionStorage.clickcount=1;
}
document.getElementById("result").innerHTML="You have clicked the button " +
sessionStorage.clickcount + " time(s) in this session.";
}
else {
document.getElementById("result").innerHTML="Sorry, your browser does not support
web storage...";
}
}
</script>
</head>
<body>
<p><button type="button">Click me! </button></p>

<div id="result"></div>
<p>Click the button to see the counter increase.</p>
<p>Close the browser tab (or window), and try again,
and the counter is reset.</p>
</body>
</html>
What is Application Cache?
HTML5 introduces application cache, which means that a web application is cached, and accessible without an
internet connection.
Application cache gives an application three advantages:
1. Offline browsing - users can use the application when they're offline
2. Speed - cached resources load faster
3. Reduced server load - the browser will only download updated/changed resources from the server
<!DOCTYPE html>
<html manifest="demo_html.appcache">
<body>
<script src="demo_time.js">
</script>
<p id="timePara">
<button Date and Time</button></p>
<p><img src="img_logo.gif" width="336" height="69"></p>
<p>Try opening <a href="tryhtml5_html_manifest.htm" target="_blank">this page</a>, then go
offline, and reload the page. The script and the image should still work.</p>
</body>
</html>
Playing a YouTube Video in HTML
If you want to play a video in a web page, you can upload the video to YouTube and insert the proper HTML code
to display the video:
<!DOCTYPE html>
<html>
<body>
<iframe width="420" height="345" src="http://www.youtube.com/embed/XGSy3_Czz8k">
</iframe>
<embed
width="420" height="345"
src="http://www.youtube.com/v/XGSy3_Czz8k"
type="application/x-shockwave-flash">
</embed>
</body>
</html>

What is CSS?
CSS is an acronym for Cascading Style Sheets.
CSS is a style language that defines layout of HTML documents. For example, CSS covers fonts, colors, margins,
lines, height, width, background images, advanced positions and many other things. Just wait and see!
HTML can be (mis-)used to add layout to websites. But CSS offers more options and is more accurate and
sophisticated. CSS is supported by all browsers today.
What is the difference between CSS and HTML?
HTML is used to structure content. CSS is used for formatting structured content.
Okay, it sounds a bit technical and confusing. But please continue reading. It will all make sense to you soon.
Back in the good old days when Madonna was a virgin and a guy called Tim Berners Lee invented the World
Wide Web, the language HTML was only used to add structure to text. An author could mark his text by stating
"this is a headline" or "this is a paragraph" using HTML tags such as <h1> and <p>.
As the Web gained popularity, designers started looking for possibilities to add layout to online documents. To
meet this demand, the browser producers (at that time Netscape and Microsoft) invented new HTML tags such
as for example <font> which differed from the original HTML tags by defining layout - and not structure.
This also led to a situation where original structure tags such as <table> were increasingly being misused to
layout pages instead of adding structure to text. Many new layout tags such as <blink> were only supported by
one type of browser. "You need browser X to view this page" became a common disclaimer on web sites.
CSS was invented to remedy this situation by providing web designers with sophisticated layout opportunities
supported by all browsers. At the same time, separation of the presentation style of documents from the content
of documents, makes site maintenance a lot easier.
Which benefits will CSS give me?
CSS was a revolution in the world of web design. The concrete benefits of CSS include:
Control layout of many documents from one single style sheet;
More precise control of layout;
Apply different layout to different media-types (screen, print, etc.);
Numerous advanced and sophisticated techniques.
How does CSS work?
In this lesson you will learn how to make your first style sheet. You will get to know about the basic CSS model
and which codes are necessary to use CSS in an HTML document.
Many of the properties used in Cascading Style Sheets (CSS) are similar to those of HTML. Thus, if you are used
to use HTML for layout, you will most likely recognize many of the codes. Let us look at a concrete example.
The basic CSS syntax
Using HTML we could have done it like this:
<body bgcolor="#FF0000">
With CSS the same result can be achieved like this:
body {background-color: #FF0000;}
As you will note, the codes are more or less identical for HTML and CSS. The above example also shows you the
fundamental CSS model:

Applying CSS to an HTML document


There are three ways you can apply CSS to an HTML document. These methods are all outlined below. We
recommend that you focus on the third method i.e. external.
Method 1: In-line (the attribute style)
One way to apply CSS to HTML is by using the HTML attribute style. Building on the above example with the red
background color, it can be applied like this:
<html>
<head>
<title>Example</title>
</head>
<body style="background-color: #FF0000;">
<p>This is a red page</p>
</body>
</html>
Method 2: Internal (the tag style)
Another way is to include the CSS codes using the HTML tag <style>. For example like this:
<html>
<head>
<title>Example</title>
<style type="text/css">
body {background-color: #FF0000;}
</style>
</head>
<body>
<p>This is a red page</p>
</body>
</html>
Method 3: External (link to a style sheet)
The recommended method is to link to a so-called external style sheet. Throughout this tutorial we will use this
method in all our examples.
An external style sheet is simply a text file with the extension .css. Like any other file, you can place the style
sheet on your web server or hard disk.
For example, let's say that your style sheet is named style.css and is located in a folder named style. The situation
can be illustrated like this:

The trick is to create a link from the HTML document (default.htm) to the style sheet (style.css). Such link can be
created with one line of HTML code:
<link rel="stylesheet" type="text/css" href="style/style.css" />

<!DOCTYPE html>
<html>
<head>
<style>
body{
background-color:#d0e4fe;
}
h1{
color:orange;
text-align:center;
}
p{
font-family:"Times New Roman";
font-size:20px;
}
</style>
</head>
<body>
<h1>CSS example!</h1>
<p>This is a paragraph.</p>
</body>
</html>

CSS Selectors
In CSS, selectors are patterns used to select the element(s) you want to style.
The "CSS" column indicates in which CSS version the property is defined (CSS1, CSS2, or CSS3).
Selector

Example

Example description

CSS

.class

.intro

Selects all elements with class="intro"

#id

#firstname

Selects the element with id="firstname"

Selects all elements

element

Selects all <p> elements

element,element

div,p

Selects all <div> elements and all <p> elements

element element

div p

Selects all <p> elements inside <div> elements

element>element

div>p

Selects all <p> elements where the parent is a <div> element

element+element

div+p

Selects all <p> elements that are placed immediately after <div> elements

[attribute]

[target]

Selects all elements with a target attribute

[attribute=value]

[target=_blank]

Selects all elements with target="_blank"

[attribute~=value]

[title~=flower]

Selects all elements with a title attribute containing the word "flower"

[attribute|=value]

[lang|=en]

Selects all elements with a lang attribute value starting with "en"

:link

a:link

Selects all unvisited links

:visited

a:visited

Selects all visited links

:active

a:active

Selects the active link

:hover

a:hover

Selects links on mouse over

:focus

input:focus

Selects the input element which has focus

:first-letter

p:first-letter

Selects the first letter of every <p> element

:first-line

p:first-line

Selects the first line of every <p> element

:first-child

p:first-child

Selects every <p> element that is the first child of its parent

:before

p:before

Insert content before the content of every <p> element

:after

p:after

Insert content after every <p> element

:lang(language)

p:lang(it)

Selects every <p> element with a lang attribute value starting with "it"

element1~element2

p~ul

Selects every <ul> element that are preceded by a <p> element

[attribute^=value]

a[src^="https"]

Selects every <a> element whose src attribute value begins with "https"

[attribute$=value]

a[src$=".pdf"]

Selects every <a> element whose src attribute value ends with ".pdf"

[attribute*=value]

a[src*="w3schools"]

Selects every <a> element whose src attribute value contains the
substring "w3schools"

:first-of-type

p:first-of-type

Selects every <p> element that is the first <p> element of its parent

:last-of-type

p:last-of-type

Selects every <p> element that is the last <p> element of its parent

:only-of-type

p:only-of-type

Selects every <p> element that is the only <p> element of its parent

:only-child

p:only-child

Selects every <p> element that is the only child of its parent

:nth-child(n)

p:nth-child(2)

Selects every <p> element that is the second child of its parent

:nth-last-child(n)

p:nth-last-child(2)

Selects every <p> element that is the second child of its parent, counting
from the last child

:nth-of-type(n)

p:nth-of-type(2)

Selects every <p> element that is the second <p> element of its parent

:nth-last-of-type(n)

p:nth-last-of-type(2)

Selects every <p> element that is the second <p> element of its parent,
counting from the last child

:last-child

p:last-child

Selects every <p> element that is the last child of its parent

:root

:root

Selects the documents root element

:empty

p:empty

Selects every <p> element that has no children (including text nodes)

:target

#news:target

Selects the current active #news element (clicked on a URL containing that
anchor name)

:enabled

input:enabled

Selects every enabled <input> element

:disabled

input:disabled

Selects every disabled <input> element

:checked

input:checked

Selects every checked <input> element

:not(selector)

:not(p)

Selects every element that is not a <p> element

::selection

::selection

Selects the portion of an element that is selected by a user

CSS Units
Measurement Values
Unit

Description

percentage

in

inch

cm

centimeter

mm

millimeter

em

1em is equal to the current font size. 2em means 2 times the size of the current font. E.g., if an element is displayed with a
font of 12 pt, then '2em' is 24 pt. The 'em' is a very useful unit in CSS, since it can adapt automatically to the font that the
reader uses

ex

one ex is the x-height of a font (x-height is usually about half the font-size)

pt

point (1 pt is the same as 1/72 inch)

pc

pica (1 pc is the same as 12 points)

px

pixels (a dot on the computer screen)

Color Values
CSS colors are defined using a hexadecimal (hex) notation for the combination of Red, Green, and Blue color values (RGB). The lowest value
that can be given to one of the light sources is 0 (hex 00). The highest value is 255 (hex FF).
Hex values are written as 3 double digit numbers, starting with a # sign.

16 Million Different Colors


The combination of Red, Green and Blue values from 0 to 255 gives a total of more than 16 million different colors to play with (256 x 256 x
256).
Most modern monitors are capable of displaying at least 16384 different colors.
If you look at the color table below, you will see the result of varying the red light from 0 to 255, while keeping the green and blue light at
zero.
To see a full list of color mixes when the red light varies from 0 to 255, click on one of the hex or rgb values below.

Red Light

HEX

RGB

#000000

rgb(0,0,0)

#080000

rgb(8,0,0)

#100000

rgb(16,0,0)

#180000

rgb(24,0,0)

#200000

rgb(32,0,0)

#280000

rgb(40,0,0)

#300000

rgb(48,0,0)

#380000

rgb(56,0,0)

#400000

rgb(64,0,0)

#480000

rgb(72,0,0)

#500000

rgb(80,0,0)

#580000

rgb(88,0,0)

#600000

rgb(96,0,0)

#680000

rgb(104,0,0)

#700000

rgb(112,0,0)

#780000

rgb(120,0,0)

#800000

rgb(128,0,0)

#880000

rgb(136,0,0)

#900000

rgb(144,0,0)

#980000

rgb(152,0,0)

#A00000

rgb(160,0,0)

#A80000

rgb(168,0,0)

#B00000

rgb(176,0,0)

#B80000

rgb(184,0,0)

#C00000

rgb(192,0,0)

#C80000

rgb(200,0,0)

#D00000

rgb(208,0,0)

#D80000

rgb(216,0,0)

#E00000

rgb(224,0,0)

#E80000

rgb(232,0,0)

#F00000

rgb(240,0,0)

#F80000

rgb(248,0,0)

#FF0000

rgb(255,0,0)

Web Safe Colors?


Some years ago, when computers supported max 256 different colors, a list of 216 "Web Safe Colors" was
suggested as a Web standard, reserving 40 fixed system colors.
This is not important now, since most computers can display millions of different colors, but the choice is left to
you.
The 216 cross-browser color palette was created to ensure that all computers would display the colors correctly
when running a 256 color palette:
Visit: http://www.w3schools.com/cssref/css_colors.asp
CSS3 Browser support
CSS3 is not yet a W3C standard, but the major browsers support many of the new properties.
The table below lists the new CSS3 properties and their browser support:
Property
IE
alignment-adjust
alignment-baseline

Firefox

Chrome

Safari

Opera

@keyframes

10

16

12.1

animation

10

16

12.1

animation-name

10

16

12.1

animation-duration

10

16

12.1

animation-timing-function

10

16

12.1

animation-delay

10

16

12.1

animation-iteration-count

10

16

12.1

animation-direction

10

16

12.1

animation-play-state

10

16

12.1

appearance
backface-visibility

10

background-clip

10.5

background-origin

10.5

background-size

10.5

border-bottom-left-radius

10.5

border-bottom-right-radius

10.5

15

16

11

baseline-shift
bookmark-label
bookmark-level
bookmark-target

border-image
border-image-outset
border-image-repeat
border-image-slice
border-image-source
border-image-width
border-radius

10.5

border-top-left-radius

10.5

border-top-right-radius

10.5

box-decoration-break
box-align
box-direction
12.1

box-flex
box-flex-group
box-lines
box-ordinal-group
box-orient
box-pack
box-shadow

box-sizing

10

5.1

10.5

10

5.1

9.5

color-profile
column-fill
column-gap

10

11.1

column-rule

10

11.1

column-rule-color

10

11.1

column-rule-style

10

11.1

column-rule-width

10

11.1

column-span

10

11.1

column-width

10

11.1

columns

10

11.1

column-count

10

11.1

crop
dominant-baseline
drop-initial-after-adjust
drop-initial-after-align

drop-initial-before-adjust
drop-initial-before-align
drop-initial-size
drop-initial-value
fit
fit-position
float-offset
@font-face

3.6

10

font-size-adjust
font-stretch
grid-columns
grid-rows
hanging-punctuation
hyphenate-after
hyphenate-before
hyphenate-characters
hyphenate-lines
hyphenate-resource
hyphens
icon
image-orientation
image-resolution
inline-box-align
line-stacking
line-stacking-ruby
line-stacking-shift
line-stacking-strategy
mark
mark-after
mark-before
marks
marquee-direction
marquee-play-count
marquee-speed
marquee-style
move-to
nav-down

11.5

nav-index

11.5

nav-left

11.5

nav-right

11.5
11.5

nav-up
opacity

3.1

overflow-style
overflow-x

overflow-y

page
page-policy
5

perspective
perspective-origin
punctuation-trim
rendering-intent
resize
rest
rest-after

9
11

outline-offset

rest-before
rotation
rotation-point
ruby-align
ruby-overhang
ruby-position
ruby-span
size
string-set
target
target-name
target-new
target-position
text-align-last
text-emphasis
text-height
5

text-justify
text-outline
text-overflow

3.1

11

text-shadow

10

3.5

9.5

transform

10

16

transform-origin

10

16

text-wrap
12.1
12.1
5

transform-style
transition

10

16

26

12.1

transition-property

10

16

26

12.1

transition-duration

10

16

26

12.1

transition-timing-function

10

16

26

12.1

transition-delay

10

16

26

word-break

5.5

15

word-wrap

3.5

3.1

12.1

10.5

Compiling [font]
Using the font short hand property it is possible to cover all the different font properties in one single property.
For example, imagine these four lines of code used to describe font-properties for <p>:
p{
font-style: italic;
font-weight: bold;
font-size: 30px;
font-family: arial, sans-serif;
}

Using the short hand property, the code can be simplified:


p{
font: italic bold 30px arial, sans-serif;
}

The order of values for font is:


font-style | font-variant | font-weight | font-size | font-family

Font family [font-family]


The property font-family is used to set a prioritized list of fonts to be used to display a given element or web
page. If the first font on the list is not installed on the computer used to access the site, the next font on the list
will be tried until a suitable font is found.
There are two types of names used to categorize fonts: family-names and generic families. The two terms are
explained below.
Family-name
Examples of a family-name (often known as "font") can e.g. be "Arial", "Times New Roman" or
"Tahoma".
Generic family
Generic families can best be described as groups of family-names with uniformed appearances. An
example is sans-serif, which is a collection of fonts without "feet".
Font style [font-style]
The property font-style defines the chosen font either in normal, italic or oblique. In the example below, all
headlines marked with <h2> will be shown in italics.
h1 {font-family: arial, verdana, sans-serif;}
h2 {font-family: "Times New Roman", serif; font-style: italic;}
Font variant [font-variant]
The property font-variant is used to choose between normal or small-caps variants of a font. A small-caps font
is a font that uses smaller sized capitalized letters (upper case) instead of lower case letters. Confused? Take a
look at these examples:
h1 {font-variant: small-caps;}
h2 {font-variant: normal;}

Font weight [font-weight]


The property font-weight describes how bold or "heavy" a font should be presented. A font can either
be normal or bold. Some browsers even support the use of numbers between 100-900 (in hundreds) to describe
the weight of a font.
p {font-family: arial, verdana, sans-serif;}
td {font-family: arial, verdana, sans-serif; font-weight: bold;}
Font size [font-size]
The size of a font is set by the property font-size.
There are many different units (e.g. pixels and percentages) to choose from to describe font sizes. In this tutorial
we will focus on the most common and appropriate units. Examples include:
h1 {font-size: 30px;}
h2 {font-size: 12pt;}
h3 {font-size: 120%;}
p {font-size: 1em;}
Text
Formatting and adding style to text is a key issue for any web designer. In this lesson you will be introduced to
the amazing opportunities CSS gives you to add layout to text. The following properties will be described:
text-indent
text-align
text-decoration
letter-spacing
text-transform

Text indention [text-indent]


The property text-indent allows you to add an elegant touch to text paragraphs by applying an indent to the first
line of the paragraph. In the example below a 30px is applied to all text paragraphs marked with <p>:
p{
text-indent: 30px;
}
Text alignment [text-align]
The CSS property text-align corresponds to the attribute align used in old versions of HTML. Text can either be
aligned to the left, to the right orcentred. In addition to this, the value justify will stretch each line so that both
the right and left margins are straight. You know this layout from for example newspapers and magazines.
In the example below the text in table headings <th> is aligned to the right while the table data <td> are centred.
In addition, normal text paragraphs are justified:
th {
text-align: right;
}
td {
text-align: center;
}
p{
text-align: justify;
}
Text decoration [text-decoration]
The property text-decoration makes it is possible to add different "decorations" or "effects" to text.
For example, you can underline the text, have a line through or above the text, etc. In the following
example, <h1> are underlined headlines, <h2> are headlines with a line above the text and <h3> are headlines
with a line though the text.
h1 {
text-decoration: underline;
}
h2 {
text-decoration: overline;
}
h3 {
text-decoration: line-through;
}
Letter space [letter-spacing]
The spacing between text characters can be specified using the property letter-spacing. The value of the property
is simply the desired width. For example, if you want a spacing of 3px between the letters in a text
paragraph <p> and 6px between letters in headlines <h1> the code below could be used.
h1 {
letter-spacing: 6px;
}
p{
letter-spacing: 3px;
}

Text transformation [text-transform]


The text-transform property controls the capitalization of a text. You can choose to capitalize,
use uppercase or lowercase regardless of how the original text is looks in the HTML code.
An example could be the word "headline" which can be presented to the user as "HEADLINE" or "Headline".
There are four possible values for text-transform:
capitalize
Capitalizes the first letter of each word. For example: "john doe" will be "John Doe".
uppercase
Converts all letters to uppercase. For example: "john doe" will be "JOHN DOE".
lowercase
Converts all letters to lowercase. For example: "JOHN DOE" will be "john doe".
none
No transformations - the text is presented as it appears in the HTML code.
As an example, we will use a list of names. The names are all marked with <li> (list-item). Let's say that we want
names to be capitalized and headlines to be presented in uppercase letters.
Try to take a look at the HTML code for this example and you will see that the text actually is in lowercase.
h1 {
text-transform: uppercase;
}
li {
text-transform: capitalize;
}
Links
You can apply what you already learned in the previous lessons to links (i.e. change colors, fonts, underline, etc).
The new thing is that CSS allows you to define these properties differently depending on whether the link is
unvisited, visited, active, or whether the cursor is on the link. This makes it possible to add fancy and useful
effects to your website. To control these effects you use so-called pseudo-classes.
What is a pseudo-class?
A pseudo-class allows you to take into account different conditions or events when defining a property for an
HTML tag.
Let's look at an example. As you know, links are specified in HTML with <a> tags. We can therefore use a as a
selector in CSS:
a{
color: blue;
}
A link can have different states. For example, it can be visited or not visited. You can use pseudo-classes to assign
different styles to visited and unvisited links.
a:link {
color: blue;
}
a:visited {
color: red;
}
Use a:link and a:visited for unvisited and visited links respectively. Links that are active have the pseudoclass a:active and a:hover is when the cursor is on the link.
We will now go through each of the four pseudo-classes with examples and further explanation.

Pseudo-class: link
The pseudo-class :link is used for links leading to pages that the user has not visited.
In the code example below, unvisited links will be light blue.
a:link {
color: #6699CC;
}
Pseudo-class: visited
The pseudo-class :visited is used for links leading to pages that the user has visited. For example, the code below
would make all visited links dark purple:
a:visited {
color: #660099;
}
Pseudo-class: active
The pseudo-class :active is used for links that are active.
This example gives active links a yellow background color:
a:active {
background-color: #FFFF00;
}
Pseudo-class: hover
The pseudo-class :hover is used when the mouse pointer hovers over a link.
This can be used to create interesting effects. For example, if we want our links to be orange and be italicized
when the cursor is pointed at them, our CSS should look like this:
a:hover {
color: orange;
font-style: italic;
}
Examples:
a:hover {
letter-spacing: 10px;
font-weight:bold;
color:red;
}
or
a:hover {
text-transform: uppercase;
font-weight:bold;
color:blue;
background-color:yellow;
}
------a{
text-decoration:none;
}
------a:link {
color: blue;
text-decoration:none;
}
a:visited {
color: purple;
text-decoration:none;
}

a:active {
background-color: yellow;
text-decoration:none;
}
a:hover {
color:red;
text-decoration:none;
}
The box model
The box model in CSS describes the boxes which are being generated for HTML-elements. The box model also
contains detailed options regarding adjusting margin, border, padding and content for each element. The
diagram below shows how the box model is constructed:
The box model in CSS

Set the margin in an element


An element has four sides: right, left, top and bottom.
The margin is the distance from each side to the
neighboring element (or the borders of the document).
As the first example, we will look at how you define
margins for the document itself i.e. for the
element <body>. The illustration below shows how we
want the margins in our pages to be.
The CSS code for this would look as follow:
body {
margin-top: 100px;
margin-right: 40px;
margin-bottom: 10px;
margin-left: 70px;
}
Or you could choose a more elegant compilation:
body {
margin: 100px 40px 10px 70px;
}

You can set the margins in the same way on almost every element. For example, we can choose to define margins
for all of our text paragraphs marked with <p>:
body {
margin: 100px 40px 10px 70px;
}
p{
margin: 5px 50px 5px 50px;
}
By defining padding for the headlines, you change how much filling there will be around the text in each
headline:
h1 {
background: yellow;
padding: 20px 20px 20px 80px;
}
h2 {
background: orange;
padding-left:120px;
}
Borders
Borders can be used for many things, for example as a decorative element or to underline a separation of two
things. CSS gives you endless options when using borders in your pages.
border-width
border-color
border-style
border
The width of borders [border-width]
The width of borders is defined by the property border-width, which can obtain
the values thin, medium, and thick, or a numeric value, indicated in pixels. The
figure below illustrates the system:

The color of borders [border-color]


The property border-color defines which color the border has. The values are the
normal color-values for example "#123456", "rgb(123,123,123)" or "yellow" .
Types of borders [border-style]
There are different types of borders to choose from. Below are shown 8 different
types of borders as Internet Explorer 5.5 interprets them. All examples are shown
with the color "gold" and the thickness "thick" but can naturally be shown in other
colors and thicknesses.
The values none or hidden can be used if you do not want any border.

Examples of defining borders


The three properties described above can be put together by each element and thereby produce different
borders. To illustrate this, we will take a look at a document where we define different borders
for <h1>, <h2>, <ul> and <p>. The result may not be that pretty but it illustrates some of the many possibilities:
h1 {
border-width: thick;
border-style: dotted;
border-color: gold;
}
h2 {
border-width: 20px;
border-style: outset;
border-color: red;
}
p{
border-width: 1px;
border-style: dashed;
border-color: blue;
}
ul {
border-width: thin;
border-style: solid;
border-color: orange;
}
Height and width
Up until now, we have not cared much about the dimensions of the elements we have worked with. In this
lesson, we will take a look at how you easily can define the height and width of an element.
Setting the width [width]
With the width-property, you can define a certain width of an element.
The simple example below provides us with a box wherein text can be typed:
div.box {
width: 200px;
border: 1px solid black;
background: orange;
}
Setting the height [height]
In the example above notice how the height of the box is set by the content of the box. You can affect the height
of an element with the property height. As an example let us try to make the box in the example 500px high:
Try with this:
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<title>Example | CSS Tutorial | HTML.net</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="styles.css" type="text/css" media="all" />
</head>
<body>
<h1>200px width and 500px height &lt;div&gt; with text</h1>
<div class="box">Contents goes here </div>
</body>
</html>
And the styles.css will be:
div.box {
height: 500px;
width: 200px;

border: 1px solid black;


background: orange;
}
Floating elements (floats)
An element can be floated to the right or to left
by using the property float. That is to say that
the box with its contents either floats to the
right or to the left in a document (or the
containing box). The following figure illustrates
the principle:

If we for example would like to have a text


wrapping around a picture, the result would be like this:

The HTML code for the example above, look as follows:


<div id="picture">
<img src="bill.jpg" alt="Bill Gates">
</div>
<p>Contents goes here.</p>
To get the picture floating to the left and the text to surround it, you only have to define the width of the box
which surrounds the picture and thereafter set the property float to left:
#picture {
float:left;
width: 100px;
}
Now try this: columns
Floats can also be used for columns in a document. To create the columns, you simply have to structure the
desired columns in the HTML-code with<div> as follows:
<div id="column1">
<p>Haec disserens qua de re agatur
et in quo causa consistat non videt...</p>
</div>
<div id="column2">
<p>causas naturales et antecedentes,

idciro etiam nostrarum voluntatum...</p>


</div>
<div id="column3">
<p>nam nihil esset in nostra
potestate si res ita se haberet...</p>
</div>
Now the desired width of the columns is set to e.g. 33%, and then you simply float each column to the left by
defining the property float:
#column1 {
float:left;
width: 33%;
}
#column2 {
float:left;
width: 33%;
}
#column3 {
float:left;
width: 33%;
}
The property clear
The clear property is used to control how the subsequent elements of floated elements in a document shall
behave.
By default, the subsequent elements are moved up to fill the available space which will be freed when a box is
floated to a side. Look at the example above wherein the text is automatically moved up beside the picture of
Bill Gates.
The property clear can assume the values left, right, both or none. The principle is, if clear, for example, is set
to both for a box, the top margin border of this box will always be under the lower margin border for possible
floating boxes coming from above.
<div id="picture">
<img src="bill.jpg" alt="Bill Gates">
</div>
<h1>Bill Gates</h1>
<p class="floatstop">causas naturales et antecedentes,
idciro etiam nostrarum voluntatum...</p>
To avoid the text from floating up next to the picture, we can add the following to our CSS:
#picture {
float:left;
width: 100px;
}
.floatstop {
clear:both;
}

Positioning of elements
With CSS positioning, you can place an element
exactly where you want it on your page.
Together with floats, positioning gives you
many possibilities to create an advanced and
precise layout.
The following will be discussed in this lesson:
The principle behind CSS positioning
Absolute positioning
Relative positioning
The principle behind CSS positioning
Imagine a browser window as a system of
coordinates:
The principle behind CSS positioning is that you can position any box anywhere in the system of coordinates.
Let's say we want to position a headline. By using the box model the headline will appear as follows:

If we want this headline positioned 100px from the top of the document and 200px from the left of the
document, we could type the following in our CSS:
h1 {
position:absolute;
top: 100px;
left: 200px;
}
The result will be as follows:

As you can see, positioning with CSS is a very precise technique to place elements. It is much easier than trying
to use tables, transparent images or anything else.
Absolute positioning
An element which is positioned absolute does not obtain any space in the document. This means that it does
not leave an empty space after being positioned.

To position an element absolutely, the position property is set as absolute. You can subsequently use the
properties left, right, top, and bottom to place the box.
As an example of absolute positioning, we choose to place 4 boxes in each corner of the document:
#box1 {
position:absolute;
top: 50px;
left: 50px;
}
#box2 {
position:absolute;
top: 50px;
right: 50px;
}
#box3 {
position:absolute;
bottom: 50px;
right: 50px;
}
#box4 {
position:absolute;
bottom: 50px;
left: 50px;
}
Relative positioning
To position an element relatively, the property position is set as relative. The difference between absolute and
relative positioning is how the position is being calculated.
The position for an element which is relatively positioned is calculated from the original position in the
document. That means that you move the element to the right, to the left, up or down. This way, the element
still obtains a space in the document after it is positioned.
As an example of relative positioning, we can try to position three pictures relatively to their original position on
the page. Notice how the pictures leave empty spaces at their original positions in the document:
#dog1 {
position:relative;
left: 350px;
bottom: 150px;
}
#dog2 {
position:relative;
left: 150px;
bottom: 500px;
}
#dog3 {
position:relative;
left: 50px;
bottom: 700px;
}

Layer on layer with z-index (Layers)


CSS operates in three dimensions - height, width and depth. We have seen the first two dimensions in previous
lessons. In this lesson, we will learn how to let different elements become layers. In short, this means the order
of which the elements overlap one another. For that purpose, you can assign each element a number (z-index).
The system is that an element with a higher number overlaps an element with a lower number.
Let us say we are playing poker and have a royal flush. Our hand can be presented in a way where each card has
got a z-index:

In this case, the numbers follow on another (1-5) but the same result can be obtained by using 5 different
numbers. The important thing is the chronological sequence of the numbers (the order).
The code in the card example could look like this:
#ten_of_diamonds {
position: absolute;
left: 100px;
top: 100px;
z-index: 1;
}
#jack_of_diamonds {
position: absolute;
left: 115px;
top: 115px;
z-index: 2;
}
#queen_of_diamonds {
position: absolute;
left: 130px;
top: 130px;
z-index: 3;
}
#king_of_diamonds {
position: absolute;
left: 145px;
top: 145px;
z-index: 4;
}
#ace_of_diamonds {
position: absolute;
left: 160px;
top: 160px;
z-index: 5;
}

JavaScript
JavaScript gives you the freedom to add interactivity and responsiveness to your web pages.
The aim of this tutorial is to provide you with a thorough, yet accessible introduction to JavaScript using snappy
explanations and practical tasks to try out right from the start.
No prior knowledge of JavaScript is assumed, but because JavaScript sits within and manipulates web pages, in
order to be able to follow along, you should already be familiar with HTML and CSS.
JavaScript is a lightweight, easy to learn, scripting language. Its used on almost every website to respond to user
actions, validate web forms, detect browser support, and much more.
JavaScript is a web programming language, that is, a language that enables you, the designer of your website, to
control how a web page behaves. This makes JavaScript crucially different from HTML, the language that
gives structure to your web documents, and CSS, the language that controls the appearance of web pages.

What is JavaScript?
The first thing that creates some confusion about JavaScript is
its name. In fact, one of the most common questions students
raise when approaching JavaScript is:
"Is JavaScript the same as Java?".
Clearing up this basic but important question is our first order
of business in this lesson, but by no means the only one. By the
end of this lesson you will also know:
the difference between JavaScript and Java;
what JavaScript can and cannot do.

Are JavaScript and Java the same thing?


No, they are not.
Java (developed by Sun Microsystems) is a powerful and much more complex programming language in the
same category as C and C++.
JavaScript was created by Brendan Eich at Netscape and was first introduced in December 1995 under the name
of LiveScript. However, it was rather quickly renamed JavaScript, although JavaScripts official name
is ECMAScript, which is developed and maintained by the ECMA (European Computer Manufacturer's
Association) International organization.
JavaScript is a scripting language, that is, a lightweight programming language that is interpreted by the browser
engine when the web page is loaded.
The fact that the JavaScript interpreter is the browser engine itself accounts for some inconsistencies in the way
your JavaScript-powered page might behave in different browsers. But don't worry: thankfully, well-established
techniques and powerful JavaScript libraries such as jQuery (which will be introduced in later lessons) are here
to make things wonderfully easier on us.
Things you can't do with JavaScript
You can't force JavaScript on a browser.
JavaScript runs in the client, that is, the brower. If you use an older browser without support for JavaScript, or if
you simply choose to disable JavaScript in your browser, then a JavaScript script can't work.

Conclusion: unlike what happens with languages that run on the server, such as PHP, you never fully know for
sure the impact that the browser your website visitors are going to use will have on your script, or whether your
visitors will choose to turn JavaScript support off.
You can't access or affect resources from another internet domain with JavaScript.
This is called the Same Origin Policy. Well, how would you like it if all of a sudden all the nice comments your
visitors left on your website started to disappear, or to change place in your page because of a naughty JavaScript
script running on another website?
This is exactly the kind of nasty situation that the Same Origin Policy is designed to prevent. Conclusion: your
JavaScript script can only access resources in your website.
You can't access server resources with JavaScript.
Because JavaScript is a client-side language, it's limited to what can be done in the client, that is, usually in the
browser environment. A JavaScript script cannot access server resources such as databases.
Zillion things you can do with JavaScript
With JavaScript you can:
Put text in an HTML page on-the-fly.
Say you want to display a nice thank you message to a user who has just submitted a comment form on your
website. Obviously, the message needs to be added after the user has submitted the form.
You could let the server do that. However, if your website is very busy and your server processes hundreds of
forms a day, it might take a little while for your thank you message to appear to the user.
Here's JavaScript to the rescue. Because JavaScript runs in the user's browser, the thank you note can be added
and displayed on the page almost instantaneously, making your website users happy.
Make your web pages responsive.
Web environments are dynamic, things happen all the time: the web page loads in the browser, the user clicks
a button or moves the mouse over a link, etc. These are called events.
With JavaScript you can make the page immediately react to these events the way you choose: for example, by
showing or hiding specific page elements, by changing the background color, etc.
Detect visitors' browsers.
You can use a JavaScript script to detect the visitors browser, or, even better, you can detect what features a
certain browser does or does not support. Depending on the browser and its capabilities, you can choose to load
a page specifically tailored to that kind of browser.
Create cookies.
A JavaScript script is great if you want to create cookies so that your visitors can enjoy a personalized experience
the next time they visit your website.
Validate web form data.
You can use a JavaScript script to validate form data before the form is submitted to a server. This saves the
server from extra processing.
And much ... much more.
Learning JavaScript will enable you to add cool animation effects to your web pages without using an external
Flash plug-in, use the newest features of HTML5 such as canvas (to draw directly on your web page) and drag
and drop capabilities, integrate your website with external web services such as Facebook, Twitter, etc.

The HTML
To insert a JavaScript script in an HTML page, you use the <script> ... </script> tag. Don't forget the closing
</script> tag! Now get ready to fire off your text editor of choice and let's get coding!
Let's start with a basic HTML page, like this one:
<!DOCTYPE html>
<html>
<head>
<title>My first JavaScript page</title>
</head>
<body>
</body>
</html>
The JavaScript script is inserted either in the HTML page itself or in a separate file.
Embed JavaScript in the HTML page
The <script> tag and its type attribute tell the browser: "Hey, browser! There's a script coming up, and it's a
JavaScript script."
You can do this either in the <head> section, as follows:
<!DOCTYPE html>
<html>
<head>
<title>My first JavaScript page</title>
<script type="text/javascript">
//JavaScript code goes here
</script>
</head>
<body>
</body>
</html>
Or or at the very bottom of the document just before the closing </body> tag, like so:
<!DOCTYPE html>
<html>
<head>
<title>My first JavaScript page</title>
</head>
<body>
<script type="text/javascript">
//JavaScript code goes here
</script>
</body>
</html>
If you're wondering whether it's best to place your <script> tag in the <head> or the <body> tag, then you're not
alone.
It mostly comes down to personal preference. However, because most of the times you'll want your JavaScript
code to run after the web page and all its resources, e.g. stylesheets, graphics, videos, etc., have finished loading
in the browser, I suggest you dump your JavaScript <script> tag at the bottom of your page.
Comments
One final thing to note about both code snippets above is the two forward slashes // before the text "JavaScript
code goes here". This is how you comment a one-line JavaScript code.
When a comment spans over more than one line, you use /* Comment goes here */ to delimit a comment, just
like you do in a stylesheet. Here's how it's done:

<!DOCTYPE html>
<html>
<head>
<title>My first JavaScript page</title>
</head>
<body>
<script type="text/javascript">
/* JavaScript code
goes here */
</script>
</body>
</html>
When the JavaScript interpreter in your browser comes across either '//' or '/* */', it just ignores whatever text
is placed in between. Use comments in your code to remind your future self of what your code is designed to
do. One day you'll be happy to have done so, just take my word for it!
Insert JavaScript in a separate file
If your script is longer than a few lines, or you need to apply the same code to several pages in your website,
then packaging your JavaScript code into a separate file is your best bet.
In fact, just like having your CSS all in one place, well away from HTML code, having your JavaScript in its own
file will give you the advantage of easily maintaining and reusing your scripts.
Here's how it's done:
<!DOCTYPE html>
<html>
<head>
<title>My first JavaScript page</title>
<script type="text/javascript" src="yourjavascript.js"></script>
</head>
<body>
</body>
</html>
As you can see, the <script> tag references an external file, "yourjavascript.js" that has the .js extension and
contains the script that puts the magic into your web page.
Your first JavaScript-powered page: Hello World
Without further ado, let's see if JavaScript works in your browser.
Try out: embedded JavaScript in an HTML page
Between the <script> and </script> tags either in the <head> or the <body> of your HTML document, add the
following line of code, just after the comment:
<!DOCTYPE html>
<html>
<head>
<title>My first JavaScript page</title>
</head>
<body>
<script type="text/javascript">
//JavaScript code goes here
alert('Hello World!');
</script>
</body>
</html>

This is your first JavaScript statement, that is, you've just instructed your web page to do something. Don't worry
about the code just yet, we'll be coming back to the alert() command again and again in the following lessons.
Just notice the semicolon ( ; ) at the end of the statement. This is important: it tells the JavaScript interpreter
that the statement is finished and whatever comes next is a different statement.
Now save your work and run the page in your favorite browser. You'll see an alert box popping up on page load.
This is how the page looks in Firefox:
If your alert box is not popping up, then check that you've typed the JavaScript command exactly as it is in the
sample code.
Make sure your <script>...</script>tags are there, that the text between the brackets is surrounded by quotes
(' '), and that there is a semicolon ( ; ) at the end of the statement. Then try again.
Try out: JavaScript in a separate file
Create a new document in your text editor and save it as "helloworld.js".Important: the file extension has to be
.js (this is the appropriate JavaScript file extension).
In the new document, paste in the JavaScript command from the previous example (no need to type the <script>
... </script> tags here):
alert('Hello World!');
Now, go back to the HTML page, delete the previous JavaScript code, and add the <script> ... </script> tags in
the <head> section of the page with a reference to the helloworld.js JavaScript file, like so:
<!DOCTYPE html>
<html>
<head>
<title>My first JavaScript page</title>
<script type="text/javascript" src="helloworld.js"></script>
</head>
<body>
</body>
</html>
Save all your documents and run the HTML page in the browser. You should view the same alert box popping up
as in the previous example.
If the code doesn't work, in your HTML document check that the filepath to the JavaScript file is correct, the
filename spelling is accurate, and double-check that you've added a closing </script> tag. In helloworld.js make
sure your JavaScript command is typed exactly the same as in the sample code above, then try again.
Events
The web is a dynamic environment where a lot of things happen. Most appropriately, they're called events.
Some of these events, like a user clicking a button or moving the mouse over a link, are of great interest to a
JavaScript coder.
By the end of this lesson you will know:
what events are;
what JavaScript can do with events and how.
What are events?
Events are occurrences taking place in the context of the interactions between
web server, web browser, and web user. For instance, if you're on a web page
and click on a link, there are at least 3 important events being triggered:
1. onClick event: triggered by you as you click the link;

2.
3.

onUnload event: triggered by the web browser as it leaves the current web page;
onLoad event: triggered by the browser as the new web page content is loaded.

Which events should I focus on from a JavaScript point of view?


It all depends on the JavaScript program you're writing, that is, on the objectives you want to achieve with your
script.
However, the most common events you're likely to deal with in your JavaScript are:
onLoad/onUnload;
onClick;
onSubmit (triggered by the user submitting a form);
onFocus/onBlur (triggered by a user as, for example, she clicks in a textbox or clicks away from a textbox
respectively);
onMouseOver/onMouseOut (triggered by the user moving the mouse over or away from an HTML
element respectively).
There are other events that might eventually be of interest to you as you write sophisticated JavaScript scripts,
such as scroll events (as users scroll up and down a web page), onTextChanged events (as users type in a textbox
or textarea), even touch events, which are likely to gain interest in today's mobile and tablet-invaded world.
However, for the purposes of this tutorial, you're mostly going to come across the core events listed above.
What do I do with events from a JavaScript point of view?
As you write a JavaScript program, events become
interesting because they give your script a hook for
gaining control on what happens in the web page.
Once your script gets hold of the hook provided by
the event, your script is boss. The jargon for this
is event-driven programming: an event happens
and JavaScript handles it, for instance by displaying
an alert box with a message for the user.
Conclusion: events bend to JavaScript commands
by means of event handlers. These are statements in your JavaScript script that are appropriately attached to
those events.
How does JavaScript handle events?
In this tutorial you've already hooked an event handler to an event. More precisely, you attached the alert()
command to the onLoad event.
The alert() command is a command which is part of the JavaScript language. The JavaScript interpreter in the
browser translates it along these lines:
"Hey, browser, display an alert box that contains the message typed within the () enclosing brackets"
(Notice: JavaScript is case sensitive. If you write Alert instead of alert, your script won't work!).
As you saw in the previous lesson, simply by writing a JavaScript statement between <script> ... </script> tags
achieves the execution of that statement as the onLoad event fires up.
However, your JavaScript scripts are capable of doing more interesting stuff when they handle events in
response to user actions, for example an onClick event. How do we do that?
Try out: handle an onClick event with JavaScript
The browser already has its own ways of handling events. For instance, when a page has loaded, the browser
fires the onLoad event and displays the page contents; when a user clicks a link, the browser communicates to
the server to access the requested page, etc. These are called default actions.

The fun of being in charge, though, is not to let the browser do what it likes, but of letting JavaScript do its job
and decide what's to be done.
The simplest way to attach an event handler to an event is to insert the required JavaScript code within the
HTML element that produces the event. Let's have a go by simply preventing the browser default action as the
user clicks a link on the page. Fire off your text editor and let's get coding!
Prepare a new basic HTML document displaying a simple link like the one shown below:
<!DOCTYPE html>
<html>
<head>
<title>Lesson 3: Events and Event Handlers</title>
</head>
<body>
<h1>Lesson 3: Events and Event Handlers</h1>
<a href="http://html.net">Click Me!</a>
</body>
</html>
Run the page in the browser. If you click on the link now, you'll be landing straight to the HTML.net website. This
is the browser default action, as explained above.
Now go back to your HTML document and type the following JavaScript command within the <a> tag, as follows:
<!DOCTYPE html>
<html>
<head>
<title>Lesson 3: Events and Event Handlers</title>
</head>
<body>
<h1>Lesson 3: Events and Event Handlers</h1>
<a href="http://html.net" anywhere? Not so fast!');
return false;">Click Me!</a>
</body>
</html>
What's just happened there?
That's how easy it was to take control of a link with JavaScript! All you did was to insert a couple of JavaScript
statements to the onclick attribute of the HTML <a> tag.
You already know about the good old alert() command, so I'll skip over it. The return false; command tells the
JavaScript interpreter to return a value, in this case the value equals false, which prevents the browser from
performing its default action. You'll be using this little command quite often in your JavaScript programming life.
You handle the other events listed above in the same way: just insert the JavaScript command as the value of
the onfocus, onblur, onmouseover, onmouseout and onsubmit attributes of an HTML element.
Variables and Constants
Variables and constants are like containers where you store data and values for processing in JavaScript.
The difference between a variable and a constant is this: once you give a value to a constant the value is meant
to be kept unchanged throughout the script. In all circumstances where you reasonably foresee that the original
value is modified through the script, by all means use a variable as your storage room. In fact, you're going to
use variables most of the times.
In this lesson, you're going to learn:
how to create variables and constants;
how to assign values to variables and constants;
how to use variables in your code;

how to name variables and constants correctly.

How to create variables and constants


You declare, that is, create variables and constants in a similar way.
Here's how you declare a variable:
/*To declare a variable you give it a name preceded by the JavaScript keyword var*/
var amountDue;
In the sample code above you declare a variable named amountDue.
The variable declaration ends with a (;) semicolon, which makes it a self-contained statement.
Also, because JavaScript is case sensitive, every time you refer to the amountDue variable, make sure you keep
the letter case exactly the same as the original declaration (this particular notation is called camelCase because
it looks like a camel's hunch).
Here's how you declare a constant:
/*To declare a constant you give it a name preceded by the JavaScript keyword const
Also take note: const is not supported by Internet Explorer use var instead: it's safer*/
const taxRate;
In the sample code above, you declare a taxRate constant. As you can see, the declaration is very similar to the
variable declaration, the only difference being the keyword used: var in the case of a variable and const in the
case of a constant.
How to assign values to variables
After you create a variable, you must assign (give) a value to it (or said in Geeeky talk "initialize a variable").
The (=) equal sign is called assignment operator: you assign the value of what is on the right side of the = sign
to whatever is on the left side of the = sign. Notice: you cannot perform operations with empty variables. Ready
to fire off your text editor? Let's get coding!
Prepare a basic HTML document with the JavaScript code illustrated below:
<!DOCTYPE html>
<html>
<head><title>Variables and Constants</title></head>
<body>
<script type="text/javascript">
//Create a variable
var amountDue;
/*Assign a value to it: you do not know the value yet so for now it is 0 */
amountDue = 0;
/* Create 2 more vars and assign a value to each at the same time */
var productPrice = 5;
var quantity = 2;
/*Assign a value to amountDue by multiplying productPrice by quantity */
amountDue = productPrice * quantity;
/* Notice how the value of amountDue has changed from 0 to 10 - Alert the result to check it is OK.
Notice: you do not use ' ' with var name in alert() */
alert(amountDue);
</script>
</body>
</html>
Did you see the good old alert box displaying the number 10 popping up? If you didn't, make sure your code is
typed exactly the same as in the snippet above (Notice: When tracing bugs (errors) in your JavaScript code,
look out for brackets, semicolons (;), quotes (' '), and letter casing).

That's great! Try experimenting with the code above. For example, change the value of quantity and
productPrice, or just come up with your own variables.
How to name variables (and constants)
Choose descriptive names for your variables (var amountDue; rather than var x;): this way your code will be
more readable and understandable.
While this can be called good programming practice (but also common sense), there are also syntax rules (yes,
just like any natural language) when it comes to naming variables, and they must be obeyed, at least if you want
your JavaScript script to work.
Keep an eye on the following simple rules when you name variables:
1) The first character must be a letter, an (_) underscore, or a ($) dollar sign:
5total is wrong: var name cannot start with a number
2) Each character after the first character can be a letter, an ( _ ) underscore, a ( $ ) dollar sign, or a number:
3) Spaces and special characters other than ( _ ) and $ are not allowed anywhere:
to tal is wrong: spaces are not allowed;
total# is wrong: # character is not allowed;
total is wrong: character is not allowed
Smarter Scripts with Operators
In the previous lesson you already employed an assignment operator ( = ) and an arithmetic operator,
specifically the multiplication operator ( * ), to write a basic JavaScript shopping cart script.
We can easily see that to do something useful with JavaScript, we need a way to manipulate data and variables.
We do this with operators.
In this lesson you are going to learn how to use:
arithmetic operators;
the + sign to concatenate text (concatenation operator);
comparison operators;
logical operators.
Also, you'll get plenty of opportunities to practice coding with variables. Let's get started!
Arithmetic operators
As you might have guessed, arithmetic operators are used to perform arithmetic operations between values
or variables. Here's a table for your reference.
Operator
Java Script Example
Addition: +
z=x+y
Subtraction: z=x-y
Multiplication: * z = x * y
Division: /
z=x/y
Modulus: %
z=x/y
Increment: ++
z = ++x
Decrement -z = --x
Try out: add 2 values and print the result
<!DOCTYPE html>
<html>
<head><title>Lesson 5: Operators and Comparisons</title>
</head>
<body>
<script type="text/javascript">
//Create and initialize your variables
var result = 0;
var firstNum = 20;

var secondNum = 5;
//Addition: result = 25
result = firstNum + secondNum;
//write result on the page
document.write(result);
</script>
</body>
</html>
Nothing new here except for the JavaScript command document.write(). This command is translated by the
JavaScript interpreter as saying:
"Hey browser, get the value within brackets and print it on the HTML document!"
In our case the value is a variable, therefore no (' ') quotes are used to enclose it. If you want to print some text
instead, the command must be: document.write('some text.');. It's all very similar to the alert() command you've
been using so far.
Now experiment with the code sample above by trying out all the other arithmetic operators and printing the
result on the page.
Concatenation operator
If you want to add pieces of text together to form one long line of text, use the + sign. In Geeky talk a piece of
text is called string, and it appears enclosed either in (' ') quotes or (" ") double-quotes (remember the 'Hello
World' text you used in the alert() command? That is an instance of string).
Try out: concatenate strings and print a message on the page
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script type="text/javascript">
//Create and initialize your variables
var firstText = "Hello";
var secondText = "World!";
//Resulting value of assignment is Hello World!
var message = firstText + ' ' + secondText;
//write result on the page
document.write(message);
</script>
</body>
</html>
If you typed your code correctly, you should see the famous Hello World! text smack on the web page. Notice:
you separate Hello and World! by concatenating quotes (' ') in-between each piece of text or variable.
Comparison operators
Often you need to compare different values and make your JavaScript program take different directions
accordingly.
Operator
What is it?
Example (if x is 10)
==
equal to
x == 5 is false
===
exactly equal to value and type
x === 10 is true x === "10" is false
!=
not equal
x != 2 is true
>
greater than
x > 20 is false
<
less than
x < 20 is true
>=
greater than or equal to
x >= 20 is false
<=
less than or equal to
x <= 20 is true

Logical operators
You use logical operators when you need to determine the logic between certain values.
Given that x = 10 and y = 5:
Operator
What is it?
Example
&&
and
(x < 20 && y > 1) is true, both conditions must be satisfied
||
or
(x == 5 || y == 5) is true, at least 1 condition must be satisfied
!
not
!(x == y) is true
ifelse and switch
Now that our JavaScript code can calculate, compare, and determine true and false conditions, things start
looking a lot more interesting.
The days of dumb message boxes popping up are long gone, the new era of smart message boxes has begun. In
this lesson you're going to inject the power of choice into your scripts with conditional statements. These
statements enable your script to evaluate given conditions on the basis of which to execute one or more actions.
More specifically, you're going to learn how to use:
if statements;
if ... else statements;
if ... else if ... else statements;
switch statements.
In the process, you're also going to learn how to use shortcut assignment operators.
if Statement
The if keyword is used in JavaScript to perform a basic test for the truth or falsity of a given condition and
execute a piece of code accordingly. Here's its structure:
//if the condition in brackets is true
if (condition) {
//do some stuff here
}
if ... else statement
Use this statement to execute a command if the condition is true and another command if the condition is
false. Here's its structure:
//if the condition is true
if (condition) {
//do this stuff
}
//otherwise
else {
//do this other stuff
}
if ... else if ... else statement
Use this statement if you want your code to evaluate several conditions on the basis of which to execute the
appropriate commands. Here's its structure:
//if the condition is true
if (condition) {
// do this stuff
}
//if this other condition is true instead
else if (condition) {
// do this other stuff
}
//if none of the above condition is true
else {

// do this instead
}
switch statements
In alternative to an if ... else if ... elsestatement you can switch to a ... well a switch statement. Here's its basic
structure:
//condition to evaluate
switch(condition) {
//in this case do this
case 1:
execute code block 1
//stop here: no need to keep going
break;
//in this other case do that
case 2:
execute code block 2
break;
default:
code to execute when all previous conditions evaluate to false
}
Handy shortcuts are also available to all other mathematical operators:
-=
*=
/=
%=
Leave Boring Repetitive Stuff to JavaScript with loops
Your JavaScript scripts can do all sort of clever stuff like calculating discounts, comparing values, and making
choices. However, don't forget we're dealing with machine language, and machines are very good at doing some
things us humans would keep a mile off if only we could.
One really boring thing most of us would happily avoid doing is repetitive stuff. You might find it hard to believe
this, but JavaScript loves repetition. So much so that it has a special construct for it: the loop.
Here's what you will learn in this lesson:
the for loop;
the while loop;
the do ... while loop.
In the process, you will also learn how to:
use getElementById(element Id) to manipulate an HTML element with JavaScript;
generate random numbers with random() and floor(number);
insert HTML mark-up dynamically with inner HTML.
This is going to be a meaty lesson. Get ready for it!
Loops
At times you will have to repeat some piece of code a number of times:
for instance: a web page has 10 radio buttons and your script needs to find out which radio button was checked
by the user.
To do so, your script has to go over each single radio button and verify whether its checked attribute is set to
true or false. Does this mean having to write this kind of verification code 10 times?

Thankfully, it does not. You dump the code in a loop once, and it's going to execute any number of times you
set it to.
The for Loop
This kind of loop, well ... loops through a block of code a set number of times. Choose a for loop if you know in
advance how many times your script should run.
Here's its basic structure:
for (var=startvalue; var<=endvalue; var=var+increment) {
//code to be executed
}
The while Loop
If you don't know the exact number of times your code is supposed to execute, use a while loop.
With a while loop your code executes while a given condition is true; as soon as this condition evaluates to
false, the while loop stops.
Here's its basic structure:
while (variable <= endvalue) {
//code to be executed
}
do ... while Loop
This kind of loop is similar to the while loop. The difference between the two is this:
In the case of the while loop, if the test condition is false from the start, the code in the loop will never be
executed.
In the case of the do ... while loop, the test condition is evaluated after the loop has performed the first cycle.
Therefore, even if the test condition is false, the code in the loop will execute once.
Here's the basic structure of a do ... while loop:
do {
//code to be executed
} while (variable <= endvalue);
Package your JavaScript Code with Functions
You can already add quite a bit of JavaScript functionality to web pages, and that's great. However, what if you
decide to implement the same kind of functionality on more than one page, or in different places on the same
page?
This is where JavaScript functions come into play.
what functions are and how they are used in JavaScript;
how to retrieve information from functions;
how to give information to functions;
what variable scope is all about.
In the process you will also learn how to:
get today's date dynamically;
change the value of an HTML button element dynamically.
Functions: what they are and what they are for?
In previous lessons you used JavaScript functions to perform some actions quickly and easily like generating
random numbers, writing something on a web page, etc. In fact, JavaScript has a great many built-in functions
like write(), alert(), getElementById(), random(), floor(), and several others. Wherever you spot a pair of round
brackets there's likely a function in action.
JavaScript also gives you the option to craft your own functions.

A function is a way of packaging your JavaScript commands so you can easily reuse them every time you need
the same piece of functionality implemented in your website.
This suggests that there are 2 distinct phases to a function:
1. The phase where the function is declared (created);
2. The phase where the function is called (used).
function functionName() {
//code you want to run goes here
}
Call a function
Once you put a block of code into a function, you can use it anywhere you need that functionality in your website.
What you need to do is just call the function.
functionName();
Prepare a simple HTML page like the one below. The program we're going to build has the following goals:
to get today's date dynamically when the user clicks a button;
to display today's date on the web page;
to change the value attribute of the button after it's clicked: to have the button still displaying Get
Dateafter the date has been displayed looks a bit confusing to the user.
<!DOCTYPE html>
<html>
<head>
<title>Declare a function</title>
</head>
<body>
<div>
<h2>Today's date is:</h2>
<span id="calendar"></span>
<input type="button" id="myButton" value="Get Date" />
</div>
<script type="text/javascript">
//Declare your function here
function showDate() {
var today = new Date();
var myCalendar = document.getElementById("calendar");
var myButton = document.getElementById("myButton");
myCalendar.innerHTML = today.toDateString();
myButton.value = "Well done!";
}
</script>
</body>
</html>
Variables inside and outside functions: scope
A variable can have local or global scope on the basis of whether it's declared inside or outside a function
block. But, what does this mean exactly?
Simply put, a variable having local scope means that it's visible, or accessible, only within the function in which
it lives. No other portion of your code can see a local variable.
On the other hand, a variable having global scope means that it's accessible, that is, it can be used, anywhere
in your script.

Introduction to Objects
Object Oriented Programming (OOP) is a programming model used by most contemporary programming
languages. JavaScript offers significant object oriented capabilities, has its own built-in objects, and offers you
the option of creating your own custom objects.
This is a wide and complex subject and we're only going to scratch the surface in this tutorial series. However,
because as soon as you start coding in JavaScript you can't avoid dealing with objects, it's important that you get
familiar with some core concepts of OOP.
This short lesson is introductory to the more detailed and practical lessons on specific JavaScript objects that
follow.
Here is what you will learn:
the concept of object in web programming;
what object properties are;
what object methods are.
What is an object in Geeky talk?
Real world objects are things like books, cars, balls, etc. We humans deal with the world around us by interacting
with and manipulating things, that is, objects.
What most computer programs do is manipulate, manage, and reuse data of various kinds. Therefore, using the
real world object metaphor, contemporary programming languages like JavaScript deal with their virtual
environment by populating it with packaged data modelled after the concept of an object.
Everything in JavaScript is an object and you've already used plenty of objects without realizing it. In fact, you're
already familiar with:
the Document object that you used to print your JavaScript messages on the web page;
the Math object, that you used to generate random numbers and round off decimals;
HTML elements like the button object that you used to manipulate its value attribute;
the Date object that you used to retrieve the current date.
Properties and methods
But how exactly does JavaScript manipulate objects?
The answer is: not much differently from the way we humans manipulate real world objects. We do this by
interacting with the qualities and capabilities that belong to individual objects.
Let's take a ball as our example. We interact with the ball by means of some of its qualities (its roundness, its
hardness, its size, etc.). Also, we interact with the ball on the bais of what we expect the ball's behavior to be
like (we expect that we can launch the ball without breaking it, that we can throw it against a wall and it bounces
back, etc.).
Similarly, a JavaScript script interacts with its object-modelled data by means of the objects' qualities and
behavior. These are called properties and methods.
Properties are values associated with an object. For example, an HTML element object has a value property
(like the button object you're familiar with), and an inner HTML property, that you used to add new mark-up to
the web page.
Methods represent what an object can do, its behavior, and are very much like functions.
How do you associate an object with a property or a method?
If you wondered what that odd-looking (.) dot notation in document.write() or Math.random(), and so on, meant
in previous lessons, here's the answer.

You use the object.property and object.method syntax to interact with JavaScript objects.
//use the random() method of the Math object
Math.random();
//use the write() method of the document object
document.write();
//use the length property of the string object
myStringText.length;
JavaScript Objects - Strings
In the previous lesson you were introduced to the concept of Object Oriented Programming (OOP). You're now
familiar with the use of objects and their properties and methods in JavaScript programming.
Starting from this lesson and for the next 3 lessons, we will be getting up close and personal with some of the
most common properties and methods of widely used JavaScript objects: String, Date, Math, and Array.
However, because JavaScript as a programming language is mostly made of objects, you will keep learning to
use more objects and related properties and methods throughout the rest of this tutorial.
In this lesson you will learn how to use the following properties and methods of the string object:
length property;
toLowerCase()/toUpperCase();
match();
replace();
indexOf().
In the process, you will also practice putting your JavaScript code into an external file.
The String object
You've had plenty of practice with the string object through this tutorial. In fact, the JavaScript interpreter reads
any piece of text enclosed in quotes ' ' (or double quotes " ") as an instance of the string object. This puts the
magic of all the properties and methods belonging to the string object in our hands.
The beauty of Object Oriented Programming is that we can use all that JavaScript goodness to achieve our
script's goals without needing to have any clue whatsoever of the inner workings of those properties and
methods. All we need to know is what a property or method can do for us, not how it does it.
For example, if we need to know the length of a piece of text, just using pieceOfText.length will achieve this.
This is accomplished without us knowing anything of the programming virtuosity responsible for the power of
the length property of the string object.
Let's have a taste of such power.
How to use length
The length property of the string object contains the number of characters (including spaces) in the text value
of a string.
Here's a basic code snippet to demonstrate its use:
//create and initialize a string variable
var myString = "Hello JavaScript"
//apply the length property to the string
document.write(myString.length);
//JavaScript will print 16:
//spaces are included in the count
//If the string is empty length returns 0
Try out for yourself: insert the code above between enclosing <script> tags and have fun experimenting with it.
How to use toUpperCase()
The toUpperCase() method of the string object turns the text value of a string into, well ... uppercase letters. Its
companion toLowerCase() does the opposite: it turns the text value of a string into lowercase letters.

Here's a basic code snippet to demonstrate its use:


//create and initialize a string variable
var myString = "Hello JavaScript"
//apply the toUpperCase() method to the string
document.write(myString.toUpperCase());
//JavaScript will print HELLO JAVASCRIPT
//Try using myString.toLowerCase() on your own
Have a try: insert the code above between enclosing <script> tags and switch uppercase into lowercase.
How to use match()
The match() method of the string object is used to search for a specific value inside a string.
Here's a basic code snippet to demonstrate its use:
var myString = "Hello JavaScript"
document.write(myString.match("JavaScript"));
Experiment on your own: insert the code above between enclosing <script> tags and try matching different
string values.
How to use replace()
The replace() method of the string object is used to replace a value for another value inside a string.
Here's a basic code snippet to demonstrate its use:
var myString = "Hello JavaScript"
document.write(myString.replace("JavaScript", "World"));
Have a go: insert the code above between enclosing <script> tags and try replacing different string values.
How to use indexOf()
The indexOf() method of the string object is used to know the position of the first found occurrence of a value
inside a string.
Here's a basic code snippet to demonstrate its use:
var myString = "Hello JavaScript"
document.write(myString.indexOf("Java"));
Have a go on your own: insert the code above between enclosing <script> tags and print the index position of
different letters inside the string.
Try out: guessing game
You're going to build a simple guessing game application using all the new knowledge you've acquired in this
lesson. Your application is expected to check a name entered by the user and respond accordingly:
Your JavaScript code will be placed in its own external file and referenced from the HTML
document. Separation of concerns, that is, separation between structure (HTML mark-up), appearance (CSS),
and behavior (JavaScript), reflects contemporary best practices in web design.
Let's start with the HTML document. This is a simple web page with a textbox, a button, and a div where the
JavaScript result will be displayed:
<html>
<head>
<title>Lesson 10: JavaScript Objects - Strings</title>
<script type="text/javascript" src="lesson10.js"></script>
</head>
<body>
<h1>Lesson 10: JavaScript Objects - Strings</h1>
<h2>What's the name of the wizard boy in J.K. Rowling's novels?</h2>
<p>Your answer: <input type="text" id="txtName" /></p>
<p><input type="button" value="Submit your answer" id="btnAnswer" />
<p id="message"></p>

</body>
</html>
Pay attention to the enclosing <head> tags. These contain a reference to an external JavaScript
file namedlesson10.js located in the same directory as the HTML file (you're free to place the JavaScript file in
its own directory, if you prefer. However, make sure this is reflected in the src value of your <script> tag in the
HTML document).
Also, take note of the fact that the elements that are going to play a role in our script all have an id attribute.
This gives JavaScript a hook on those elements and the data they will eventually contain.
Now open the JavaScript file lesson10.js and type the following code:
function init() {
var myButton = document.getElementById("btnAnswer");
myButton. >}
//Assign the init() function to the onload event:
//this event fires when the HTML page is loaded in the browser.
//Take note: init is assigned without brackets
>function getAnswer() {
var secretName = "Harry Potter";
var secretNameLower = secretName.toLowerCase();
var myTextBox = document.getElementById("txtName");
var name = myTextBox.value;
var nameLower = name.toLowerCase();
var message = document.getElementById("message");
if(nameLower.length <= 0) {
alert("I didn't quite catch your answer. Please enter an answer");
}
else if(nameLower.indexOf("harry") == 0 && nameLower.indexOf("potter") == -1) {
alert("Almost there: think again");
}
else if(nameLower.match(secretNameLower)) {
alert("You got it!");
message.innerHTML = "Congratulations, you win!";
}
else {
alert("Wrong!");
message.innerHTML = "Sorry. The correct answer is: ";
message.innerHTML += name.replace(name, "Harry Potter");
}
}
Save all your files and run the HTML page in the browser. You should see something similar to the example page
indicated in the link above.
If you click the button without entering any value in the textbox, an alert will pop up inviting you to enter an
answer.
If you get right the first half ("Harry") - indexOf() returns 0 ("Harry" is at position 0, which is the start of the
index) - but not the latter half ("Potter") - indexOf() returns -1 (it finds no corresponding value inside the
string), you get an alert letting you know that your answer is almost right.
If you enter the correct answer, well you'll get a prize.

Finally, if your answer is totally wrong, your application will say so and give you the correct answer.
The above code sample employs all the JavaScript tools you learned in this lesson and most of those you
encountered in previous lessons. Experiment with it as much as you can. If you have doubts, leave a message in
our JavaScript forum.
JavaScript Objects - Date Object
In the previous lesson, you had a go at manipulating text by taking advantage of the powerful properties and
methods of the String object.
Here we continue to explore the power of JavaScript objects: we will be looking into the magical virtues of
the Date object.
Here's what you will do in this lesson:
create a Date object;
set dates;
compare dates.
The Date object
In previous lesson you learned how to retrieve the current date and display it on the web page in user-friendly
format. This could be done dynamically thanks to the JavaScript goodness offered by the Date object.
The Date object exposes plenty of methods to manipulate dates and times, some of which we're going to
examine here.
I recommend you try out all the demos below by inserting the code snippets between enclosing <script> tags
in an HTML page (for such short demos we can get away with not using an external JavaScript file ). Also, feel
free to experiment with each demo as much as possible before moving on to the next example.
Create a Date object
You create a date object by using one of the following ways:
//First way:
var today = new Date().toLocaleDateString();
//Second way:
var date = new Date(1000).toLocaleDateString();
//Third way:
var date = new Date("10 November, 2011").toLocaleDateString();
//Fourth way:
var date = new Date(2011, 10).toLocaleDateString();
After a Date object is created, you can use its methods to get and set dates and times.
Use getDate() to retrieve a date
var myDate = new Date();
document.write(myDate.getDate());
Use getTime() to retrieve a time
var myTime = new Date();
document.write(myTime.getTime());
Get Date object components
Once you have a Date object, one interesting thing you can do with it is to get its various components. JavaScript
offers some interesting methods to do just that.

Use getFullYear() to extract the year component


var myDate = new Date();
document.write(myDate.getFullYear());
Use getMonth() to extract the month component
var myDate = new Date();
document.write(myDate.getMonth());
Use getDay() to extract the day component
var myDate = new Date();
document.write(myDate.getDay());
Use getHours() and getMinutes() to extract time components
var myDate = new Date();
var hours = myDate.getHours();
var minutes = myDate.getMinutes();
if (minutes < 10) {
minutes = "0" + minutes;
}
var timeString = hours + " : " + minutes;
document.write(timeString);
Set dates
You can also set dates and times as easily as calling the appropriate methods. Here are a few examples.
Use setFullYear() to set a specific date
var myDate = new Date();
var mySetDate = myDate.setFullYear(2011, 9, 31);
var mySetDay = myDate.getDay(mySetDate);
switch (mySetDay) {
case 0:
mySetDay = "Sunday";
break;
case 1:
mySetDay = "Monday";
break;
case 2:
mySetDay = "Tuesday";
break;
case 3:
mySetDay = "Wednesday";
break;
case 4:
mySetDay = "Thursday";
break;
case 5:
mySetDay = "Friday";
break;
case 6:
mySetDay = "Saturday";

break;
}
document.write("The 31st October 2011 is a " + mySetDay);
Compare 2 dates
var myDate = new Date();
var mySetDate = myDate.setFullYear(2011, 9, 31);
var now = new Date();
if (mySetDate > now) {
document.write("The 31st October is in the future");
}
else {
document.write("The 31st October is in the past");
}
JavaScript Objects - Math Object
We continue on our journey through JavaScript built-in objects by offering a quick overview of the Math object.
You already had occasion to taste the power of the Math object back in lesson 7, where you used its random()
methodto generate a random number between 0 and 1, and its floor() method to round down the resulting
random number.
The Math object allows you to write scripts that perform complex mathematical tasks in the blink of an eye.
In this lesson you will use:
Math.PI to calculate the circumference of a circle;
Math.sqrt() to calculate a square root value.
In the process, you will learn how to use:
parseInt()/parseFloat() to convert strings to numbers;
isNaN() to check whether a value is or is not a number;
Math.PI
This property stores the value of PI, a mathematical constant that amounts to approximately 3.14159.
Let's quickly refresh our school math. Here are some definitions:
Circle
A circle is a shape with all points the same distance from the center:
the round border surrounding the shape (the color blue in the graphic above), is the circle
circumference;
the line cutting the circle horizontally in half (the color red in the graphic above) is the circle diameter;
each half of the diameter represents a radius.
PI is the ratio of the circumference of a circle to the diameter.
If you need this value in your JavaScript program, use Math.PI. Just try this one out between enclosing <script>
tags of an HTML page:
var pi = Math.PI;
document.write(pi);
<html>
<head>
<title>Lesson 12: JavaScript Objects - Math Object</title>
<script type="text/javascript" src="lesson12_tryout1.js"></script>
</head>
<body>
<h1>Lesson 12: Circumference calculator</h1>
<p>Enter length of radius: <input type="text" id="txtRadius" /></p>

<p><input type="button" id="btnSubmit" value="Calculate circumference" /></p>


<p id="result"></p>
</body>
</html>
The HTML page above references an external JavaScript file, lesson12_tryout1.js, and contains an inputbox, a
button, and a paragraph where the result of the calculation will be displayed. Make sure these 3 crucial elements
have an id value so your JavaScript script will have an easy to reach hook on those elements.
Now create a JavaScript document and name it lesson12_tryout1.js. This file will contain 3 functions:
1. init() initializes the script by binding the processAnswer() function to its appropriate event, that is, the
btnSubmit onclick event;
2. processAnswer() checks the answer submitted by the user, calls the function that performs the
calculation, and displays the result;
3. getCircumference(rad) gets passed the radius value as argument, performs the actual calculation, and
returns the circumference.
function init() {
var myButton = document.getElementById("btnSubmit");
myButton. >}
//Bind the init function to the onload event
>function processAnswer() {
var inputBox = document.getElementById("txtRadius");
var radius = parseInt(inputBox.value);
var result = document.getElementById("result");
var resultString = "";
if (isNaN(radius)) {
alert("Please, enter a number");
}
else {
var circ = getCircumference(radius);
resultString = "Circumference is: " + circ;
result.innerHTML = resultString;
}
}
function getCircumference(rad) {
var circumference = 2 * (Math.PI * rad);
return circumference;
}
Save all your files and run the HTML page in the browser. You should see something like the page indicated by
following the example link above.
If you click the button without entering any value in the inputbox, or if you enter a letter rather than a number,
the program asks you to enter a number value.
As you click the button, the calculation is performed and the result is displayed on the page.
Math.sqrt()
Math.sqrt(number) takes a number as argument and returns the square root of that number.
If a negative number is entered as argument, for instance Math.sqrt(-5), the function returns NaN, that is, a
value that JavaScript does not treat as a number.

Brushing up on our school math, the square root of 25, for example, is that number that multiplied by itself
yields 25 as a result, that is, 5.
The formula is: square of n = n * n. JavaScript performs this calculation automatically. Here's a quick demo: type
the following code between enclosing <script> tags of an HTML page:
var squareRoot = Math.sqrt(25);
document.write("The square root of 25 is: " + squareRoot);
Try out: square root calculator
You will build a simple square root calculator. Here are the requirements for this little application:
the user will be able to enter a number value into an inputbox;
the user will be able to click a button that calculates the square root of the number entered into the
inputbox;
the result will be displayed on the web page.
Create a fresh HTML page with an inputbox, 1 button, and a paragraph where the result will be displayed. These
HTML elements contain id attributesthat will provide a handy hook for our JavaScript code.
<html>
<head>
<title>Lesson 12: JavaScript Objects - Math Object</title>
<script type="text/javascript" src="lesson12_tryout2.js"></script>
</head>
<body>
<h1>Lesson 12: Square root calculator</h1>
<p>Enter a number: <input type="text" id="txtNumber" /></p>
<p><input type="button" id="btnSubmit" value="Calculate square root" /></p>
<p id="result"></p>
</body>
</html>
Now create the tryout2.js file. This file will contain 3 functions:
1. init() initializes the script by binding the displaySquare() function to its appropriate event, that is, the
btnSubmit onclick event;
2. displaySquare() checks the answer submitted by the user, calls the function that performs the
calculation, and displays the result;
3. calculateSquare(input) gets passed the number value entered by the user as argument, performs the
actual calculation, and returns the the square root.
function init() {
var myButton = document.getElementById("btnSubmit");
myButton. >}
//Bind the init() function to the onload event
>function displaySquare() {
var inputVal = parseInt(document.getElementById("txtNumber").value);
var result = document.getElementById("result");
var resultMessage = "";
if (isNaN(inputVal)) {
alert("Please, enter a number");
}
else {
var squareVal = calculateSquare(inputVal);
if (squareVal) {
resultMessage = "Square root of " + inputVal + " is " + squareVal;

}
else {
resultMessage = "Sorry, an error occurred";
}
}
result.innerHTML = resultMessage;
}
function calculateSquare(input) {
var squareVal = Math.sqrt(input);
return squareVal;
}
Save all files and preview your work in a browser. You should see something similar to the example indicated by
following the link above.
Enter a number into the inputbox and click the button. If you enter anything but a number into the inputbox (or
if you leave the inputbox empty), you'll be alerted by a popup box asking you to enter a number. If all goes well,
the square root of the number you enter in the inputbox will be displayed on the page.
If the application is not working, check your typing, especially letter casing, brackets, and semi-colons (;).
JavaScript Objects - Arrays
Just using a few properties and methods of common JavaScript objects has opened your eyes to the amazing
things that Object Oriented Programming enables you to accomplish with a few lines of code. In this lesson, you
will learn to use what is a very powerful object in most programming languages, including JavaScript of course:
the Array object.
In particular, in this lesson you will learn:
what the Array object is for;
how to create arrays;
how to access, sort, add, and remove data inside an array.
In the process, you will learn how to use the for ... in loop to access data inside an array.
What is the Array object for?
An object's job is that of storing and allowing for the easy manipulation of data. We can safely say that the Array
object performs both tasks wonderfully.
From the perspective of data storage, an array works a bit like a variable. The difference is that you are not
limited to one piece of data, as it's the case with common variables. You can stuff several items at once inside
an array and retrieve whichever you need at the right time in your program.
Imagine if you had to have a storage place for each pair of socks. This would be a nightmare! Having a drawer to
store all your socks in one place makes much more sense. In this respect, arrays are a bit like drawers, but much
more powerful.
From the point of view of data manipulation, the Array object offers a wealth of properties and methods, some
of which you will examine in this lesson.
How do you create an Array object?
You create an array in 1 of 3 ways:
1) use new Array()
This is the most verbose approach. It works as follows:
var colors = new Array();
colors[0] = "green";
colors[1] = "red";

2) use new Array(item0, item1, item2 ...)


This approach also employs the new Array() constructor, but does so using a more concise formulation. Here's
what it looks like:
var colors = new Array("green", "red");
3) use the literal array approach
This is the shortest way of creating and populating an array, and it's the most widely used approach. It looks like
this:
var colors = ["green", "red"];
All 3 approaches illustrated above, create an array object called colors containing 2 string values, "green" and
"red" - but arrays can store all other data types: numbers, booleans, even other arrays! The items in our array
occupy position 0 and 1 respectively.
As you might have guessed, you count the index position of an item inside an array starting at 0.
But, is this index position important? Well, yes it is, at least if you want to use the items inside the array, which
is most likely the case.
How do I access data inside the Array object?
Arrays are great to store several values using only 1 variable. However, they wouldn't be so great if you couldn't
also access those values quickly and easily. Here's how it's done:
//"green" is at index position 0, "red" is at index position 1, etc.
var colors = ["green", "red", "yellow", "orange", "blue"];
var red = colors[1];
document.write(red);
Enter the code snippet above between enclosing <script> tags in an HTML page, save your work, and run the
page in the browser. You should see the word red displayed on the page.
What you did was to access the second value in the colors array by using its index position within the array
starting to count at 0.
Access all items in the array with a loop
You might have probably guessed this, but loops and arrays go together like cookies and milk. Here's how you
would access all values inside an array by looping over each of them:
//use the array from the previous example
var colors = ["green", "red", "yellow", "orange", "blue"];
//use a for loop to access each item in colors
//The array object has a length property
//that contains the size of the array: you can use it in the for loop
for (var i=0; i < colors.length; i++) {
//You use the counter i to access the index position
document.write(colors[i] + "<br />");
}
Save your file and preview the page in a browser. You should see the color names displayed on the page.
There's also a special type of for loop that you can use with the Array object, the for ... in loop. Here's how it
works:
//use the array from the previous example
var colors = ["green", "red", "yellow", "orange", "blue"];
for (color in colors) {
//color is the variable that marks the index position
document.write(colors[color] + "<br />");
}
Run the HTML document containing the code snippet above inside <script> tags in a browser. The web page
should look the same as it did in the previous example.

Once you access a value inside an array you can simply retrieve it, as you did in the previous example, or you
can modify it, as follows:
var colors = ["green", "red", "yellow", "orange", "blue"];
colors[2] = "pink";
//Now you've replaced the item at index position 2,
//the third item called "yellow",
//with "pink"
document.write(colors);
//The code should print:
//green,red,pink,orange,blue ("pink" has replaced "yellow")
Can I sort array items?
You can do amazing stuff with values stored inside an array. For example, you can sort items alphabetically, in
descending or ascending order, or numerically. Let's see how this is done.
You sort array elements with a fantastic method most appropriately called sort(). Here it is in action:
//sort the colors array alphabetically and ascending:
var colors = ["green", "red", "yellow", "orange", "blue"];
var ascendingColors = colors.sort();
//display each value
document.write(ascendingColors);
//This should print:
//blue, green, orange, red, yellow
If you want to sort numerical values inside an array, either in ascending or descending order, you need to build
a simple custom function and pass this function as argument to the sort() method. It sounds a bit harder than
it actually is. Here's how it's done:
//build a new array containing number values
var myNumbers = [4, 2, 10, 6, 9];
//build your custom function: this is a simple formula
function sortAscending(a, b) {
//the formula return a - b sorts the numbers
//from the smaller to the bigger,
//the formula return b - a sorts numbers in descending order,
//that is, from the bigger to the smaller number
return a - b;
}
//pass the sortAscending function as argument to sort()
var sortedAscending = myNumbers.sort(sortAscending);
//print result on the page
document.write(sortedAscending);
//This should print:
//2,4,6,9,10 . Now try sorting in descending order on your own.
How do I add data to the Array object?
You can add new items inside an array in different ways. Which method you choose depends largely on your
program's requirements.
Add items to the end of the array with push()
What feels more like the natural order of things, that is, adding an item to the end of an array, is easily achieved
using the push() method. Here's how it works:
//use our old colors array
var colors = ["green", "red", "yellow", "orange", "blue"];

//use push() to add the color "pink" at the end


colors.push("pink");
//print the enlarged array
document.write(colors);
//This should print: green,red,yellow,orange,blue,pink
Add items to the beginning of an array with unshift()
Use unshift() to add new items to the start index position of an array. This is easily done.
Just replace push() with unshift() in the previous example, save your work and run the page in a browser. The
page should display the color name "pink" at the very start, like so:
pink,green,red,yellow,orange,blue.
How do I remove data from the Array object?
If you want to remove the last item in an array you use pop(). If you want to remove the first item in an array
you use shift().
var colors = ["green", "red", "yellow", "orange", "blue"];
//remove "blue" from colors
colors.pop();
document.write(colors);
//This prints: green,red,yellow,orange
//remove "green" from colors
colors.shift();
document.write("<br />" + colors);
//This prints: red,yellow,orange
//on a new line break
Have fun experimenting with the examples above and come back to ourtry out challenge as soon as you're ready.
Try out: Username registration
You will build a mock Username registration program with the following requirements:
the user can enter a Username in the inputbox, and click a button to register;
if the Username already exists, the program informs the user;
if the Username is not already stored in the program, the new Username is added, the user is informed,
and all stored Usernames are displayed on the page in alphabetical order.
A real registration program would ask for more information, the data would be permanently stored in a
database, and existing Usernames would never be printed out for everybody to see.
However, this is a mock application: our Usernames are stored in a global array. This ensures that the values
inside will be accessible from any function in the script, and the newly added Usernames will be preserved for
as long as the program runs. Displaying the Usernames on the page will show the workings of the global variable
(see Lesson 4 for a refresher on global variables) as well as of the array methods push() and sort().
Enough talking, let's get coding! Prepare an HTML page with an inputbox, a button, and a paragraph to display
messages to the user. Make sure each element has an id value so that your code can have an easy handle on
them.
The HTML document
<html>
<head><title> Arrays</title>
<script type="text/javascript" src="lesson_tryout.js"></script>
</head>
<body>
<h1>Register with us</h1>
<p>Register a Username: <input type="text" id="txtName" /></p>
<p><input type="button" id="btnSubmit" value="Register" /></p>
<p id="result"></p>

</body>
</html>
The JavaScript file: tryout.js
Your program contains:
a global array called userNames used to store Usernames;
a function called init() used to bind the main function to the onclick event of the button;
and a function called registerName() that performs all the main program tasks.
//global array: it's outside any function
var userNames = ["harry potter", "donald duck", "shrek", "supercoder"];
function init() {
var myButton = document.getElementById("btnSubmit");
myButton. >}
//assign init() function to onload event
>//registerName() function: it executes when user clicks the button
function registerName() {
//set up main vars: Username entered by user,
//a message string to communicate with the user,
//a reference to the paragraph used to display the message,
//and a boolean var (true/false) used as flag:
//if the registration is successful, this is set to true,
//if registration fails, this is set to false. It's initialized as false.
//Notice how you chain getElementById(), value, and toLowerCase
//to store the value entered by the user in lowercase
var newName = document.getElementById("txtName").value.toLowerCase();
var message = "";
var result = document.getElementById("result");
var success = false;
//If the user clicks the button but the inputbox is empty
//we alert the user and stop further program execution:
if (newName == "") {
alert("Please, enter a Username");
return false;
}
//we loop over each Username stored in the array
//to make sure the Username is not already in existence
for (var i = 0; i < userNames.length; i++) {
//if we find a Username equal to the newly entered name,
//it means the Username already exists and we can't
//proceed with registration
if (userNames[i] == newName) {
message = "Sorry, the Username " + userNames[i] + " already exists. Try again";
result.innerHTML = message;
//set the success flag to false so the rest of the program knows
//that registration failed
success = false;
//stop further program execution
return false;
}
//else - if the Username entered by the user
//is not already stored in the application, register new user:
else {
message = "Great, you've successfully registered with us as " + newName;

result.innerHTML = message;
//set the success flag to true, so the program knows
//the new Username can be added
success = true;
}
}
//Now you're out of the loop
//if registration was successful (success flag is true),
//add new Username to the array with push()
if (success) {
userNames.push(newName);
}
//display Usernames sorted alphabetically on a new line
result.innerHTML += "<br />" + userNames.sort();
}
Save all your files and run the HTML document in a browser. You should see something similar to the example
page indicated by following the link above.
Try clicking the button without entering anything in the inputbox, then enter a Username already present in the
array - for example, supercoder - and try to register; finally, enter a new name and see it getting added to the
array. As you enter new names, these get added to the array and displayed alphabetically.
JavaScript Living Space - the Browser Environment
As we have seen, the JavaScript language is made up of objects, their properties and methods. Your JavaScript
code is interpreted and executed by a web browser. Therefore, JavaScript lives and comes alive in the browser
environment.
This environment, in its turn, is also present in the JavaScript language, and obviously it is so in object form.
Better yet, in the form of several objects, their properties and methods.
In this lesson you will be presented with a quick overview of the main objects making up the browser
environment.
In particular, you will learn about:
the Browser Object Model (BOM);
the Document Object Model (DOM);
accessing, adding, and removing DOM elements and attributes.
What is the Browser Object Model (BOM)?
The BOM is a a collection of objects that represent the browser and the computer screen. These objects are
accessible through the global objects window and window.screen.
The window object is global to the extent that it represents the very host environment of all other JavaScript
objects. It's so fundamental, that you've already used it without needing to invoke it explicitly.
In fact, you already used alert() and onload. You didn't need explicitly to write window.alert() because the global
window object was already presupposed.
Also, you could think about the window object as being at the top of a tree-like hierarchy of other objects,
its descendants, or children. In fact, it's quite common for programming languages to use family-related
metaphors to refer to objects representing their environment.
You will have occasion to work further with the window object through the rest of this tutorial. For now, let's
move on to the Document Object Model (DOM).

What is the Document Object Model (DOM)?


One of the most interesting children of the window object, certainly from the point of view of JavaScript, is
the Document object. This gives access to the all the elements that make up your HTML document.
The DOM is an ever evolving standard defined by the World Wide Web Consortium (W3C) implemented with
varying degrees of consistency among different kinds of browsers. It contains a wealth of properties and
methods that enable you to access and manipulate anything you can think of in an HTML document. So far
you've used document.write() to write on the HTML page, and document.getElementById() to get a hook on
an HTML element. But there's a lot more.
For example, here's all the info the document object can be made to yield when appropriately nudged. Insert
the following code inside enclosing <script> tags of an HTML page and preview its content in a browser:
//Set up your variables to represent
//bits of info about your document:
var myTitle = document.title;
var myUrl = document.URL;
var myLastModification = document.lastModified;
var myInfoString = "The title of my document is: " + myTitle + "<br />";
myInfoString += "My document's URL is: " + myUrl + "<br />";
myInfoString += "My document was last modified on: " + myLastModification;
document.write(myInfoString);
That's so cool. Let's have a look at how the HTML page is represented in the DOM.
What does a DOM representation of an HTML page look like?
The DOM represents HTML elements in a top-down tree-like structure. For instance, let's consider the following
simple HTML document:
<html>
<head>
<title>Lesson 14: DOM</title>
</head>
<body>
<p>Lorem ipsum ...</p>
<p>Lorem ipsum ...</p>
<p>link <a href="http://html.net">HTML.net</a></p>
</body>
</html>
The DOM representation of the elements in the HTML page above is as follows:
The DOM elements are also known as nodes. Familyrelated metaphors are also used to represent the
relationships and the position of each node with respect
to the others. In connection to the DOM tree graphic
above, we find:
1. The <html> node
The <html> element or node, is parent to all
other nodes. In fact, all other DOM nodes
are nested inside the <html> node;
2.

<head> and <body> nodes


Next, we find 2 elements: the <head> and the
<body>. These have a parent/child relationship
with the <html> element (the parent). Because
both are on the same level, they're siblings with
respect to each other;

3.

<title> and <p> nodes


The next level down is occupied by the <title> as child of the <head>, and 3 <p> elements as children
of the <body>. In our sample HTML page above, <title> and <p> tags are siblings when considered with
respect to each other;

4.

Text nodes
The text inside the <p> tags, and the text inside the anchor tag are called text nodes. In this case
they're children of the <p> element and the <a> element respectively;

5.

Anchor tag
The next level down is occupied by an anchor tag, which is child to one of the <p> tags.

How do I access DOM elements?


Use one of the 2 following methods of the document object to access DOM elements.
Get the DOM element by its id attribute
The most widely used method of the document object to access DOM elements is certainly our old
friend document.getElementById(elementId). This is the most appropriate way of accessing 1 HTML element at
a time.
var inputBox = document.getElementById("txtHello");
alert(inputBox);
//if you run this code in an HTML page containing
//an input element called txtHello, you should see
//[object HTMLInputElement] displayed in an alert box.
Get DOM elements by tag name
Another popular way of accessing DOM elements is by using their tag name in the HTML mark-up. This is a handy
way of grabbing all HTML elements in one go that have a tag name in common, such as images, links, list items,
etc. You can store a reference to these elements in an array and manipulate them via JavaScript.
For example, in an HTML page containing a list and 3 list items, you can access each list item and modify their
color and background-color style properties by inserting the following code in enclosing <script> tags:
//Retrieve all 3 list items and store them in an array
var listElems = document.getElementsByTagName("li");
//loop over each list item and access the style property
for (var i = 0; i < listElems.length; i++)
{
//Notice how you write backgroundColor,
//NOT background-color as you would in CSS:
listElems[i].style.backgroundColor = "red";
listElems[i].style.color = "white";
}
Run your HTML page in the browser. You should see something like the page indicated by following the example
link above.
How do I add DOM elements?
In previous lessons you used the practical and easy innerHTML property of an HTML element to add new stuff
to your web page, be it new mark-up or new text.
However, innerHTML, although widely used, has not been recognized as a standard by the W3C. The DOM
standard way to add new elements to an HTML page via JavaScript is done as follows. Enter the code below in
enclosing <script> tags inside an HTML page:
//First create a <p> element with createElement(element):
var newParagraph = document.createElement("p");
//Then add <p> to the <body> tag with appendChild():
document.body.appendChild(newParagraph);
//Now create the text that goes inside the new <p> element

//with createTextNode():
var newTextPara = document.createTextNode("Hello DOM standard");
//Finally, add the new text inside the <p> tag:
newParagraph.appendChild(newTextPara);
You can also add attributes to the newly created DOM nodes with setAttribute(attrType, attrName), and later
retrieve them with getAttribute(attrType). Using the code snippet above, you can add an id
called newParagraph to the newly created paragraph like so:
var newParagraph = document.createElement("p");
//setAttribute has 2 string arguments: the attribute we want to set
//and the name we want to apply to the attribute.
//Here we create an id attribute called newParagraph:
newParagraph.setAttribute("id", "newParagraph");
document.body.appendChild(newParagraph);
var newTextPara = document.createTextNode("Hello DOM standard");
newParagraph.appendChild(newTextPara);
//getAttribute() has one string argument: the type of attribute
//we want to retrieve:
alert("The Id of the new paragraph is: " + newParagraph.getAttribute("id"));
Save your work and preview it in a browser. You should see something like the page indicated by following the
example link above.
As you can see, there are at least 2 steps you need to take to insert fresh stuff inside an HTML page with
JavaScript:
1. create the new content: to do this you use either createElement(element) in case of an HTML tag,
or createTextNode(text) in case of new text content;
2. append the newly created DOM node to the appropriate location in the HTML document.
How do I remove DOM elements?
That's pretty simple stuff. First grab the DOM node you want to remove,
use removeChild(elementToRemove).
Prepare a simple HTML document with a <p> element and an input button like so:
<html>
<head>
<title>Delete DOM Element</title>
</head>
<body>
<h1>Delete DOM element</h1>
<p id="remove">I'm going to be removed.</p>
<input type="button" value="Delete paragraph" />
</body>
</html>

then

Note that the onclick attribute of the button element contains a call to the deleteParagraph() function. Let's
write this function inside enclosing <script> tags in the <body> of our HTML page:
function deleteParagraph()
{
//retrieve the element you want to remove:
var remove = document.getElementById("remove");
//use removeChild(elementToRemove) to delete the element
document.body.removeChild(remove);
}
Save your work, run it in a browser, and click the button. You should see something like the page indicated by
following the example link above: after you click the button the paragraph should be removed from the page.

Useful Tasks (I) Setting and Retrieving Cookies


You've come a long way in this tutorial. You're ready to look more closely at how JavaScript performs a real
world task: setting and retrieving cookies.
In this lesson, you will learn:
what a cookie is;
how you can store cookies on your website visitors' computer;
how you can retrieve the cookie and use the values stored in it on the web page.
In the process, you will have occasion to use the global escape() function, the split() method of the String object,
and the toGMTString() method of the Date object.
What's a cookie?
The values stored in JavaScript variables are destroyed as soon as the browser is closed or the page is reloaded.
Therefore, if you use an input box on your web page to store visitors' names in a variable, that value is lost as
soon as they leave the page.
A common feature present in most websites today is some sort of personalization mechanism whereby web
visitors are recognized. Some instances of this personal touch can be things like greeting returning visitors by
their name, indicating how long it's been since the last visit to the website, showing some products that might
be of interest to the user based on past purchases, etc.
As you might have guessed, we're dealing with values, and if we want to use them in our JavaScript program,
we need a storage place for them. However, all storage places examined so far are temporary. We need
something that persists in between visits to our web page.
This is where cookies enter the scene.
Cookies are strings of text containing small pieces of data about your website visitors. They are stored by the
browser in your visitors' computers. Each cookie has a name and an expiration date, and is separated from other
cookies by a semicolon ( ; ). The fact that cookies are all stored in the same place, retrieving a specific cookie out
of the collection to read its values calls for some little work on our part.
However, before we can retrieve a cookie, we need to write one and store it in the visitor's browser.
How do I set cookies with JavaScript?
Cookie data is stored in the document object's cookie property. The data is stored as "name=value" pairs, in
which the values may not contain any whitespace, commas ( , ) and semicolons ( ; ). This is why we use
the escape() method, which enables us to encode the string in Unicode format(e.g., a space is represented as
%20).
By default the lifespan of cookies is limited to the current browser session. However, by setting an expiry date
in the form of an "expires=date" pair, we can prolong the cookie's life (unless the user decides to delete the
cookies stored on her machine). The date value is a GMT string, which can be obtained by using the Date object
and its toGMTString() method.
If you insert the code snippet below inside enclosing <script> tags of an HTML page, you set a cookie
named "myCookie" on your visitor's computer, thatexpires after a minute starting from the time of its creation:
//If no cookie is present, we create one
if (! document.cookie) {
var cookieName = "Test Cookie";
//escape the string to make sure there are
//no unallowed characters
var myCookie = escape(cookieName);
//set the expiry date to 1 minute from creation date:
//get current date and add 1 minute reduced to milliseconds:
var expiryDate = new Date();
expiryDate.setTime(expiryDate.getTime() + (60 * 1000));
//create the myCookie cookie and add it

//to the cookie property of the document object:


//in name=value pairs separated by ;
document.cookie = "myCookie=" + myCookie + ";" + "expires="
+ expiryDate.toGMTString() + ";";
//leave a message to the user:
document.write("Thank you, " + cookieName + " is your cookie");
}
That's all set. The browser running a page containing the code snippet above, will store a cookie by the name
"myCookie" with a value of "Test Cookie", that expires after 1 minute.
How do I retrieve and use cookies in my web page?
Retrieving cookies to read their values requires the use of a couple of methods. First, you need to unescape the
name value that you previously escaped. This means that, if your name value contained a space, it was escaped
by replacing the space with %20. Now that you're reading the value back from the cookie name, you need to
replace %20 with a space character. This is easily done with the unescape() method.
Secondly, you need to extract each name-value pair separately from the cookie string. You do this with
the split() method of the String object.
split() is used to split a string into an array of comma ( , ) separated substrings. It takes an optional argument
called separator. This specifies the character to use for splitting the string.
The code snippet below will check if cookies are present in the cookie property of the document object. If they
are, the script extracts and displays the values of the "myCookie" cookie.
//continue from the previous code snippet
else {
var myCookieString = unescape(document.cookie);
//create a comma-separated array of substrings from the string
//containing the cookie values by using
//split() with "=" as separator.
//Remember name/value pairs in the cookie
//string are separated by an = sign:
var dataList = myCookieString.split("=");
//check that the name at index position 0 is
//"myCookie" (remember the cookie name from previous example):
if (dataList[0] === "myCookie") {
//let's extract the value of myCookie
//by using split() once again. Now the items in
//dataList array are separated by " , ".
//This will be our separator in the split() method.
//Item 1 (index 0) is the cookie name,
//item 2 (index 1) is the value, which is what we need:
var data = dataList[1].split(",");
//Now we have a new array of strings called data.
//containing only the cookie value ("Test Cookie"),
//which is at index 0. We extract it:
var cookieName = data[0];
}
//Now we display a personalized greeting
document.write("Welcome back, here's your cookie, " + cookieName);
}

Useful Tasks (II) Form Validation


A web form is a staple feature of almost any website today. Nothing can be more frustrating for your visitors
than filling out all form fields, clicking the submit button, and have the entire form come back, emptied of all
their carefully entered values, and displaying a cryptic error message expecting them to start all over again.
Any data that comes from users must be validated. This means that programs must check that no empty values
are submitted, that submitted values are of the right type and length, etc. However, such checks are necessarily
performed after the user has filled out and submitted the form to the server.
If the server is busy and takes a while before alerting the user that the form could not be accepted due to errors,
users might get quite annoyed and decide not to come back to your otherwise fantastic website.
Thankfully, this rarely happens nowadays, thanks to JavaScript. In fact, although it's crucial that checking user
input must be done on the server (e.g., php, .net, ruby, etc.), client-side JavaScript can do a lot to make the
experience less painful and time consuming.
JavaScript runs in the user's browser, therefore it executes immediately. There's no need for the form to be
submitted to the server before alerting the user that, for example, she has left one of the required fields empty.
In this lesson, you will learn how to:
make sure users fill out all required form fields;
make sure users enter a valid email.
How do I validate empty form fields?
In previous lessons you already performed some validation tasks. For example, you used isNaN() to make sure
users entered a number data type. You also checked users didn't submit an empty value by using something
like if (inputboxValue == "") { alert user...}. Let's see what else you could do to prevent users from submitting
an empty form field.
Prepare an HTML document with a form and a button, like the one below:
<html>
<head>
<title>Form validation</title>
</head>
<body>
<form id="myForm" action="#" method="post">
<fieldset>
<p><label for="txtName">First Name:</label>
<input type="text" id="txtName" name="txtName" /> </p>
<p><input type="submit" value="Submit" /></p>
</fieldset>
</form>
<script type="text/javascript">
</script>
</body>
</html>
In between <script> tags write the validate() function as follows:
function validate()
{
var userName = document.getElementById("txtName").value;
//if the length of the string value is 0,
//it means the user has entered no value:
if (name.length == 0) {
alert("Please, enter your name");
return false;

}
else {
alert("Thank you, " + userName);
}
}
Save your work and run the page in a browser. Try submitting the form leaving the inputbox empty, and see
what happens. Can you post the form? I hope not.
How do I validate email addresses?
Email addresses present a characteristic pattern. We know that they have one @ character and at least a dot (.)
character.
More detailed patterns of email addresses, as well as of domain names, zip codes, telephone numbers, etc., can
be validated using a powerful feature called regular expression. A treatment of regular expressions is beyond
the scope of this tutorial. However, if you're interested the web offers a wealth of material on the subject.
In our code snippet we use some string manipulation methods to make sure the value entered by the user has
an @ character and a dot.
<html>
<head>
<title>Form validation</title>
</head>
<body>
<form id="myForm" action="#" method="post">
<fieldset>
<p><label for="txtEmail">Email:</label>
<input type="text" id="txtEmail" name="txtEmail" />
</p>
<p><input type="submit" value="Submit" /></p>
</fieldset>
</form>
<script type="text/javascript">
</script>
</body>
</html>
Now, change the validate() function as follows:
function validate() {
var email = document.getElementById("txtEmail").value;
//still check user entered a value
if (email.length == 0) {
alert("Please, enter an email address");
return false;
}
//if the index position of the @ or . characters
//is -1 (any value bigger than this, including 0,
//means the character is present)
else if (email.indexOf("@") == -1 || email.indexOf(".") == -1) {
alert("Please, enter a valid email address");
return false;
}
//if we get here, all went well
else {
alert("Thank you");
}
}

Save your work and preview the page in a browser. Now, enter an email address with no @ character or no dot
charachter. Is your form submitting the value to the server? Hopefully, it isn't.
Try out: form validation demo
In this try out you will build a JavaScript program that checks user input (name and email) before web form
submission. Prepare an HTML page containing a form with 2 inputboxes and a button, and add a paragraph with
an id attribute called result to display messages to the user, like the one below:
<html>
<head>
<title> Form validation</title>
<script type="text/javascript" src="lesson16.js"></script>
</head>
<body>
<form id="myForm" action="#" method="post">
<fieldset>
<p><label for="txtName">Name:</label>
<input type="text" id="txtName" name="txtName" /></p>
<p><label for="txtEmail">Email:</label>
<input type="text" id="txtEmail" name="txtEmail" /></p>
<p><input type="submit" value="Submit" /></p>
</fieldset>
</form>
<p id="result"></p>
</body>
</html>
Now create the lesson.js file. This contains 5 functions:
1. init() binds the main function, validate(), to the form's onsubmit event;
2. validate() examines the results returned by functions validating required fields and email format and
displays an appropriate message;
3. validateRequired(input) checks the input box has a value. It returns true if it has and false if it hasn't;
4. validateEmail(email) checks the email is valid and returns true if it is, false if it isn't;
5. writeMessage(text) displays a message to users when something goes wrong. It would be annoying to
have alerts popping up every time an error occurs.
function init() {
var myForm = document.getElementById("myForm");
myForm. >}
/********************************/
//bind init() function to onload event >/******************************************/
//validate() checks answers from validateRequired() and validateEmail() and displays appropriate messages.
//If an error occurs program execution is stopped:
function validate() {
var name = document.getElementById("txtName").value;
var email = document.getElementById("txtEmail").value;
//validateRequired() and validateEmail() return true/false values: create variables to store the result
var isRequiredNameSet = false;
var isRequiredEmailSet = false;
var isEmailValid = false;

//create variable that holds message to display


var message = "";
isRequiredNameSet = validateRequired(name);
isRequiredEmailSet = validateRequired(email);
isEmailValid = validateEmail(email);
//if all values are valid, prepare thank you message and allow form submission
if (isRequiredNameSet && isRequiredEmailSet && isEmailValid) {
message = "Thank you, your details have been successfully posted!";
}
//if the name field is empty, write message to user and stop submission:
else if (! isRequiredNameSet) {
message = "Please, enter a name";
writeMessage(message);
return false;
}
//If the email field is empty, write message to user and stop submission:
else if (! isRequiredEmailSet) {
message = "Please, enter an email";
writeMessage(message);
return false;
}
//If the email is not in a valid format (no @ or . characters), we write a message to the user
//and stop program execution:
else if (! isEmailValid) {
message = "Please, enter a valid email";
writeMessage(message);
return false;
}
//If we are here validation is successful: display the thank you message with an alertbox:
alert(message);
}
/***********************************************/
//This function takes an argument that represents the input element and checks
//that it's not empty - it returns true if input is valid and false if input is not valid:
function validateRequired(input)
var isValid = false;
if (input.length == 0) {
isValid = false;
}
else {
isValid = true;
}
return isValid;
}

/**********************************************/
//validateEmail(email) checks the email is in valid format and returns true if it is, false if it isn't:
function validateEmail(email) {
var isValid = false;
if (email.indexOf("@") == -1 || email.indexOf(".") == -1) {
isValid = false;
}
else {
isValid = true;
}
return isValid;
}
/**********************************************/
//writeMessage(text) has the message to display to the user as argument, clears any previous
//content from the paragraph with the id of result and inserts the appropriate message for display
//using DOM compliant techniques (lesson 14):
function writeMessage(text) {
var paragraph = document.getElementById("result");
//The content inside the paragraph is the paragraph's
//first child. We check if there is any content and remove it:
if (paragraph.firstChild) {
paragraph.removeChild(paragraph.firstChild);
}
//Now we can create and append the new
//message to display to the user:
paragraph.appendChild(document.createTextNode(text));
}
Save your work and preview it in a browser. You should see something like the page indicated by following the
example link above.
Try clicking the submit button without filling out the form properly. If all goes as expected, you should not be
able to submit your form unless it's values are complete and appropriate.
Obviously, your script can't verify an email address, but it can validate its format. Finally, keep in mind that for
a detailed check of the email pattern, the best tool for the job is a regular expression.
JavaScript Timing Events
The global window object offers a few little functions that are great if you want to create the effect of movement
or of passing time on the web.
In this lesson, you will learn about:
setTimeout();
clearTimeout();
setInterval();
clearInterval().
In the process, you will also learn how to preload images with JavaScript and how to build a simple photo gallery
application.
How do I use setTimeout()?
If your program has a chunk of code that needs to be executed after a specified time,
then setTimeout(actionToExecute, timeInMilliseconds) is your function.
Let's see it in action. In this simple example, we will call up an alertbox 2 seconds after page load. Type the code
below in enclosing <script> tags on a simple HTML page:

//Package the code to insert in the timer in a simple function:


function sayHello() {
alert("Hello");
}
//Package the timer into its own function
function timeGreeting()
{
//assign the timer to a variable: you need to do this so the timer can be
//referenced by another function when you want to stop it:
var greeting = setTimeout(sayHello, 2000);
//Notice how the time is set in milliseconds.
}
//Now call the timer function
timeGreeting();
Save your work and run it in a browser. After 2 seconds, an alertbox should pop up to greet you.
How do I use setInterval()?
If you need to execute a chunk of code at specified time intervals, then setInterval(codeToExecute,
timeIntervalInMilliseconds) is your function.
To see it in action in its most annoying manifestation, just replace setTimeout with setInterval in the previous
example and you're done.
Now you should see an alertbox greeting you every 2 seconds! That's enough, just close that window in your
browser and let's modify our script so that we can put a stop to that nuisance.
How do I stop the timer?
JavaScript offers 2 handy methods to get rid of timers: clearTimeout(timerVariable) if your timer uses
setTimeOut(), and clearInterval(timerVariable) if your timer uses setInterval(). Let's put clearInterval() to good
use right away by stopping that annoying alertbox. First of all, add an inputbox to your HTML page, like so:
<input type="button" value="Stop timer" />
Next, rewrite the preceding JavaScript code and then add the new function as follows:
//Make the variable holding the timer global, so that it can be accessed both
//by the function setting the timer and by the function stopping the timer:
var greeting;
//sayHello() remains unchanged from the previous example
function sayHello() {
alert("Hello");
}
//we increase the time interval to give more time to the user to click the button that stops the alert:
function timeGreeting() {
greeting = setInterval(sayHello, 5000);
}

timeGreeting();
//package the code that cancels the timer in its own function that will be called when
//the button on the page is clicked:
function stopTimer() {
//you call clearInterval() and pass the variable containing the timer as argument
clearInterval(greeting);
}
Save your work and preview it in a browser. Just click the button and the annyoing alertbox disappears: that's
much better, great! I leave you to experiment with clearTimeout() on your own.

Short Introduction to jQuery


jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and
manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a
multitude of browsers. With a combination of versatility and extensibility, jQuery has changed the way that
millions of people write JavaScript.
Why should I use jQuery?
Here are some good reasons why using jQuery in your JavaScript projects is a great idea.
jQuery is:
extremely light-weight (just 31 kb in its latest minified and zipped production-ready version);
it's free and very easy to include in your projects: just download its latest version from the jQuery
website, or use an online Content Delivery Network;
it's continually upgraded, maintained and documented by a dedicated community of great
developers. This ensures high quality and support on the internet;
it helps overcoming inconsistencies in the way some JavaScript features are implemented across
different browsers;
and last but not least, it offers a wealth of ready-made animation effects that are a joy to use.
How do I include jQuery in my website?
Including jQuery in your project is fast and easy. You have the choice of downloading a copy of the library and
save it locally, or you can use a Content Delivery Network (CDN) to serve jQuery to your website on the Internet.

Short Introduction to JSON


JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and
write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming
Language, Standard ECMA-262 3rd Edition - December 1999. JSON is a text format that is completely language
independent but uses conventions that are familiar to programmers of the C-family of languages, including C,
C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange
language.
JSON is built on two structures:
A collection of name/value pairs. In various languages, this is realized as an object, record, struct,
dictionary, hash table, keyed list, or associative array.
An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.
These are universal data structures. Virtually all modern programming languages support them in one form or
another. It makes sense that a data format that is interchangeable with programming languages also be based
on these structures.
In JSON, they take on these forms:
An object is an unordered set of name/value pairs. An object begins with { (left brace) and ends with } (right
brace). Each name is followed by : (colon) and the name/value pairs are separated by , (comma).

An array is an ordered collection of values. An array begins with [ (left bracket) and ends with ] (right bracket).
Values are separated by , (comma).

A value can be a string in double quotes, or a number, or true or false or null, or an object or an array. These
structures can be nested.

A string is a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes.
A character is represented as a single character string. A string is very much like a C or Java string.

A number is very much like a C or Java number, except that the octal and hexadecimal formats are not used.

Whitespace can be inserted between any pair of tokens. Excepting a few encoding details, that completely
describes the language.

Some Queries on JavaScript?


9 reasons why CSS tableless design performs better than traditional table based web design and why it has
become the preferred method of modern web design:
1. CSS tableless design allows web designers the possibility to make more complex layouts and designs when
producing a website. With table based layouts, web designers are confined to creating layouts that can be rigid,
inflexible, and based on grids. CSS tableless based layouts, on the other hand, allow the designer to be as creative
as their imagination allows them to be.
2. If your intention is to improve search engine rankings for your website, then a CSS tableless design will help
your cause. CSS tableless designs result in smaller web page file sizes, a reduction in the ratio of code to content,
and the elimination of the extraneous junk HTML markup that many table based web editors use. This makes
it easier for search engine spiders to crawl through your website and results in a more favorable ranking in search
engines.
3. By using CSS style sheets it is extremely easy to maintain visual consistency throughout your website. When
using table based layouts, it is easy to lose this consistency because each web pages style, layout, and design
are frequently hard-coded individually into every page. If you need to make a change to your website across all
pages, youll have to change the code on each individual page. With CSS, all pages can use the same CSS
document for their layout and styles. If you change a property in the CSS file, the changes will be instantaneously
reflected across all pages of your website.
4. Updating a CSS tableless website is easier and less time consuming than compared to table based designs. For
example, if you want to change font sizes and colors within your website, your external CSS file can be simply
opened and the necessary changes made without making the change on each and every page of your website.
To change the look of your website for special or seasonal promotions, the entire website look and feel can
be completely altered simply by changing properties in the CSS file without touching the HTML code of the web
page.
5. Redesigning a website using CSS tableless design is faster and less expensive than redesigning a website using
table based design. This is because CSS tableless designs have separate files for content and visual data including
web page structure whereas table based designs mix layout information with content in the same file. By
separating the visual data and layout from the content, a web designer is able to quickly and easily make changes
across the entire website.
6. Table web page designs rely heavily on the use of spacer .gifs, a transparent image used to control blank space
within a table based web page. Having to create a series of custom sized transparent images to organize your
web page layout creates messy code and a rigid page structure that cant be easily changed. CSS tableless design
eliminates this problem by using DIVs instead of tables which can be easily resized, positioned anywhere on a
page, or even dynamically manipulated through the use of scripting languages.
7. A common advantage of using CSS tableless web design is a reduction in web page file size which equates to
your web pages loading faster. When compared to a CSS tableless layout, a table based web page frequently
takes twice as long to load. Also, the amount of bandwidth you will save using a CSS tableless based approach,
especially as your website grows in size, can be vast resulting in a faster overall loading website while saving you
money.
8. Using CSS tableless web design makes your website more accessible by making content consumption and site
navigation easier for users. Youll also do a much better job of accommodating those with visual impairments
and other disabilities. Screen readers, Braille devices, and special browsers for the impaired have fewer
problems with tableless designs because they can control the CSS file making font sizes larger, or even modify
the web page structure to make it easier to read.
9. CSS enables the web designer to attach multiple style sheets for different media types. If a potential customer
visits your site with her Blackberry or mobile phone, a different CSS style sheet is called which dictates a

completely different layout and styling for your entire website formatting it for optimal viewing on the small
screen of the device.
Garbage Collection in JavaScript
"In computer science, garbage collection (GC) is a form of automatic memory management. The garbage
collector, or just collector, attempts to reclaim garbage, or memory used by objects that will never be accessed
or mutated again by the application."
Javascript garbage collection may differ between browser implementations, but basic foundation is the same.
1. All variables defined in a function scope, get trashed the moment the function completes execution.
2. No global variables get recycled, even if not being used by any function, therefore, avoid them like the
plague, they add to namespace pollution.
3. Anonymous functions passed as an argument, disappear the moment they are executed.

Lexical Structure of JavaScript


This is a set of elementary rules that specify how you write programs in a language.
1. Case Sensitivity
While HTML tags are not case sensitive, JavaScript code is case sensitive.
2. White Space and Line Breaks
JavaScript ignores spaces, tabs, and new lines that appear between tokens in programs, except those
that are a part of string constraints. A token is a keyword, variable name, number, function name, or some
other entity in which you would obviously not want to insert a space or line break. The token 123 is one token,
where 12 3 becomes two tokens and may result in an error.
3. Semicolons
Semicolons are used to separate statement from each other. They can be omitted if the statements
are placed on a separate line. Omitting semicolons is not a good practice, you should get used to using them.
4. Comments
Any text between a // and the end of a line is treated as a comment and ignored by JavaScript. Also,
any text between the characters /* and */ is treated as a comment. JavaScript will recognize HTML comment
structure of <!-- -->.
5. Literals
Literals are data values that appear directly in a program
12
1.2
Hello world
Hi
true
Value Types
Number
String
Boolean
Null
Object
Function
Operators
X+Y (numeric)
X+Y (string)
X-Y
X*Y
X/Y
X%Y
X++, ++X
X--, --X
-X

any numeric value


characters inside of quote marks
True or False
empty or Meaningless
any value associated with the object
value returned by a function
Adds x and y together
Concatenates x and y together
Subtracts y from x
Multiplies x and y together
Divides x by y
Modulus of x and y (the remainder when x is divided by y)
Adds one to x
Subtracts one from x
Reverses the sign of x

Assignments
X=Y
Sets x to the value of y
X+ =Y
Same as x = x+y
X- =Y
Same as x = x-y
X* =Y
Same as x = x*y
X/ =Y
Same as x = x/y
X% =Y
Same as x = x%y
Comparisons
X= =Y
Returns true if x and y are equal
X! =Y
Returns true if x and y are not equal
X>Y
Returns true if x is greater than y
X > =Y
Returns true if x is greater than or equal to y
X<Y
Returns true if x is less than y
X < =Y
Returns true if x is less than or equal to y
X && Y
Returns true if both x and y are true
X||Y
Returns true if either x or y is true
!X
Returns true if x is false
6. Identifiers
An identifier is simply a name. They are used to name variables and functions. The first character
must be an ASCII letter (upper or lower case), an underscore (_) or a dollar sign ($). Subsequent characters may
be any letter, digit, underscore, or dollar sign.
i
my_variable_name
v13
_dummy
$str
7. Reserve Words
There are a number of words in JavaScript that cannot be used as (identifiers) variable names,
function names, and loop labels. These key words have a special meaning to JavaScript.
break
do
function
null
typeof
case
else
if
return
var
continue
export
import
switch
void
default
false
in
this
while
delete
for
new
true
with
These words are not used in JavaScript but are reserved for future use.
Catch
const
enum
finally
Class
debugger
extends
super
These are Java keywords that in the future maybe used in JavaScript
abstract
final
int
private
boolean
float
interface
protected
byte
goto
long
public
char
implements
native
short
double
instanceof
package
static

throw
try

synchronized
throws
transient

These are other to avoid. They are the names of properties, methods, and constructors.
alert
escape
Math
parseFloat
setTimeout
arguments
eval
menubar
parseInt
status
Array
find
moveBy
personalbar
statusbar
blur
focus
moveTo
print
stop
Boolean
frames
name
prompt
String
callee
Fuction
NaN
prototype
toolbar
caller
history
netscape
RegExp
top
captureEvents home
Number
releaseEvents
toSrting
clearInterval
Infinity
Object
resizeBy
unescape
clearTimeout
innerHeight
open
resizeTo
unwatch

close
innerwidth
opener
routeEvent
valueOf
closed
isFinite
outerHeight
scroll
watch
confirm
isNaN
outerWidth
scrollbars
window
constructor
java
Packages
scrollBy
Date
length
pageXOffset
scrollTo
defaultStatus
location
pageYOffset
self
document
locationbar
parent
setInterval
8. Special Symbols
Curly Brackets { }
These are used to combine a number of statements into a statement block. The statement
block acts as a single statement and can be placed anywhere that JavaScript expects a single
statement.
Quotes Single and Double
Single quotes can be placed inside of double quotes and double quotes can be placed inside
of single quotes. HTML tags incorporate a heavy use of double quotes. So, it is go practice to
use single quotes around your JavaScript stings.
Square Brackets [ ]
These are used to access the elements of an array
9. Objects
These are a collection of named pieces of data. The named values are referred to as properties of an
object.
10. Arrays
These are a collection of numbered pieces of data.

JavaScript constructors, prototypes, and the `new` keyword


The new operator creates a new object based on a constructor and a prototype.
The constructor is a function matching the name of the object, and, when called by the new operator, has the
keyword this assigned to the newly created instance of the object. The constructor can then assign any initial
variables as required.
function CoinObject() {
this.value = 0;
}
slug = new CoinObject(); // Creates a "slug" - a valueless coin (slug.value = 0).
The constructor can accept parameters - however, it is not possible to overload the constructors by having
multiple functions with a different number of parameters.
A prototype for an object is the set of auto-created fields and methods. It cannot operate by itself, and relies
on an existing constructor.
When the object is created, the fields initialized in the prototype are copied to the newly created object.
function CoinObject() {
this.value = 0;
}
CoinObject.prototype.diameter = 1;
slug = new CoinObject(); // A valueless coin (slug.value = 0), with diameter of 1 (slug.diameter = 1)
Since the prototype of an object behaves as an object, you can use this to create inheritance.

Methods vs. Functions


Some times it seems that functions and methods are one and the same. Technically they are in JavaScript,
because all functions belong to some object. However, methods that can be called without an object-dot prefix

(object.) are considered to be functions. As such, they are part of the global namespace. In fact, all global
functions are owned by the Window object, but it doesn't require the object-dot prefix. To put it to the test,
take any global function that you can think of, like alert(), isNaN(), or eval() and prepend the 'window.' object
identifier to it:
alert('hi there.'); window.alert('hi there.'); //still works
isNaN('test'); //returns true
window.isNaN('test'); //still returns true
eval("isNaN('test');"); //also returns true!
window.eval("window.isNaN('test');"); //true as well

Objects in JavaScript
JavaScript is an object oriented language. However, in practice objects defined by the programmer himself are
rarely used, except in complex DOM API's. Of course such standard objects as window and document and their
numerous offspring are very important, but they are defined by the browser, not by the programmer.
Since the only other programming languages I know are Commodore 64 Basic (which is not object oriented, to
put it mildly) and Perl (which doesn't need to be object oriented) and since I don't have any formal training in
programming I cannot write a general introduction to objects and object oriented programming. Therefore a
quick overview will have to suffice.

Methods and properties


In JavaScript you can define your own objects. In addition, you can assign methods and properties to each object,
pre-written or self-defined.
Methods are 'things that do something', they can be recognized by their brackets (). When you call
them, like object.method(), something happens.
Properties are 'things that are something'. They have a value, for instance a number, a string or a
Boolean value. When you call them, like object.property, you get (or set) this value.
Normal JavaScript functions are also methods (hence the brackets). If you do
document.write('text')
You execute the pre-defined write() method of the document object. If you write your own functions you add
methods to the window object, the parent of all other JavaScript objects.
Likewise, if you ask for the innerHeight of a page, you access a property of the window object and if you define
a variable of your own you really add a new property to the window object.
So you already use methods and properties in everyday JavaScripting. Since most of these are preprogrammed
functions and variables, you usually don't need to worry about the objects themselves, they're just a kind of
'black boxes' that contain useful stuff. The methods and properties (functions and variables) that you define
yourself are usually added to the window object.

Defining an object and properties


But now we want to create an object of our own. This is simple:
var theStatus = new Object;
Now we have initialized our theStatus object and we can start adding properties (in this example we don't need
methods). What we want is to create one property for each image on the page. We could do
theStatus.Home = 'normal';
Now we have added a new property Home to our object and set its value to the string 'normal'. (Remember that
JavaScript is case sensitive, so the property home does not exist, only Home.)

All this is very useful, but using this notation we encounter problems later on. Suppose we want to create a
property of theStatus for each image on the page. The property should have the same name as the image and
its value should be 'normal'.
We cannot do:
var x = document.images;
for (var i=0;i<x.length;i++) {
var theName = x[i].name;
theStatus.theName = 'normal';
}
We go through the entire images array of the page, take the name of each image and then try to create a new
property with the same name. But the code above doesn't work. Each time you do
theStatus.theName = 'normal';
JavaScript faithfully creates a new property named theName and sets its value to 'normal'. After executing this
script you have only one property theName. This is not what we want, we want one property for each image.

Associative arrays
So we have to use one of JavaScript's minor mysteries. In JavaScript, objects are also associative arrays (or
hashes). That is, the property
theStatus.Home
can also be read or written by calling
theStatus['Home']
Thus, you can access each property by entering the name of the property as a string into this array. Such an
array associates each key with a value (in this case the key Home is associated with the value normal). In the Perl
programming language it is also called a hash.
Unlike Perl, which requires you to create such an associative array explicitly, JavaScript automatically creates a
associative array for each object.
You see this behaviour with common objects like a form. You can access a form by performing either of these
DOM calls:
document.forms['theForm']
document.forms.theForm
(You can also use document.theForm but that's a special case, not regular behaviour of JavaScript
objects/associative arrays).
So when we want to set the status of each image to 'normal' in our object, we do
var x = document.images;
for (var i=0;i<x.length;i++) {
var theName = x[i].name;
theStatus[theName] = 'normal';
}
and it works. Now theName (a string) is put into the brackets [] where a string is expected. So you create a new
key/value pair, which is the same as a new property with a value.
All this is JavaScript magic at its fullest. I don't completely understand what I'm doing either, but it works just
fine. Basically you now have the power to let one name or string refer to another one.

for (var i in object)


for (var i in object) is equivalent to Perl foreach $key (keys %hash).
Just as you can go through each element of a normal array by
var x = [the array];
for (var i = 0;i<x.length;i++) {
do something with x[i]

}
you can also go through each element of an associative array. Suppose you want to go through the status values
of all images. If the status of the image is 'mouseover' you want to call a function callFn() and pass the image
name to it. You can of course tediously write out everything:
if (theStatus.Home == 'mouseover')
callFn('Home'):
if (theStatus.Place == 'mouseover')
callFn('Place'):
etc.
or
if (theStatus['Home'] == 'mouseover')
callFn('Home'):
if (theStatus['Place'] == 'mouseover')
callFn('Place'):
etc.
But this quickly leads to immense scripts. Besides, if you rename an image later on you also have to change a
line of code and of course you forget, so you get errors etc.
Fortunately JavaScript has the for/in statement which is meant exactly for this situation. If you do
for (var i in theStatus) {
if (theStatus[i] == 'mouseover')
callFn(i)
}
you go through all properties of the theStatus object (= all keys in the associative array theStatus). The variable
i succesively becomes the name of each property of the object (key of the associative array) so you can do
something with theStatus[i] and it is done to each property. In this case, if an image status has the value
'mouseover' you call callFn() and pass it the key (the name of the image).

HTML IN BRIEF
Root element
Element Description
<html> Represents the root of an HTML or XHTML document. All other elements must be descendants of
this element. (This also is the root elements.)
Document metadata
Element Description
<head> Represents a collection of metadata about the document, including links to, or definitions of, scripts
and style sheets.
<title> Defines the title of the document, shown in a browser's title bar or on the page's tab. It can only
contain text and any contained tags are not interpreted.
<base> Defines the base URL for relative URLs in the page.
<link> Used to link JavaScript and external CSS with the current HTML document.
<meta> Defines metadata that can't be defined using another HTML element.
<style> Used to write inline CSS.
Sections
Element
<body>
<section>
<nav>
<article>

Description
Represents the main content of an HTML document. There is only one <body> element in a
document.
Defines a section in a document.
Defines a section that contains only navigation links.
Defines self-contained content that could exist independently of the rest of the content.

<aside>
<h1> - <h6>

<header>
<footer>
<address>
<main>

Defines some content loosely related to the page content. If it is removed, the remaining
content still makes sense.
Heading elements implement six levels of document headings; <h1> is the most important
and <h6> is the least. A heading element briefly describes the topic of the section it
introduces.
Defines the header of a page or section. It often contains a logo, the title of the Web site,
and a navigational table of content.
Defines the footer for a page or section. It often contains a copyright notice, some links to
legal information, or addresses to give feedback.
Defines a section containing contact information.
Defines the main or important content in the document. There is only one <main> element in
the document.

Grouping content
Element
Description
<p>
Defines a portion that should be displayed as a paragraph.
<hr>
Represents a thematic break between paragraphs of a section or article or any longer content.
<pre>
Indicates that its content is preformatted and that this format must be preserved.
<blockquote> Represents a content that is quoted from another source.
<ol>
Defines an ordered list of items.
<ul>
Defines an unordered list of items.
<li>
Defines a item of an enumeration list.
<dl>
Defines a definition list, that is, a list of terms and their associated definitions.
<dt>
Represents a term defined by the next <dd>.
<dd>
Represents the definition of the terms immediately listed before it.
<figure>
Represents a figure illustrated as part of the document.
<figcaption> Represents the legend of a figure.
<div>
Represents a generic container with no special meaning.
Text-level semantics
Element
Description
<a>
Represents a hyperlink, linking to another resource.
<em>
Represents emphasized text, like a stress accent.
<strong>
Represents especially important text.
<small>
Represents a side comment, that is, text like a disclaimer or a copyright, which is not essential to
the comprehension of the document.
<s>
Represents content that is no longer accurate or relevant.
<cite>
Represents the title of a work.
<q>
Represents an inline quotation.
<dfn>
Represents a term whose definition is contained in its nearest ancestor content.
<abbr>
Represents an abbreviation or an acronym; the expansion of the abbreviation can be
represented in the title attribute.
<data>
Associates to its content a machine-readable equivalent. (This element is only in the WHATWG
version of the HTML standard, and not in the W3C version of HTML5).
<time>
Represents a date and time value; the machine-readable equivalent can be represented in the
datetime attribute.
<code>
Represents computer code.
<var>
Represents a variable, that is, an actual mathematical expression or programming context, an
identifier representing a constant, a symbol identifying a physical quantity, a function
parameter, or a mere placeholder in prose.
<samp>
Represents the output of a program or a computer.
<kbd>
Represents user input, often from the keyboard, but not necessarily; it may represent other
input, like transcribed voice commands.
<sub>,<sup> Represent a subscript, or a superscript.
<i>
Represents some text in an alternate voice or mood, or at least of different quality, such as a
taxonomic designation, a technical term, an idiomatic phrase, a thought, or a ship name.

<b>
<u>
<mark>
<ruby>

<rt>
<rp>
<bdi>
<bdo>
<span>

<br>
<wbr>

Represents a text which to which attention is drawn for utilitarian purposes. It doesn't convey
extra importance and doesn't imply an alternate voice.
Represents a non-textual annotation for which the conventional presentation is underlining,
such labeling the text as being misspelt or labeling a proper name in Chinese text.
Represents text highlighted for reference purposes, which is for its relevance in another context.
Represents content to be marked with ruby annotations, short runs of text presented alongside
the text. This is often used in conjunction with East Asian language where the annotations act as
a guide for pronunciation, like the Japanese furigana.
Represents the text of a ruby annotation.
Represents parenthesis around a ruby annotation, used to display the annotation in an alternate
way by browsers not supporting the standard display for annotations.
Represents text that must be isolated from its surrounding for bidirectional text formatting. It
allows embedding a span of text with a different, or unknown, directionality.
Represents the directionality of its children, in order to explicitly override the Unicode
bidirectional algorithm.
Represents text with no specific meaning. This has to be used when no other text-semantic
element conveys an adequate meaning, which, in this case, is often brought by global attributes
like class, lang, or dir.
Represents a line break.
Represents a line break opportunity, which is a suggested point for wrapping text in order to
improve readability of text split on several lines.

Edits
Element Description
<ins>
Defines an addition to the document.
<del>
Defines a removal from the document.
Embedded content
Element
Description
<img>
Represents an image .
<iframe>
Represents a nested browsing context , that is an embedded HTML document.
<embed>
Represents a integration point for an external, often non-HTML, application or interactive
content.
<object>
Represents an external resource , which is treated as an image, an HTML sub-document, or an
external resource to be processed by a plug-in.
<param>
Defines parameters for use by plug-ins invoked by <object> elements.
<video>
Represents a video , and its associated audio files and captions, with the necessary interface
to play it.
<audio>
Represents a sound , or an audio stream .
<source>
Allows authors to specify alternative media resources for media elements like <video> or
<audio>.
<track>
Allows authors to specify timed text track for media elements like <video> or <audio>.
<canvas>
Represents a bitmap area that scripts can be used to render graphics, like graphs, game
graphics, or any visual images on the fly.
<map>
In conjunction with <area>, defines an image map .
<area>
In conjunction with <map>, defines an image map .
<svg>
Defines an embedded vectorial image .
<math>
Defines a mathematical formula .
Tabular data
Element
Description
<table>
Represents data with more than one dimension .
<caption> Represents the title of a table .
<colgroup> Represents a set of one or more columns of a table.
<col>
Represents a column of a table.
<tbody>
Represents the block of rows that describes the concrete data of a table.
<thead>
Represents the block of rows that describes the column labels of a table.

<tfoot>
<tr>
<td>
<th>

Represents the block of rows that describes the column summaries of a table.
Represents a row of cells in a table.
Represents a data cell in a table.
Represents a header cell in a table.

Forms
Element
<form>
<fieldset>
<legend>
<label>
<input>
<button>
<select>
<datalist>
<optgroup>
<option>
<textarea>
<keygen>
<output>
<progress>
<meter>

Description
Represents a form , consisting of controls, that can be submitted to a server for processing.
Represents a set of controls .
Represents the caption for a <fieldset>.
Represents the caption of a form control.
Represents a typed data field allowing the user to edit the data.
Represents a button .
Represents a control allowing selection among a set of options .
Represents a set of predefined options for other controls.
Represents a set of options , logically grouped.
Represents an option in a <select> element, or a suggestion of a <datalist> element.
Represents a multiline text edit control .
Represents a key-pair generator control .
Represents the result of a calculation .
Represents the completion progress of a task.
Represents a scalar measurement (or a fractional value), within a known range.

Interactive elements
Element
Description
<details>
Represents a widget from which the user can obtain additional information or controls.
<summary>
Represents a summary , caption , or legend for a given <details>.
<menuitem>
Represents a command that the user can invoke.
<menu>
Represents a list of commands .
Link
The HTML <link> Element specifies relationships between the current document and other documents. Possible
uses for this element include defining a relational framework for navigation and linking the document to a style
sheet.
To include a stylesheet in a page, use the following syntax:
<link href="style.css" rel="stylesheet" type="text/css" media="all">
You can also specify alternative style sheets.
<link href="default.css" rel="stylesheet" type="text/css" title="Default Style">
<link href="fancy.css" rel="alternate stylesheet" type="text/css" title="Fancy">
<link href="basic.css" rel="alternate stylesheet" type="text/css" title="Basic">
The user can choose which style sheet to use by choosing it from the View>Page Style menu. This provides a way
for users to see multiple versions of a page.
A <link> tag can occur only in the head element; however, there can be multiple occurrences of
<link>.
HTML 3.2 defines only the href, rel, rev, and title attributes for the link element.
HTML 2 defines the href, methods, rel, rev, title, and urn attributes for the <link> element. The
methods and urn attributes were later removed from the specifications.
The HTML and XHTML specifications define event handlers for the <link> element, but it is unclear
how they would be used.
Under XHTML 1.0, empty elements such as <link> require a trailing slash: <link />.

You might also like