You are on page 1of 80

1

2
What is HTML?
HTML is a language for describing web pages.
HTML stands for Hyper Text Markup Language
HTML is a markup language
A markup language is a set of markup tags
The tags describe document content
HTML documents contain HTML tags and plain text
HTML documents are also called web pages

HTML Tags
HTML markup tags are usually called HTML tags
HTML tags are keywords (tag names) surrounded by angle brackets like <html>
HTML tags normally come in pairs like <b> and </b>
The first tag in a pair is the start tag, the second tag is the end tag
The end tag is written like the start tag, with a forward slash before the tag name
Start and end tags are also called opening tags and closing tags
<tagname>content</tagname>


HTML Elements
"HTML tags" and "HTML elements" are often used to describe the same thing.
But strictly speaking, an HTML element is everything between the start tag and the end tag,
including the tags:
HTML Element:
<p>This is a paragraph.</p>


Web Browsers
The purpose of a web browser (such as Google Chrome, Internet Explorer, Firefox, Safari) is
to read HTML documents and display them as web pages. The browser does not display the
HTML tags, but uses the tags to interpret the content of the page:

3


HTML Page Structure
Below is a visualization of an HTML page structure:
<html>
<body>
<h1>This a Heading</h1>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
</body>
</html>


HTML Versions
Since the early days of the web, there have been many versions of HTML:
Version Year
HTML 1991
HTML+ 1993
HTML 2.0 1995
HTML 3.2 1997
HTML 4.01 1999
XHTML 1.0 2000
HTML5 2012
XHTML5 2013

4


The <!DOCTYPE> Declaration
The <!DOCTYPE> declaration helps the browser to display a web page correctly.
There are many different documents on the web, and a browser can only display an HTML
page 100% correctly if it knows the HTML type and version used.

Common Declarations
HTML5
<!DOCTYPE html>

Writing HTML Using Notepad or TextEdit
Step 1: Start Notepad
To start Notepad go to:
Start
All Programs
Accessories
Notepad

Step 2: Edit Your HTML with Notepad
Type your HTML code into your Notepad:


5
Step 3: Save Your HTML
Select Save as.. in Notepad's file menu.
When you save an HTML file, you can use either the .htm or the .html file extension. There is
no difference, it is entirely up to you.
Save the file in a folder that is easy to remember, like w3schools.

Step 4: Run the HTML in Your Browser
Start your web browser and open your html file from the File, Open menu, or just browse the
folder and double-click your HTML file.
The result should look much like this:

The HTML <head> Element
The <head> element is a container for all the head elements. Elements inside <head> can
include scripts, instruct the browser where to find style sheets, provide meta information, and
more.
The following tags can be added to the head section: <title>, <style>, <meta>, <link>,
<script>, <noscript>, and <base>.



6
The HTML <title> Element
The <title> tag defines the title of the document.
The <title> element is required in all HTML/XHTML documents.
The <title> element:
defines a title in the browser toolbar
provides a title for the page when it is added to favorites
displays a title for the page in search-engine results
A simplified HTML document:
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
</head>

<body>
The content of the document......
</body>

</html>

HTML Headings
HTML headings are defined with the <h1> to <h6> tags.
Example
<h1>This is a heading</h1>
<h2>This is a heading</h2>
<h3>This is a heading</h3>
HTML Elements
An HTML element is everything from the start tag to the end tag:
Start tag * Element content End tag *
<p> This is a paragraph </p>
<a href="default.htm"> This is a link </a>
<br>
* The start tag is often called the opening tag. The end tag is often called the closing tag.


7
HTML Element Syntax
An HTML element starts with a start tag / opening tag
An HTML element ends with an end tag / closing tag
The element content is everything between the start and the end tag
Some HTML elements have empty content
Empty elements are closed in the start tag
Most HTML elements can have attributes

Don't Forget the End Tag
Some HTML elements might display correctly even if you forget the end tag:
<p>This is a paragraph
<p>This is a paragraph
The example above works in most browsers, because the closing tag is considered optional.
Never rely on this. Many HTML elements will produce unexpected results and/or errors if
you forget the end tag .

Empty HTML Elements
HTML elements with no content are called empty elements.
<br> is an empty element without a closing tag (the <br> tag defines a line break).

HTML Tip: Use Lowercase Tags
HTML tags are not case sensitive: <P> means the same as <p>. Many web sites use
uppercase HTML tags.
HTML Document Example
<!DOCTYPE html>
<html>

<body>
<p>This is my first paragraph.</p>
</body>

</html>
The example above contains 3 HTML elements.

8
HTML Example Explained
The <p> element:
<p>This is my first paragraph.</p>
The <p> element defines a paragraph in the HTML document.
The element has a start tag <p> and an end tag </p>.
The element content is: This is my first paragraph.
The <body> element:
<body>
<p>This is my first paragraph.</p>
</body>
The <body> element defines the body of the HTML document.
The element has a start tag <body> and an end tag </body>.
The element content is another HTML element (a p element).

Styling HTML with CSS
CSS was introduced together with HTML 4, to provide a better way to style HTML elements.
CSS can be added to HTML in the following ways:
Inline - using the style attribute in HTML elements
Internal - using the <style> element in the <head> section
External - using an external CSS file
The preferred way to add CSS to HTML, is to put CSS syntax in separate CSS files.
However, in this HTML tutorial we will introduce you to CSS using the style attribute. This
is done to simplify the examples. It also makes it easier for you to edit the code and try it
yourself.

Inline Styles
An inline style can be used if a unique style is to be applied to one single occurrence of an
element.
To use inline styles, use the style attribute in the relevant tag. The style attribute can contain
any CSS property. The example below shows how to change the text color and the left
margin of a paragraph:
<p style="color:blue;margin-left:20px;">This is a paragraph.</p>

9

HTML Style Example - Background Color
The background-color property defines the background color for an element:
Example
<!DOCTYPE html>
<html>

<body style="background-color:yellow;">
<h2 style="background-color:red;">This is a heading</h2>
<p style="background-color:green;">This is a paragraph.</p>
</body>

</html>

HTML Style Example - Font, Color and Size
The font-family, color, and font-size properties defines the font, color, and size of the text in
an element:
Example
<!DOCTYPE html>
<html>

<body>
<h1 style="font-family:verdana;">A heading</h1>
<p style="font-family:arial;color:red;font-size:20px;">A paragraph.</p>
</body>

</html>

The font-family, color, and font-size properties make the old <font> tag obsolete.



10
HTML Style Example - Text Alignment
The text-align property specifies the horizontal alignment of text in an element:
Example
<!DOCTYPE html>
<html>

<body>
<h1 style="text-align:center;">Center-aligned heading</h1>
<p>This is a paragraph.</p>
</body>

</html>

The text-align property makes the old <center> tag obsolete.

Internal Style Sheet
An internal style sheet can be used if one single document has a unique style. Internal styles
are defined in the <head> section of an HTML page, by using the <style> tag, like this:
<head>
<style type="text/css">
body {background-color:yellow;}
p {color:blue;}
</style>
</head>

HTML Style Tags
Tag Description
<style> Defines style information for a document
<link> Defines the relationship between a document and an external resource


Deprecated Tags and Attributes
In HTML 4, several tags and attributes were used to style documents. These tags are not
supported in er versions of HTML.
Avoid using the elements: <font>, <center>, and <strike>, and the attributes: color and
bgcolor.

11

HTML Paragraphs
HTML paragraphs are defined with the <p> tag.
Example
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
HTML Links
HTML links are defined with the <a> tag.
Example
<a href="http://www.restarttechnologies.com">This is a link</a>
HTML Images - The <img> Tag and the Src Attribute
In HTML, images are defined with the <img> tag.
The <img> tag is empty, which means that it contains attributes only, and has no closing tag.
To display an image on a page, you need to use the src attribute. Src stands for "source". The
value of the src attribute is the URL of the image you want to display.
Syntax for defining an image:
<img src="url" alt="some_text">
The URL points to the location where the image is stored. An image named "boat.gif",
located in the "images" directory on "www.w3schools.com" has the URL:
http://www.w3schools.com/images/boat.gif.
The browser displays the image where the <img> tag occurs in the document. If you put an
image tag between two paragraphs, the browser shows the first paragraph, then the image,
and then the second paragraph.

HTML Images - The Alt Attribute
The required alt attribute specifies an alternate text for an image, if the image cannot be
displayed.
The value of the alt attribute is an author-defined text:

