HTML
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
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
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
Default
Depr.
abbr
TD, TH
%Text;
#IMPLIED
acceptcharset
FORM
%Charsets;
#IMPLIED
accept
FORM, INPUT
%ContentTypes;
#IMPLIED
accesskey
#IMPLIED
action
FORM
%URI;
#REQUIRED
align
CAPTION
%CAlign;
#IMPLIED
align
#IMPLIED
align
LEGEND
%LAlign;
#IMPLIED
align
TABLE
%TAlign;
#IMPLIED
align
HR
align
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
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
#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
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
(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
#IMPLIED
onchange
#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
#IMPLIED
#IMPLIED
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
#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
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
#IMPLIED
target
%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
valign
value
INPUT
%Text;
%URI;
CDATA
#IMPLIED
#IMPLIED
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
%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
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
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>
<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 [email protected]:</h3>
<form action="MAILTO:[email protected]" 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>
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"
ondrop="drop(event)"
ondragover="allowDrop(event)"></div>
<img id="drag1" src="img_logo.gif" draggable="true" ondragstart="drag(event)" 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
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>
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
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>
park
in
Disney
World,
Florida.</p>
<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 onclick="clickCounter()" 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 onclick="clickCounter()" 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 onclick="getDateTime()">Get 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:
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
#id
#firstname
element
element,element
div,p
element element
div p
element>element
div>p
element+element
div+p
Selects all <p> elements that are placed immediately after <div> elements
[attribute]
[target]
[attribute=value]
[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
:visited
a:visited
:active
a:active
:hover
a:hover
:focus
input:focus
:first-letter
p:first-letter
:first-line
p:first-line
:first-child
p:first-child
Selects every <p> element that is the first child of its parent
:before
p:before
:after
p:after
:lang(language)
p:lang(it)
Selects every <p> element with a lang attribute value starting with "it"
element1~element2
p~ul
[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
: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
:disabled
input:disabled
:checked
input:checked
:not(selector)
:not(p)
::selection
::selection
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
pc
px
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.
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)
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;
}
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
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:
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;
}
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.
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.
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" onclick="alert('Going 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;
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" onclick="showDate();" />
</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.
</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.onclick = getAnswer;
}
//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
onload = init;
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.
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>
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.onclick = displaySquare;
}
//Bind the init() function to the onload event
onload = init;
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";
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"];
</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.onclick = registerName;
}
//assign init() function to onload event
onload = init;
//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).
3.
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.
//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" onclick="deleteParagraph()" />
</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.
}
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" onclick="validate()" /></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.onsubmit = validate;
}
/********************************/
//bind init() function to onload event onload = init;
/******************************************/
//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;
/**********************************************/
//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:
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.
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.
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.
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.
(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.
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.
}
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 />.