12
<img src="boat.gif" alt="Big Boat">
The alt attribute provides alternative information for an image if a user for some reason
cannot view it (because of slow connection, an error in the src attribute, or if the user uses a
screen reader).

HTML Images - Set Height and Width of an Image
The height and width attributes are used to specify the height and width of an image.
The attribute values are specified in pixels by default:
<img src="pulpit.jpg" alt="Pulpit rock" width="304" height="228">
Tip: It is a good practice to specify both the height and width attributes for an image. If these
attributes are set, the space required for the image is reserved when the page is loaded.
However, without these attributes, the browser does not know the size of the image. The
effect will be that the page layout will change during loading (while the images load).
HTML Tables
Tables are defined with the <table> tag.
A table is divided into rows (with the <tr> tag), and each row is divided into data cells (with
the <td> tag). td stands for "table data," and holds the content of a data cell. A <td> tag can
contain text, links, images, lists, forms, other tables, etc.
Table Example
<table border="1">
<tr>
<td>row 1, cell 1</td>
<td>row 1, cell 2</td>
</tr>
<tr>
<td>row 2, cell 1</td>
<td>row 2, cell 2</td>
</tr>
</table>
How the HTML code above looks in a browser:
row 1, cell 1 row 1, cell 2
row 2, cell 1 row 2, cell 2



13

HTML Tables and the Border Attribute
If you do not specify a border attribute, the table will be displayed without borders.
Sometimes this can be useful, but most of the time, we want the borders to show.
To display a table with borders, specify the border attribute:
<table border="1">
<tr>
<td>Row 1, cell 1</td>
<td>Row 1, cell 2</td>
</tr>
</table>


HTML Table Headers
Header information in a table are defined with the <th> tag.
All major browsers display the text in the <th> element as bold and centered.
<table border="1">
<tr>
<th>Header 1</th>
<th>Header 2</th>
</tr>
<tr>
<td>row 1, cell 1</td>
<td>row 1, cell 2</td>
</tr>
<tr>
<td>row 2, cell 1</td>
<td>row 2, cell 2</td>
</tr>
</table>
How the HTML code above looks in your browser:
Header 1 Header 2
row 1, cell 1 row 1, cell 2
row 2, cell 1 row 2, cell 2




14
The <html> element:
<html>

<body>
<p>This is my first paragraph.</p>
</body>

</html>
The <html> element defines the whole HTML document.
The element has a start tag <html> and an end tag </html>.
The element content is another HTML element (the body element).
HTML Attributes
HTML elements can have attributes
Attributes provide additional information about an element
Attributes are always specified in the start tag
Attributes come in name/value pairs like: name="value"

Attribute Example
HTML links are defined with the <a> tag. The link address is specified in the href attribute:
Example
<a href="http://www.restarttechnologies.com">This is a link</a>

HTML Headings
Headings are defined with the <h1> to <h6> tags.
<h1> defines the most important heading. <h6> defines the least important heading.
Example
<h1>This is a heading</h1>
<h2>This is a heading</h2>
<h3>This is a heading</h3>
HTML Lines
The <hr>tag creates a horizontal line in an HTML page.

The hr element can be used to separate content:

15
Example
<p>This is a paragraph</p>
<hr><p>This is a paragraph</p>
<hr><p>This is a paragraph</p>
HTML Line Breaks
Use the <br> tag if you want a line break (a line) without starting a paragraph:

HTML Text Formatting Tags
Tag Description
<b> Defines bold text
<em> Defines emphasized text
<i> Defines a part of text in an alternate voice or mood
<small> Defines smaller text
<strong> Defines important text
<sub> Defines subscripted text
<sup> Defines superscripted text
<ins> Defines inserted text
<del> Defines deleted text
<pre> Defines pre formatted text
HTML Comments
Comments can be inserted into the HTML code to make it more readable and understandable.
Comments are ignored by the browser and are not displayed.
Comments are written like this:
Example
<!-- This is a comment -->



16
HTML Tag Reference
Tag Description <p> Defines a paragraph <br> Inserts a single line break

HTML <col> Tag
Example
Set the background color of the three columns with the <colgroup> and <col> tags:
<table border="1">
<colgroup>
<col span="2" style="background-color:red">
<col style="background-color:yellow">
</colgroup>
<tr>
<th>ISBN</th>
<th>Title</th>
<th>Price</th>
</tr>
<tr>
<td>3476896</td>
<td>My first HTML</td>
<td>$53</td>
</tr>
</table>
Definition and Usage
The <col> tag specifies column properties for each column within a <colgroup> element.
The <col> tag is useful for applying styles to entire columns, instead of repeating the styles
for each cell, for each row.

HTML <thead> Tag
Example
An HTML table with a <thead>, <tfoot>, and a <tbody> element:
<table border="1">
<thead>
<tr>
<th>Month</th>
<th>Savings</th>

17
</tr>
</thead>
<tfoot>
<tr>
<td>Sum</td>
<td>$180</td>
</tr>
</tfoot>
<tbody>
<tr>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td>February</td>
<td>$80</td>
</tr>
</tbody>
</table>


Definition and Usage
The <thead> tag is used to group header content in an HTML table.
The <thead> element is used in conjunction with the <tbody> and <tfoot> elements to specify
each part of a table (header, body, footer).
Browsers can use these elements to enable scrolling of the table body independently of the
header and footer. Also, when printing a large table that spans multiple pages, these elements
can enable the table header and footer to be printed at the top and bottom of each page.
The <thead> tag must be used in the following context: As a child of a <table> element, after
any <caption>, and <colgroup> elements, and before any <tbody>, <tfoot>, and <tr>
elements.
HTML Lists
The most common HTML lists are ordered and unordered lists:
HTML Lists
An ordered list:
1. The first list item
2. The second list item
3. The third list item
An unordered list:
List item
List item
List item

18
HTML Unordered Lists
An unordered list starts with the <ul> tag. Each list item starts with the <li> tag.
The list items are marked with bullets (typically small black circles).
<ul>
<li>Coffee</li>
<li>Milk</li>
</ul>
How the HTML code above looks in a browser:
Coffee
Milk

HTML Ordered Lists
An ordered list starts with the <ol> tag. Each list item starts with the <li> tag.
The list items are marked with numbers.
<ol>
<li>Coffee</li>
<li>Milk</li>
</ol>
How the HTML code above looks in a browser:
1. Coffee
2. Milk

HTML Definition Lists
A definition list is a list of items, with a description of each item.
The <dl> tag defines a definition list.
The <dl> tag is used in conjunction with <dt> (defines the item in the list) and <dd>
(describes the item in the list):
<dl>
<dt>Coffee</dt>
<dd>- black hot drink</dd>
<dt>Milk</dt>
<dd>- white cold drink</dd>
</dl>

19
How the HTML code above looks in a browser:
Coffee
- black hot drink
Milk
- white cold drink

HTML Block Elements
Most HTML elements are defined as block level elements or as inline elements.
Block level elements normally start (and end) with a line when displayed in a browser.
Examples: <h1>, <p>, <ul>, <table>

HTML Inline Elements
Inline elements are normally displayed without starting a line.
Examples: <b>, <td>, <a>, <img>

The HTML <div> Element
The HTML <div> element is a block level element that can be used as a container for
grouping other HTML elements.
The <div> element has no special meaning. Except that, because it is a block level element,
the browser will display a line break before and after it.
When used together with CSS, the <div> element can be used to set style attributes to large
blocks of content.
Another common use of the <div> element, is for document layout. It replaces the "old way"
of defining layout using tables. Using tables is not the correct use of the <table> element. The
purpose of the <table> element is to display tabular data.

The HTML <span> Element
The HTML <span> element is an inline element that can be used as a container for text.
The <span> element has no special meaning.

20
When used together with CSS, the <span> element can be used to set style attributes to parts
of the text.

HTML Grouping Tags
Tag Description
<div> Defines a section in a document (block-level)
<span> Defines a section in a document (inline)

HTML Forms
HTML forms are used to pass data to a server.
An HTML form can contain input elements like text fields, checkboxes, radio-buttons,
submit buttons and more. A form can also contain select lists, textarea, fieldset, legend, and
label elements.
The <form> tag is used to create an HTML form:
<form>
.
input elements
.
</form>


HTML Forms - The Input Element
The most important form element is the <input> element.
The <input> element is used to select user information.
An <input> element can vary in many ways, depending on the type attribute. An <input>
element can be of type text field, checkbox, password, radio button, submit button, and more.
The most common input types are described below.

Text Fields
<input type="text"> defines a one-line input field that a user can enter text into:

21
<form>
First name: <input type="text" name="firstname"><br>
Last name: <input type="text" name="lastname">
</form>
How the HTML code above looks in a browser:
First name:
Last name:
Note: The form itself is not visible. Also note that the default width of a text field is 20
characters.

Password Field
<input type="password"> defines a password field:
<form>
Password: <input type="password" name="pwd">
</form>
How the HTML code above looks in a browser:
Password:
Note: The characters in a password field are masked (shown as asterisks or circles).

Radio Buttons
<input type="radio"> defines a radio button. Radio buttons let a user select ONLY ONE of a
limited number of choices:
<form>
<input type="radio" name="sex" value="male">Male<br>
<input type="radio" name="sex" value="female">Female
</form>
How the HTML code above looks in a browser:
Male
Female



22
Checkboxes
<input type="checkbox"> defines a checkbox. Checkboxes let a user select ZERO or MORE
options of a limited number of choices.
<form>
<input type="checkbox" name="vehicle" value="Bike">I have a bike<br>
<input type="checkbox" name="vehicle" value="Car">I have a car
</form>
How the HTML code above looks in a browser:
I have a bike
I have a car

Submit Button
<input type="submit"> defines a submit button.
A submit button is used to send form data to a server. The data is sent to the page specified in
the form's action attribute. The file defined in the action attribute usually does something with
the received input:
<form name="input" action="html_form_action.asp" method="get">
Username: <input type="text" name="user">
<input type="submit" value="Submit">
</form>
How the HTML code above looks in a browser:
Username:
If you type some characters in the text field above, and click the "Submit" button, the browser
will send your input to a page called "html_form_action.asp". The page will show you the
received input.




23
HTML EVENT ATTRIBUTES

Global Event Attributes
HTML 4 added the ability to let events trigger actions in a browser, like starting a JavaScript
when a user clicks on an element.
Below are the global event attributes that can be added to HTML elements to define event
actions.
Window Event Attributes
Events triggered for the window object (applies to the <body> tag):
Attribute Value Description
onafterprint script Script to be run after the document is printed
onbeforeprint script Script to be run before the document is printed
onbeforeunload script Script to be run before the document is unloaded
onerror script Script to be run when an error occur
onhaschange script Script to be run when the document has changed
onload script Fires after the page is finished loading
onmessage script Script to be run when the message is triggered
onoffline script Script to be run when the document goes offline
ononline script Script to be run when the document comes online
onpagehide script Script to be run when the window is hidden
onpageshow script Script to be run when the window becomes visible
onpopstate script Script to be run when the window's history changes
onredo script Script to be run when the document performs a redo
onresize script Fires when the browser window is resized
onstorage script Script to be run when a Web Storage area is updated
onundo script Script to be run when the document performs an undo
onunload script
Fires once a page has unloaded (or the browser window has been
closed)


24
Form Events
Events triggered by actions inside a HTML form (applies to almost all HTML elements, but
is most used in form elements):
Attribute Value Description
onblur script Fires the moment that the element loses focus
onchange script Fires the moment when the value of the element is changed
oncontextmenu script Script to be run when a context menu is triggered
onfocus script Fires the moment when the element gets focus
onformchange script Script to be run when a form changes
onforminput script Script to be run when a form gets user input
oninput script Script to be run when an element gets user input
oninvalid script Script to be run when an element is invalid
onreset script
Fires when the Reset button in a form is clicked
Not supported in HTML5
onselect script Fires after some text has been selected in an element
onsubmit script Fires when a form is submitted


Keyboard Events
Attribute Value Description
onkeydown script Fires when a user is pressing a key
onkeypress script Fires when a user presses a key
onkeyup script Fires when a user releases a key


Mouse Events
Events triggered by a mouse, or similar user actions:

25
Attribute Value Description
onclick script Fires on a mouse click on the element
ondblclick script Fires on a mouse double-click on the element
ondrag script Script to be run when an element is dragged
ondragend script Script to be run at the end of a drag operation
ondragenter script
Script to be run when an element has been dragged to a valid drop
target
ondragleave script Script to be run when an element leaves a valid drop target
ondragover script
Script to be run when an element is being dragged over a valid
drop target
ondragstart script Script to be run at the start of a drag operation
ondrop script Script to be run when dragged element is being dropped
onmousedown script Fires when a mouse button is pressed down on an element
onmousemove script Fires when the mouse pointer moves over an element
onmouseout script Fires when the mouse pointer moves out of an element
onmouseover script Fires when the mouse pointer moves over an element
onmouseup script Fires when a mouse button is released over an element
onmousewheel script Script to be run when the mouse wheel is being rotated
onscroll script Script to be run when an element's scrollbar is being scrolled


26
CSS
CSS stands for Cascading Style Sheets
Styles define how to display HTML elements
Styles were added to HTML 4.0 to solve a problem
External Style Sheets can save a lot of work
External Style Sheets are stored in CSS files
CSS Demo
An HTML document can be displayed with different styles:
Styles Solved a Big Problem
HTML was never intended to contain tags for formatting a document.
HTML was intended to define the content of a document, like:
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
When tags like <font>, and color attributes were added to the HTML 3.2 specification, it
started a nightmare for web developers. Development of large web sites, where fonts and
color information were added to every single page, became a long and expensive process.
To solve this problem, the World Wide Web Consortium (W3C) created CSS.
In HTML 4.0, all formatting could be removed from the HTML document, and stored in a
separate CSS file.
All browsers support CSS today.
CSS Saves a Lot of Work!
CSS defines HOW HTML elements are to be displayed.
Styles are normally saved in external .css files. External style sheets enable you to change the
appearance and layout of all the pages in a Web site, just by editing one single file!




27
CSS Syntax
A CSS rule has two main parts: a selector, and one or more declarations:

The selector is normally the HTML element you want to style.
Each declaration consists of a property and a value.
The property is the style attribute you want to change. Each property has a value.
CSS Example
A CSS declaration always ends with a semicolon, and declaration groups are surrounded by
curly brackets: p {color:red;text-align:center;} To make the CSS more readable, you can put
one declaration on each line, like this:
Example
p
{
color:red;
text-align:center;
}

CSS Comments
Comments are used to explain your code, and may help you when you edit the source code at
a later date. Comments are ignored by browsers.
A CSS comment begins with "/*", and ends with "*/", like this:
/*This is a comment*/
p
{
text-align:center;
/*This is another comment*/
color:black;
font-family:arial;
}

28
CSS Id and Class
The id and class Selectors
In addition to setting a style for a HTML element, CSS allows you to specify your own
selectors called "id" and "class".
The id Selector
The id selector is used to specify a style for a single, unique element.The id selector uses the
id attribute of the HTML element, and is defined with a "#".The style rule below will be
applied to the element with id="para1":
Example
#para1
{
text-align:center;
color:red;
}
The class Selector
The class selector is used to specify a style for a group of elements. Unlike the id selector, the
class selector is most often used on several elements.
This allows you to set a particular style for many HTML elements with the same class.
The class selector uses the HTML class attribute, and is defined with a "."
In the example below, all HTML elements with class="center" will be center-aligned:
Example
.center {text-align:center;}
You can also specify that only specific HTML elements should be affected by a class.
In the example below, all p elements with class="center" will be center-aligned:
Example
p.center {text-align:center;}


29
CSS Background
CSS background properties are used to define the background
effects of an element.
CSS properties used for background effects:
background-color
background-image
background-repeat
background-attachment
background-position
Background Color
The background-color property specifies the background color of an element.
The background color of a page is defined in the body selector:
Example
body {background-color:#b0c4de;}
With CSS, a color is most often specified by:
a HEX value - like "#ff0000"
an RGB value - like "rgb(255,0,0)"
a color name - like "red"
In the example below, the h1, p, and div elements have different background colors:
Example
h1 {background-color:#6495ed;}
p {background-color:#e0ffff;}
div {background-color:#b0c4de;}
Background Image
The background-image property specifies an image to use as the background of an element.
By default, the image is repeated so it covers the entire element. The background image for a
page can be set like this:
Example
body {background-image:url('paper.gif');}
Below is an example of a bad combination of text and background image. The text is almost not
readable:

30
Example
body {background-image:url('bgdesert.jpg');}
Background Image - Repeat Horizontally or Vertically
By default, the background-image property repeats an image both horizontally and vertically.
Some images should be repeated only horizontally or vertically, or they will look strange, like
this:
Example
body
{
background-image:url('gradient2.png');
}
If the image is repeated only horizontally (repeat-x), the background will look better:
Example
body
{
background-image:url('gradient2.png');
background-repeat:repeat-x;
}
Background Image - Set position and no-repeat
When using a background image, use an image that does not disturb the text. Showing the
image only once is specified by the background-repeat property:
Example
body
{
background-image:url('img_tree.png');
background-repeat:no-repeat;
}
In the example above, the background image is shown in the same place as the text. We want to
change the position of the image, so that it does not disturb the text too much. The position of the
image is specified by the background-position property:
Example
body
{
background-image:url('img_tree.png');
background-repeat:no-repeat;

31
background-position:right top;
}

Background - Shorthand property
As you can see from the examples above, there are many properties to consider when dealing
with backgrounds. To shorten the code, it is also possible to specify all the properties in one
single property. This is called a shorthand property. The shorthand property for background is
simply "background":
Example
body {background:#ffffff url('img_tree.png') no-repeat right top;}
When using the shorthand property the order of the property values is:
background-color
background-image
background-repeat
background-attachment
background-position
It does not matter if one of the property values is missing, as long as the ones that are present
are in this order.
All CSS Background Properties
Property Description
background Sets all the background properties in one declaration
background-attachment
Sets whether a background image is fixed or scrolls with the rest of
the page
background-color Sets the background color of an element
background-image Sets the background image for an element
background-position Sets the starting position of a background image
background-repeat Sets how a background image will be repeated

32

CSS Text
TEXT FORMATTING
Text Color
The color property is used to set the color of the text. With CSS, a color is most often
specified by:
a HEX value - like "#ff0000"
an RGB value - like "rgb(255,0,0)"
a color name - like "red"
The default color for a page is defined in the body selector.
Example
body {color:blue;}
h1 {color:#00ff00;}
h2 {color:rgb(255,0,0);}
For W3C compliant CSS: If you define the color property, you must also define the
background-color property.
Text Alignment
The text-align property is used to set the horizontal alignment of a text. Text can be centered,
or aligned to the left or right, or justified. When text-align is set to "justify", each line is
stretched so that every line has equal width, and the left and right margins are straight (like in
magazines and newspapers).
Example
h1 {text-align:center;}
p.date {text-align:right;}
p.main {text-align:justify;}


Text Decoration
The text-decoration property is used to set or remove decorations from text. The text-
decoration property is mostly used to remove underlines from links for design purposes:


33
Example
a {text-decoration:none;}
It can also be used to decorate text:
Example
h1 {text-decoration:overline;}
h2 {text-decoration:line-through;}
h3 {text-decoration:underline;}
h4 {text-decoration:blink;}

It is not recommended to underline text that is not a link, as this often confuses users.
Text Transformation
The text-transform property is used to specify uppercase and lowercase letters in a text. It can
be used to turn everything into uppercase or lowercase letters, or capitalize the first letter of
each word.
Example
p.uppercase {text-transform:uppercase;}
p.lowercase {text-transform:lowercase;}
p.capitalize {text-transform:capitalize;}
Text Indentation
The text-indentation property is used to specify the indentation of the first line of a text.
Example
p {text-indent:50px;}




34
All CSS Text Properties
Property Description
color Sets the color of text
direction Specifies the text direction/writing direction
letter-spacing
Increases or decreases the space between characters in a
text
line-height Sets the line height
text-align Specifies the horizontal alignment of text
text-
decoration
Specifies the decoration added to text
text-indent Specifies the indentation of the first line in a text-block
text-shadow Specifies the shadow effect added to text
text-transform Controls the capitalization of text
unicode-bidi
vertical-align Sets the vertical alignment of an element
white-space Specifies how white-space inside an element is handled
word-spacing
Increases or decreases the space between words in a text






35
CSS Font
CSS font properties define the font family, boldness, size, and the style of a text.
Difference Between Serif and Sans-serif Fonts

On computer screens, sans-serif fonts are considered easier to read than serif fonts.
CSS Font Families
In CSS, there are two types of font family names:
generic family - a group of font families with a similar look (like "Serif" or "Monospace")
font family - a specific font family (like "Times New Roman" or "Arial")
Generic family Font family Description
Serif
Times New
Roman
Georgia
Serif fonts have small lines at the ends on some
characters
Sans-serif
Arial
Verdana
"Sans" means without - these fonts do not have
the lines at the ends of characters
Monospace
Courier New
Lucida
Console
All monospace characters have the same width
Font Family
The font family of a text is set with the font-family property. The font-family property should
hold several font names as a "fallback" system. If the browser does not support the first font,
it tries the next font.
Start with the font you want, and end with a generic family, to let the browser pick a similar
font in the generic family, if no other fonts are available. Note: If the name of a font family
is more than one word, it must be in quotation marks, like font-family: "Times New Roman".
More than one font family is specified in a comma-separated list:

36
Example
p{font-family:"Times New Roman", Times, serif;}
Font Style
The font-style property is mostly used to specify italic text. This property has three values:
normal - The text is shown normally
italic - The text is shown in italics
oblique - The text is "leaning" (oblique is very similar to italic, but less supported)
Example
p.normal {font-style:normal;}
p.italic {font-style:italic;}
p.oblique {font-style:oblique;}
Font Size
The font-size property sets the size of the text. Being able to manage the text size is important
in web design. However, you should not use font size adjustments to make paragraphs look
like headings, or headings look like paragraphs.
Always use the proper HTML tags, like <h1> - <h6> for headings and <p> for paragraphs.
The font-size value can be an absolute, or relative size.
Absolute size:
Sets the text to a specified size
Does not allow a user to change the text size in all browsers (bad for accessibility reasons)
Absolute size is useful when the physical size of the output is known
Relative size:
Sets the size relative to surrounding elements
Allows a user to change the text size in browsers
If you do not specify a font size, the default size for normal text, like paragraphs, is 16px
(16px=1em).
Set Font Size With Pixels
Setting the text size with pixels gives you full control over the text size:


37
Example
h1 {font-size:40px;}
h2 {font-size:30px;}
p {font-size:14px;}
The example above allows Internet Explorer 9, Firefox, Chrome, Opera, and Safari to resize
the text. Note: The example above does not work in IE, prior version 9.
The text can be resized in all browsers using the zoom tool (however, this resizes the entire
page, not just the text).
Set Font Size With Em
To avoid the resizing problem with older versions of Internet Explorer, many developers use
em instead of pixels. The em size unit is recommended by the W3C.
1em is equal to the current font size. The default text size in browsers is 16px. So, the default
size of 1em is 16px. The size can be calculated from pixels to em using this formula:
pixels/16=em
Example
h1 {font-size:2.5em;} /* 40px/16=2.5em */
h2 {font-size:1.875em;} /* 30px/16=1.875em */
p {font-size:0.875em;} /* 14px/16=0.875em */

In the example above, the text size in em is the same as the previous example in pixels. However,
with the em size, it is possible to adjust the text size in all browsers.
Unfortunately, there is still a problem with older versions of IE. The text becomes larger than
it should when made larger, and smaller than it should when made smaller.
Use a Combination of Percent and Em
The solution that works in all browsers, is to set a default font-size in percent for the <body>
element:
Example
body {font-size:100%;}
h1 {font-size:2.5em;}
h2 {font-size:1.875em;}
p {font-size:0.875em;}
Our code now works great! It shows the same text size in all browsers, and allows all
browsers to zoom or resize the text!


38
All CSS Font Properties
Property Description
font Sets all the font properties in one declaration
font-family Specifies the font family for text
font-size Specifies the font size of text
font-style Specifies the font style for text
font-variant
Specifies whether or not a text should be displayed in a small-caps
font
font-weight Specifies the weight of a font
CSS Links
Styling Links
Links can be styled with any CSS property (e.g. color, font-family, background, etc.).
Special for links are that they can be styled differently depending on what state they are in.
The four links states are:
a:link - a normal, unvisited link
a:visited - a link the user has visited
a:hover - a link when the user mouses over it
a:active - a link the moment it is clicked
Example
a:link {color:#FF0000;} /* unvisited link */
a:visited {color:#00FF00;} /* visited link */
a:hover {color:#FF00FF;} /* mouse over link */
a:active {color:#0000FF;} /* selected link */
When setting the style for several link states, there are some order rules:
a:hover MUST come after a:link and a:visited
a:active MUST come after a:hover


39
Common Link Styles
In the example above the link changes color depending on what state it is in.
Lets go through some of the other common ways to style links:
Text Decoration
The text-decoration property is mostly used to remove underlines from links:
Example
a:link {text-decoration:none;}
a:visited {text-decoration:none;}
a:hover {text-decoration:underline;}
a:active {text-decoration:underline;}
Background Color
The background-color property specifies the background color for links:
Example
a:link {background-color:#B2FF99;}
a:visited {background-color:#FFFF85;}
a:hover {background-color:#FF704D;}
a:active {background-color:#FF704D;}
CSS Lists
The CSS list properties allow you to:
Set different list item markers for ordered lists
Set different list item markers for unordered lists
Set an image as the list item marker
List
In HTML, there are two types of lists:
unordered lists - the list items are marked with bullets
ordered lists - the list items are marked with numbers or letters
Different List Item Markers
The type of list item marker is specified with the list-style-type property:
Example
ul.a {list-style-type: circle;}
ul.b {list-style-type: square;}

40

ol.c {list-style-type: upper-roman;}
ol.d {list-style-type: lower-alpha;}
Some of the values are for unordered lists, and some for ordered lists.
An Image as The List Item Marker
To specify an image as the list item marker, use the list-style-image property:
Example
ul
{
list-style-image: url('sqpurple.gif');
}
The example above does not display equally in all browsers. IE and Opera will display the image-
marker a little bit higher than Firefox, Chrome, and Safari.
If you want the image-marker to be placed equally in all browsers, a crossbrowser solution is
explained below.
Crossbrowser Solution
The following example displays the image-marker equally in all browsers:
Example
ul
{
list-style-type: none;
padding: 0px;
margin: 0px;
}
ul li
{
background-image: url(sqpurple.gif);
background-repeat: no-repeat;
background-position: 0px 5px;
padding-left: 14px;
}
Example
For ul:
Set the list-style-type to none to remove the list item marker
Set both padding and margin to 0px (for cross-browser compatibility)
For all li in ul:
o Set the URL of the image, and show it only once (no-repeat)
o Position the image where you want it (left 0px and down 5px)

41
o Position the text in the list with padding-left
List - Shorthand property
It is also possible to specify all the list properties in one, single property. This is called a
shorthand property.
The shorthand property used for lists, is the list-style property:
Example
ul
{
list-style: square url("sqpurple.gif");
}
When using the shorthand property, the order of the values are:
list-style-type
list-style-position (for a description, see the CSS properties table below)
list-style-image
It does not matter if one of the values above are missing, as long as the rest are in the
specified order.
All CSS List Properties
Property Description
list-style Sets all the properties for a list in one declaration
list-style-image Specifies an image as the list-item marker
list-style-position
Specifies if the list-item markers should appear inside or outside the content
flow
list-style-type Specifies the type of list-item marker
CSS Tables
The look of an HTML table can be greatly improved with CSS:
Company Contact Country
Alfreds Futterkiste Maria Anders Germany
Berglunds snabbkp Christina Berglund Sweden
Centro comercial Moctezuma Francisco Chang Mexico

42
Ernst Handel Roland Mendel Austria
Island Trading Helen Bennett UK
Kniglich Essen Philip Cramer Germany
Laughing Bacchus Winecellars Yoshi Tannamuri Canada
Magazzini Alimentari Riuniti Giovanni Rovelli Italy
North/South Simon Crowther UK
Paris spcialits Marie Bertrand France
The Big Cheese Liz Nixon USA
Vaffeljernet Palle Ibsen Denmark
Table Borders
To specify table borders in CSS, use the border property.The example below specifies a black
border for table, th, and td elements:
Example
table, th, td
{
border: 1px solid black;
}

Notice that the table in the example above has double borders. This is because both the table and
the th/td elements have separate borders.To display a single border for the table, use the border-
collapse property.

Collapse Borders
The border-collapse property sets whether the table borders are collapsed into a single border
or separated:
Example
table
{
border-collapse:collapse;
}
table,th, td
{

43
border: 1px solid black;
}
Table Width and Height
Width and height of a table is defined by the width and height properties.The example below
sets the width of the table to 100%, and the height of the th elements to 50px:
Example
table
{
width:100%;
}
th
{
height:50px;
}
Table Text Alignment
The text in a table is aligned with the text-align and vertical-align properties.The text-align
property sets the horizontal alignment, like left, right, or center:
Example
td
{
text-align:right;
}
The vertical-align property sets the vertical alignment, like top, bottom, or middle:
Example
td
{
height:50px;
vertical-align:bottom;
}




44
Table Padding
To control the space between the border and content in a table, use the padding property on td
and th elements:
Example
td
{
padding:15px;
}

Table Color
The example below specifies the color of the borders, and the text and background color of th
elements:
Example
table, td, th
{
border:1px solid green;
}
th
{
background-color:green;
color:white;




45
JAVASCRIPT INTRODUCTION
JavaScript is the world's most popular programming language. It is the language for HTML
and the web, for servers, PCs, laptops, tablets, smart phones, and more.

JavaScript is a Scripting Language
A scripting language is a lightweight programming language.
JavaScript is programming code that can be inserted into HTML pages.
JavaScript inserted into HTML pages, can be executed by all modern web browsers.
JavaScript is easy to learn.

What You Will Learn
Below is a taste of what you will learn in this tutorial.

JavaScript: Writing Into HTML Output
Example
document.write("<h1>This is a heading</h1>");
document.write("<p>This is a paragraph</p>");


You can only use document.write in the HTML output. If you use it after the document has
loaded, the whole document will be overwritten.




46
JavaScript: Reacting to Events
Example
<button type="button" onclick="alert('Welcome!')">Click Me!</button>

The alert() function is not much used in JavaScript, but it is often quite handy for trying out
code.
The onclick event is only one of the many HTML events you will learn about in this tutorial.

JavaScript: Changing HTML Content
Using JavaScript to manipulate the content of HTML elements is a very powerful
functionality.
Example
x=document.getElementById("demo") //Find the element
x.innerHTML="Hello JavaScript"; //Change the content
You will often see document.getElementByID("some id"). This is defined in the HTML
DOM.
The DOM (Document Object Model) is the official W3C standard for accessing HTML
elements.

JavaScript: Changing HTML Styles
Changing the style of an HTML element, is a variant of changing an HTML attribute.
Example
x=document.getElementById("demo") //Find the element
x.style.color="#ff0000"; //Change the style




47

JavaScript: Validate Input
JavaScript is commonly used to validate input.
Example
if isNaN(x) {alert("Not Numeric")};


Did You Know?

JavaScript and Java are two completely different languages, in both concept and design.
Java (invented by Sun) is a more complex programming language in the same category as C.

ECMA-262 is the official name of the JavaScript standard.

JavaScript was invented by Brendan Eich. It appeared in Netscape (a no longer existing
browser) in 1995, and has been adopted by ECMA (a standard association) since 1997

Scripts in HTML must be inserted between <script> and </script> tags.
Scripts can be put in the <body> and in the <head> section of an HTML page.

The <script> Tag
To insert a JavaScript into an HTML page, use the <script> tag.
The <script> and </script> tells where the JavaScript starts and ends.
The lines between the <script> and </script> contain the JavaScript:
<script>
alert("My First JavaScript");
</script>
You don't have to understand the code above. Just take it for a fact, that the browser
will interpret and execute the JavaScript code between the <script> and </script> tags.

Old examples may have type="text/javascript" in the <script> tag. This is no longer
required. JavaScript is the default scripting language in all modern browsers and in
HTML5.

48

JavaScript in <body>
In this example, JavaScript writes into the HTML <body> while the page loads:
Example
<!DOCTYPE html>
<html>
<body>
.
.
<script>
document.write("<h1>This is a heading</h1>");
document.write("<p>This is a paragraph</p>");
</script>
.
.
</body>
</html>

JavaScript Functions and Events
The JavaScript statements in the example above, are executed while the page loads.
More often, we want to execute code when an event occurs, like when the user clicks a
button.
If we put JavaScript code inside a function, we can call that function when an event
occurs.
You will learn much more about JavaScript functions and events in later chapters.

JavaScript in <head> or <body>
You can place an unlimited number of scripts in an HTML document.
Scripts can be in the <body> or in the <head> section of HTML, and/or in both.
It is a common practice to put functions in the <head> section, or at the bottom of the
page. This way they are all in one place and do not interfere with page content.


49
A JavaScript Function in <head>
In this example, a JavaScript function is placed in the <head> section of an HTML
page.
The function is called when a button is clicked:
Example
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction()
{
document.getElementById("demo").innerHTML="My First JavaScript Function";
}
</script>
</head>
<body>
<h1>My Web Page</h1>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>
</body>
</html>


A JavaScript Function in <body>
In this example, a JavaScript function is placed in the <body> section of an HTML
page.
The function is called when a button is clicked:
Example
<!DOCTYPE html>
<html>
<body>

50
<h1>My Web Page</h1>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
document.getElementById("demo").innerHTML="My First JavaScript Function";
}
</script>
</body>
</html>


External JavaScripts
Scripts can also be placed in external files. External files often contain code to be used
by several different web pages.
External JavaScript files have the file extension .js.
To use an external script, point to the .js file in the "src" attribute of the <script> tag:
Example
<!DOCTYPE html>
<html>
<body>
<script src="myScript.js"></script>
</body>
</html>

You can place the script in the <head> or <body> as you like. The script will behave as
if it was located exactly where you put the <script> tag in the document.

External scripts cannot contain <script> tags.

JavaScript Variables

51
JavaScript variables are "containers" for storing information:
Example
var x=5;
var y=6;
var z=x+y;
Much Like Algebra
x=5
y=6
z=x+y
In algebra we use letters (like x) to hold values (like 5).
From the expression z=x+y above, we can calculate the value of z to be 11.
In JavaScript these letters are called variables.


JavaScript Variables
As with algebra, JavaScript variables can be used to hold values (x=5) or expressions
(z=x+y).
Variable can have short names (like x and y) or more descriptive names (age, sum,
totalvolume).
Variable names must begin with a letter
Variable names can also begin with $ and _ (but we will not use it)
Variable names are case sensitive (y and Y are different variables)

Both JavaScript statements and JavaScript variables are case-sensitive.


JavaScript Data Types
JavaScript variables can also hold other types of data, like text values (name="John
Doe").
In JavaScript a text like "John Doe" is called a string.

52
There are many types of JavaScript variables, but for now, just think of numbers and
strings.
When you assign a text value to a variable, put double or single quotes around the
value.
When you assign a numeric value to a variable, do not put quotes around the value. If
you put quotes around a numeric value, it will be treated as text.
Example
var pi=3.14;
var name="John Doe";
var answer='Yes I am!';


Declaring (Creating) JavaScript Variables
Creating a variable in JavaScript is most often referred to as "declaring" a variable.
You declare JavaScript variables with the var keyword:
var carname;
After the declaration, the variable is empty (it has no value).
To assign a value to the variable, use the equal sign:
carname="Volvo";
However, you can also assign a value to the variable when you declare it:
var carname="Volvo";
In the example below we create a variable called carname, assigns the value "Volvo" to
it, and put the value inside the HTML paragraph with id="demo":
Example
<p id="demo"></p>
var carname="Volvo";
document.getElementById("demo").innerHTML=carname;


It's a good programming practice to declare all the variables you will need, in one
place, at the beginning of your code.

53


One Statement, Many Variables
You can declare many variables in one statement. Just start the statement with var and
separate the variables by comma:
var name="Doe", age=30, job="carpenter";
Your declaration can also span multiple lines:
var name="Doe",
age=30,
job="carpenter";


Value = undefined
In computer programs, variables are often declared without a value. The value can be
something that has to be calculated, or something that will be provided later, like user
input. Variable declared without a value will have the value undefined.
The variable carname will have the value undefined after the execution of the following
statement:
var carname;


Re-Declaring JavaScript Variables
If you re-declare a JavaScript variable, it will not lose its value:.
The value of the variable carname will still have the value "Volvo" after the execution
of the following two statements:
var carname="Volvo";
var carname;


JavaScript Arithmetic

54
As with algebra, you can do arithmetic with JavaScript variables, using operators like =
and +:
Example
y=5;
x=y+2;


JavaScript Statements

JavaScript is a sequence of statements to be executed by the browser.

JavaScript Statements
JavaScript statements are "commands" to the browser. The purpose of the statements is
to tell the browser what to do.
This JavaScript statement tells the browser to write "Hello Dolly" inside an HTML
element with id="demo":
document.getElementById("demo").innerHTML="Hello Dolly";


Semicolon ;
Semicolon separates JavaScript statements.
Normally you add a semicolon at the end of each executable statement.
Using semicolons also makes it possible to write many statements on one line.

You might see examples without semicolons.
Ending statements with semicolon is optional in JavaScript.


JavaScript Code

55
JavaScript code (or just JavaScript) is a sequence of JavaScript statements.
Each statement is executed by the browser in the sequence they are written.
This example will manipulate two HTML elements:
Example
document.getElementById("demo").innerHTML="Hello Dolly";
document.getElementById("myDIV").innerHTML="How are you?";


JavaScript Code Blocks
JavaScript statements can be grouped together in blocks.
Blocks start with a left curly bracket, and end with a right curly bracket.
The purpose of a block is to make the sequence of statements execute together.
A good example of statements grouped together in blocks, are JavaScript functions.
This example will run a function that will manipulate two HTML elements:
Example
function myFunction()
{
document.getElementById("demo").innerHTML="Hello Dolly";
document.getElementById("myDIV").innerHTML="How are you?";
}

JavaScript is Case Sensitive
JavaScript is case sensitive.
Watch your capitalization closely when you write JavaScript statements:
A function getElementById is not the same as getElementbyID.
A variable named myVariable is not the same as MyVariable.
White Space
JavaScript ignores extra spaces. You can add white space to your script to make it more

56
readable. The following lines are equivalent:
var name="Hege";
var name = "Hege";


Break up a Code Line
You can break up a code line within a text string with a backslash. The example
below will be displayed properly:
document.write("Hello \
World!");
However, you cannot break up a code line like this:
document.write \
("Hello World!");


Did You Know?

JavaScript is a scripting language. Scripting code is executed line by line while the
browser reads it. With traditional programming, all the code has to be compiled before
it can be

JavaScript If...Else Statements

Conditional statements are used to perform different actions based on different
conditions.

Conditional Statements
Very often when you write code, you want to perform different actions for different
decisions. You can use conditional statements in your code to do this.
In JavaScript we have the following conditional statements:
if statement - use this statement to execute some code only if a specified condition is
true

57
if...else statement - use this statement to execute some code if the condition is true
and another code if the condition is false
if...else if....else statement - use this statement to select one of many blocks of code
to be executed
switch statement - use this statement to select one of many blocks of code to be
executed

If Statement
Use the if statement to execute some code only if a specified condition is true.
Syntax
if (condition)
{
code to be executed if condition is true
}
Note that if is written in lowercase letters. Using uppercase letters (IF) will generate a
JavaScript error!
Example
Make a "Good day" greeting if the time if less than 20:00:
if (time<20)
{
x="Good day";
}
The result of x will be:
Good day

Notice that there is no ..else.. in this syntax. You tell the browser to execute some code
only if the specified condition is true.

If...else Statement
Use the if....else statement to execute some code if a condition is true and another code
if the condition is not true.
Syntax
if (condition)
{

58
code to be executed if condition is true
}
else
{
code to be executed if condition is not true
}

Example
If the time is less than 20:00, you will get a "Good day" greeting, otherwise you will
get a "Good evening" greeting
if (time<20)
{
x="Good day";
}
else
{
x="Good evening";
}
The result of x will be:
Good day


If...else if...else Statement
Use the if....else if...else statement to select one of several blocks of code to be
executed.
Syntax
if (condition1)
{
code to be executed if condition1 is true
}
else if (condition2)
{
code to be executed if condition2 is true
}
else
{
code to be executed if neither condition1 nor condition2 is true
}


59
Example
If the time is less than 10:00, you will get a "Good morning" greeting, if not, but the
time is less than 20:00, you will get a "Good day" greeting, otherwise you will get a
"Good evening" greeting:
if (time<10)
{
x="Good morning";
}
else if (time<20)
{
x="Good day";
}
else
{
x="Good evening";
}
The result of x will be:
Good day
JavaScript Popup Boxes

JavaScript has three kind of popup boxes: Alert box, Confirm box, and Prompt box.

Alert Box
An alert box is often used if you want to make sure information comes through to the
user.
When an alert box pops up, the user will have to click "OK" to proceed.
Syntax
window.alert("sometext");
The window.alert method can be written without the window prefix.
Example
<!DOCTYPE html>
<html>
<head>
<script>

60
function myFunction()
{
alert("I am an alert box!");
}
</script>
</head>
<body>

<input type="button" onclick="myFunction()" value="Show alert box">

</body>
</html>

Confirm Box
A confirm box is often used if you want the user to verify or accept something.
When a confirm box pops up, the user will have to click either "OK" or "Cancel" to
proceed.
If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box returns
false.
Syntax
window.confirm("sometext");
The window.confirm() method can be written without the window prefix.
Example
var r=confirm("Press a button");
if (r==true)
{
x="You pressed OK!";
}
else
{
x="You pressed Cancel!";
}

Prompt Box
A prompt box is often used if you want the user to input a value before entering a page.
When a prompt box pops up, the user will have to click either "OK" or "Cancel" to

61
proceed after entering an input value.
If the user clicks "OK" the box returns the input value. If the user clicks "Cancel" the
box returns null.
Syntax
window.prompt("sometext","defaultvalue");
The window.prompt() method can be written without the window prefix.
Example
var name=prompt("Please enter your name","Harry Potter");
if (name!=null && name!="")
{
x="Hello " + name + "! How are you today?";
}


Line Breaks
To display line breaks inside a popup box, use a back-slash followed by the character n.
Example
alert("Hello\nHow are you?");
JavaScript Functions

A function is a block of code that will be executed when "someone" calls it:
Example
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction()
{
alert("Hello World!");
}
</script>
</head>

<body>

62
<button onclick="myFunction()">Try it</button>
</body>
</html>


JavaScript Function Syntax
A function is written as a code block (inside curly { } braces), preceded by the function
keyword:
function functionname()
{
some code to be executed
}
The code inside the function will be executed when "someone" calls the function.
The function can be called directly when an event occurs (like when a user clicks a
button), and it can be called from "anywhere" by JavaScript code.

JavaScript is case sensitive. The function keyword must be written in lowercase letters,
and the function must be called with the same capitals as used in the function name.


Calling a Function with Arguments
When you call a function, you can pass along some values to it, these values are called
arguments or parameters.
These arguments can be used inside the function.
You can send as many arguments as you like, separated by commas (,)
myFunction(argument1,argument2)
Declare the argument, as variables, when you declare the function:
function myFunction(var1,var2)
{
some code
}
The variables and the arguments must be in the expected order. The first variable is
given the value of the first passed argument etc.

63
Example
<button onclick="myFunction('Harry Potter','Wizard')">Try it</button>

<script>
function myFunction(name,job)
{
alert("Welcome " + name + ", the " + job);
}
</script>

The function above will alert "Welcome Harry Potter, the Wizard" when the button is
clicked.
The function is flexible, you can call the function using different arguments, and
different welcome messages will be given:
Example
<button onclick="myFunction('Harry Potter','Wizard')">Try it</button>
<button onclick="myFunction('Bob','Builder')">Try it</button>

The example above will alert "Welcome Harry Potter, the Wizard" or "Welcome Bob,
the Builder" depending on which button is clicked.

Functions With a Return Value
Sometimes you want your function to return a value back to where the call was made.
This is possible by using the return statement.
When using the return statement, the function will stop executing, and return the
specified value.
Syntax
function myFunction()
{
var x=5;
return x;
}
The function above will return the value 5.
Note: It is not the entire JavaScript that will stop executing, only the function.

64
JavaScript will continue executing code, where the function-call was made from.
The function-call will be replaced with the returnvalue:
var myVar=myFunction();
The variable myVar holds the value 5, which is what the function "myFunction()"
returns.
You can also use the returnvalue without storing it as a variable:
document.getElementById("demo").innerHTML=myFunction();
The innerHTML of the "demo" element will be 5, which is what the function
"myFunction()" returns.
You can make a returnvalue based on arguments passed into the function:
Example
Calculate the product of two numbers, and return the result:
function myFunction(a,b)
{
return a*b;
}

document.getElementById("demo").innerHTML=myFunction(4,3);
The innerHTML of the "demo" element will be:
12
The return statement is also used when you simply want to exit a function. The return
value is optional:
function myFunction(a,b)
{
if (a>b)
{
return;
}
x=a+b
}
The function above will exit the function if a>b, and will not calculate the sum of a and
b.


65
Local JavaScript Variables
A variable declared (using var) within a JavaScript function becomes LOCAL and can
only be accessed from within that function. (the variable has local scope).
You can have local variables with the same name in different functions, because local
variables are only recognized by the function in which they are declared.
Local variables are deleted as soon as the function is completed.

Global JavaScript Variables
Variables declared outside a function, become GLOBAL, and all scripts and functions
on the web page can access it.

The Lifetime of JavaScript Variables
The lifetime JavaScript variables starts when they are declared.
Local variables are deleted when the function is completed.
Global variables are deleted when you close the page.

Assigning Values to Undeclared JavaScript Variables
If you assign a value to variable that has not yet been declared, the variable will
automatically be declared as a GLOBAL variable.
This statement:
carname="Volvo";
will declare the variable carname as a global variable , even if it is executed inside a
function.

JavaScript HTML DOM Events

HTML DOM allows JavaScript to react to HTML events.

66
Example
Mouse Over Me
Click Me


Reacting to Events
A JavaScript can be executed when an event occurs, like when a user clicks on an
HTML element.
To execute code when a user clicks on an element, add JavaScript code to an HTML
event attribute:
onclick=JavaScript
Examples of HTML events:
When a user clicks the mouse
When a web page has loaded
When an image has been loaded
When the mouse moves over an element
When an input field is changed
When an HTML form is submitted
When a user strokes a key
In this example, the content of the <h1> element is changed when a user clicks on it:
Example
<!DOCTYPE html>
<html>
<body>
<h1 onclick="this.innerHTML='Ooops!'">Click on this text!</h1>
</body>
</html>

In this example, a function is called from the event handler:
Example
<!DOCTYPE html>
<html>
<head>

67
<script>
function changetext(id)
{
id.innerHTML="Ooops!";
}
</script>
</head>
<body>
<h1 onclick="changetext(this)">Click on this text!</h1>
</body>
</html>
HTML Event Attributes
To assign events to HTML elements you can use event attributes.
Example
Assign an onclick event to a button element:
<button onclick="displayDate()">Try it</button>
In the example above, a function named displayDate will be executed when the button
is clicked.

Assign Events Using the HTML DOM
The HTML DOM allows you to assign events to HTML elements using JavaScript:
Example
Assign an onclick event to a button element:
<script>
document.getElementById("myBtn").onclick=function(){displayDate()};
</script>
In the example above, a function named displayDate is assigned to an HTML element
with the id=myButn".
The function will be executed when the button is clicked.

The onload and onunload Events

68
The onload and onunload events are triggered when the user enters or leaves the page.
The onload event can be used to check the visitor's browser type and browser version,
and load the proper version of the web page based on the information.
The onload and onunload events can be used to deal with cookies.
Example
<body onload="checkCookies()">


The onchange Event
The onchange event are often used in combination with validation of input fields.
Below is an example of how to use the onchange. The upperCase() function will be
called when a user changes the content of an input field.
Example
<input type="text" id="fname" onchange="upperCase()">


The onmouseover and onmouseout Events
The onmouseover and onmouseout events can be used to trigger a function when the
user mouses over, or out of, an HTML element.

Example
A simple onmouseover-onmouseout example:
Mouse Over Me

The onmousedown, onmouseup and onclick Events
The onmousedown, onmouseup, and onclick events are all parts of a mouse-click. First
when a mouse-button is clicked, the onmousedown event is triggered, then, when the
mouse-button is released, the onmouseup event is triggered, finally, when the mouse-

69
click is completed, the onclick event is triggered.
Example
A simple onmousedown-onmouseup example:
Click Me


JavaScript Array Object

The Array object is used to store multiple values in a single variable.

Try it Yourself - Examples
Create an array, and assign values to it:
Example
var mycars = new Array();
mycars[0] = "Saab";
mycars[1] = "Volvo";
mycars[2] = "BMW";


What is an Array?
An array is a special variable, which can hold more than one value at a time.
If you have a list of items (a list of car names, for example), storing the cars in single
variables could look like this:
var car1="Saab";
var car2="Volvo";
var car3="BMW";
However, what if you want to loop through the cars and find a specific one? And what
if you had not 3 cars, but 300?

70
The solution is an array!
An array can hold many values under a single name, and you can access the values by
referring to an index number.

Create an Array
An array can be created in three ways.
The following code creates an Array object called myCars:
1: Regular:
var myCars=new Array();
myCars[0]="Saab";
myCars[1]="Volvo";
myCars[2]="BMW";
2: Condensed:
var myCars=new Array("Saab","Volvo","BMW");
3: Literal:
var myCars=["Saab","Volvo","BMW"];


Access an Array
You refer to an element in an array by referring to the index number.
This statement access the value of the first element in myCars:
var name=myCars[0];
This statement modifies the first element in myCars:
myCars[0]="Opel";


[0] is the first element in an array. [1] is the second . . . . . (indexes start with 0)



71
You Can Have Different Objects in One Array
All JavaScript variables are objects. Array elements are objects. Functions are objects.
Because of this, you can have variables of different types in the same Array.
You can have objects in an Array. You can have functions in an Array. You can have
arrays in an Array:
myArray[0]=Date.now;
myArray[1]=myFunction;
myArray[2]=myCars;


Array Methods and Properties
The Array object has predefined properties and methods:
var x=myCars.length // the number of elements in myCars
var y=myCars.indexOf("Volvo") // the index position of "Volvo"


Create New Methods
Prototype is a global constructor in JavaScript. It can construct new properties and
methods for any JavaScript Objects.

Example: Make a new Array method.
Array.prototype.ucase=function()
{
for (i=0;i<this.length;i++)
{this[i]=this[i].toUpperCase();}
}

JavaScript String Object
The String object is used for storing and manipulating text.

72

JavaScript Strings
A string simply stores a series of characters like "John Doe".
A string can be any text inside quotes. You can use simple or double quotes:
Example
var carname="Volvo XC60";
var carname='Volvo XC60';
You can access each character in a string with its position (index):
Example
var character=carname[7];
String indexes are zero-based, which means the first character is [0], the second is [1],
and so on.
You can use quotes inside a string, as long as they don't match the quotes surrounding
the string:
Example
var answer="It's alright";
var answer="He is called 'Johnny'";
var answer='He is called "Johnny"';
Or you can put quotes inside a string by using the \ escape character:
Example
var answer='It\'s alright';
var answer="He is called \"Johnny\"";

String Length
The length of a string (a string object) is found in the built in property length:
Example
var txt="Hello World!";
document.write(txt.length);

73

var txt="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
document.write(txt.length);


Finding a String in a String
The indexOf() method returns the position (as a number) of the first found occurrence
of a specified text inside a string:
Example
var str="Hello world, welcome to the universe.";
var n=str.indexOf("welcome");
The method returns -1 if the specified text is not found.
The lastIndexOf() method starts searching at the end of the string instead of at the
beginning.

Matching Content
The match() method can be used to search for a matching content in a string:
Example
var str="Hello world!";
document.write(str.match("world") + "<br>");
document.write(str.match("World") + "<br>");
document.write(str.match("world!"));

Replacing Content
The replace() method replaces a specified value with another value in a string.
Example
str="Please visit Microsoft!"
var n=str.replace("Microsoft","W3Schools");


74
Upper Case and Lower Case
A string is converted to upper/lower case with the methods toUpperCase() /
toLowerCase():
Example
var txt="Hello World!"; // String
var txt1=txt.toUpperCase(); // txt1 is txt converted to upper
var txt2=txt.toLowerCase(); // txt2 is txt converted to lower

Convert a String to an Array
A string is converted to an array with the built in method string.split():
Example
txt="a,b,c,d,e" // String
txt.split(","); // Split on commas
txt.split(" "); // Split on spaces
txt.split("|"); // Split on pipe
Special Characters
The backslash (\) can be used to insert apostrophes, new lines, quotes, and other special
characters into a string.
Look at the following JavaScript code:
var txt="We are the so-called "Vikings" from the north.";
document.write(txt);
In JavaScript, a string is started and stopped with either single or double quotes. This
means that the string above will be chopped to: We are the so-called
To solve this problem, you must place a backslash (\) before each double quote in
"Viking". This turns each double quote into a string literal:
var txt="We are the so-called \"Vikings\" from the north.";
document.write(txt);
JavaScript will now output the proper text string: We are the so-called "Vikings" from
the north.
The table below lists other special characters that can be added to a text string with the
backslash sign:

75
Code Outputs
\' single quote
\" double quote
\\ backslash
\n new line
\r carriage return
\t tab
\b backspace
\f form feed


String Properties and Methods
Properties:
length
prototype
constructor
Methods:
charAt()
charCodeAt()
concat()
fromCharCode()
indexOf()
lastIndexOf()
match()
replace()
search()
slice()
split()
substr()
substring()
toLowerCase()
toUpperCase()
valueOf()

JavaScript Date Object

76
The Date object is used to work with dates and times.
Return today's date and time
How to use the Date() method to get today's date.
getFullYear()
Use getFullYear() to get the year.
getTime()
getTime() returns the number of milliseconds since 01.01.1970.
setFullYear()
How to use setFullYear() to set a specific date.
toUTCString()
How to use toUTCString() to convert today's date (according to UTC) to a string.
getDay()
Use getDay() and an array to write a weekday, and not just a number.
Display a clock
How to display a clock on your web page.

Create a Date Object
The Date object is used to work with dates and times.
Date objects are created with the Date() constructor.
There are four ways of initiating a date:
new Date() // current date and time
new Date(milliseconds) //milliseconds since 1970/01/01
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds)
Most parameters above are optional. Not specifying, causes 0 to be passed in.
Once a Date object is created, a number of methods allow you to operate on it. Most
methods allow you to get and set the year, month, day, hour, minute, second, and
milliseconds of the object, using either local time or UTC (universal, or GMT) time.
All dates are calculated in milliseconds from 01 January, 1970 00:00:00 Universal
Time (UTC) with a day containing 86,400,000 milliseconds.
Some examples of initiating a date:
var today = new Date()

77
var d1 = new Date("October 13, 1975 11:13:00")
var d2 = new Date(79,5,24)
var d3 = new Date(79,5,24,11,33,0)


Set Dates
We can easily manipulate the date by using the methods available for the Date object.
In the example below we set a Date object to a specific date (14th January 2010):
var myDate=new Date();
myDate.setFullYear(2010,0,14);
And in the following example we set a Date object to be 5 days into the future:
var myDate=new Date();
myDate.setDate(myDate.getDate()+5);
Note: If adding five days to a date shifts the month or year, the changes are handled
automatically by the Date object itself!

Compare Two Dates
The Date object is also used to compare two dates.
The following example compares today's date with the 14th January 2100:
var x=new Date();
x.setFullYear(2100,0,14);
var today = new Date();

if (x>today)
{
alert("Today is before 14th January 2100");
}
else
{
alert("Today is after 14th January 2100");
}




78
What is RegExp?
RegExp, is short for regular expression.
A regular expression is an object that describes a pattern of characters.
When you search in a text, you can use a pattern to describe what you are searching for.
A simple pattern can be one single character.
A more complicated pattern can consist of more characters, and can be used for
parsing, format checking, substitution and more.
Regular expressions are used to perform powerful pattern-matching and "search-and-
replace" functions on text.
Syntax
var patt=new RegExp(pattern,modifiers);

or more simply:

var patt=/pattern/modifiers;
pattern specifies the pattern of an expression
modifiers specify if a search should be global, case-sensitive, etc.

RegExp Modifiers
Modifiers are used to perform case-insensitive and global searches.
The i modifier is used to perform case-insensitive matching.
The g modifier is used to perform a global match (find all matches rather than stopping
after the first match).
Example 1
Do a case-insensitive search for "w3schools" in a string:
var str="Visit Restarttechnologies ";
var patt1=/ Restarttechnologies /i;
The marked text below shows where the expression gets a match:
Visit Restarttechnologies

79

Example 2
Do a global search for "is":
var str="Is this all there is?";
var patt1=/is/g;
The marked text below shows where the expression gets a match:
Is this all there is?

Example 3
Do a global, case-insensitive search for "is":
var str="Is this all there is?";
var patt1=/is/gi;
The marked text below shows where the expression gets a match:
Is this all there is?

test()
The test() method searches a string for a specified value, and returns true or false,
depending on the result.
The following example searches a string for the character "e":
Example
var patt1=new RegExp("e");
document.write(patt1.test("The best things in life are free"));
Since there is an "e" in the string, the output of the code above will be:
true

exec()
The exec() method searches a string for a specified value, and returns the text of the

80
found value. If no match is found, it returns null.
The following example searches a string for the character "e":
Example 1
var patt1=new RegExp("e");
document.write(patt1.exec("The best things in life are free"));
Since there is an "e" in the string, the output of the code above will be:
e

You might also like