4. HTML Guide - To Print

62
PROGRAMMING Web Designing with HTML, CSS and JavaScript Students Guide In partnership with

Transcript of 4. HTML Guide - To Print

Page 1: 4. HTML Guide - To Print

PROGRAMMING Web Designing with HTML,

CSS and JavaScript

Students Guide

In partnership with

Page 2: 4. HTML Guide - To Print

Web Designing with HTML, CSS and JavaScript

Page I

SLANA Technology Learning Centre

Preface

Youth unemployment is high in Sri Lanka’s rural regions, and the disadvantaged youth

population has difficulty in accessing the required knowledge and training which will allow them

to break the existing cycle of poverty to build a better life for themselves. As of 2015, the field of

programming is flourishing on a global scale; nevertheless in rural areas of Sri Lanka, youth have

little to no access to learn programming.

‘Learn the Code that Builds Your World’ project was conceptualized by Sri Lanka Anti

Narcotics Association to address this important issue. This project aims to disseminate

programming knowledge and practical training to youth who previously would not have had the

opportunity to gain access to such teachings; with the ultimate goal of the beneficiaries to

become more employable at the end of their learning experience. One important aspect of this

project’s success is collaborating with relevant organizations, institutes, and schools that identify

apt students and help SLANA disseminate the coding curriculum.

SLANA has been very fortunate to be able to be sponsored by World Bank, Microsoft,

and Sarvodya Fusion to start our Learn the Code that Builds Your World program in Maskeliya

with Tea Leaf Vision being our first collaborative partner.

Page 3: 4. HTML Guide - To Print

Web Designing with HTML, CSS and JavaScript

Page II

SLANA Technology Learning Centre

Introduction This book is specifically targeted at Junior Website Designers, and gives them a

sufficient understanding of basics in HTML, CSS (Cascading Style Sheets) and JavaScript to

create websites. It’s better if you have basic programming knowledge to follow the JavaScript

part of this book.

What is HTML?

HTML is a markup language for describing web documents (web pages).HTML stands

for Hyper Text Markup Language. A markup language is a set of markup tags. HTML

documents are described by HTML tags. Each HTML tag describes different document content.

CSS (Cascading Style Sheets)

Cascading Style Sheets (CSS) is a style sheet language used for describing the look and

formatting of a document written in a markup language.

JavaScript

JavaScript is the programming language that uses for handle the dynamic part of the web

site for any user interaction. It is very easy to learn as a programming language point of view and

because of that it is the most popular programming language in the world.

Page 4: 4. HTML Guide - To Print

Web Designing with HTML, CSS and JavaScript

Page III

Sri Lanka Anti Narcotics Association

Table of Contents Chapter 1

Introduction ...................................................................................................................................................... 1 The World Wide Web (WWW)

HTML Introduction

The Declarations

The HTML Elements

HTML Headings

HTML Text Formatting

Chapter 2

Styles & CSS ..................................................................................................................................................... 6 HTML Styling

CSS Styling

Main Styling Methods (Inline, Internal and External)

CSS Selectors

CSS for Background and Text

Chapter 3

HTML Links ................................................................................................................................................... 14 HTML Links Syntax

HTML Links with Attributes

Styling Links

Chapter 4

Images .............................................................................................................................................................. 17 HTML Images Syntax

Set Image Size

Set Image Path

Image as Links

Chapter 5

HTML Tables ................................................................................................................................................. 20 HTML Table Syntax

HTML Table Styling

Chapter 6

HTML Lists..................................................................................................................................................... 24 HTML List Types with Syntaxes

Chapter 7

HTML Layouts ............................................................................................................................................... 28 HTML Block Elements and Inline Elements

HTML Div and Span Elements

Website Layout Using HTML5

HTML Layout Using Tables

Chapter 8

HTML Forms .................................................................................................................................................. 32 HTML Form Elements

Chapter 9

HTML5 ............................................................................................................................................................ 39 HTML5 Introduction

HTML5 Supports

HTML5 Elements

Chapter 10

HTML Media .................................................................................................................................................. 42 HTML Media Elements with Introduction

Chapter 11

JavaScript........................................................................................................................................................ 45

Basic Introduction to JavaScript

Control Structures in JavaScript

Functions in JavaScript

User Interaction through Dialog Boxes in JavaScript

References ............................................................................................................................................................. 58

Page 5: 4. HTML Guide - To Print

Web Designing with HTML, CSS and JavaScript

Page 1

Sri Lanka Anti Narcotics Association

Chapter 1 Introduction 1.1 The World Wide Web (WWW)

The World Wide Web is a collection of computers that offer access to services (web, ftp,

mail, telnet). Communication across the World Wide Web depends on the TCP/IP stack of

protocols.

These services are organized as websites; websites are built from web pages. And we can

use HTML to create webpages.

1.2 What is HTML?

HTML is a markup language for describing web documents (web pages).

HTML stands for Hyper Text Markup Language.

A markup language is a set of markup tags.

HTML documents are described by HTML tags.

Each HTML tag describes different document content.

1.3 HTML Tags

HTML tags are keywords (tag names) surrounded by angle brackets:

<tagname>content goes here </tagname>

HTML tags normally come in pairs like <p> and </p>

The first tag in a pair is the start tag(opening tag), the second tag is the end tag(closing

tag)

The end tag is written like the start tag, but with a slash before the tag name

HTML Example

Code: Output:

<!DOCTYPE html>

<html>

<head>

<title>My First HTML</title>

</head>

<body>

<h1>My First Heading</h1>

<p>My First Paragraph</p>

</body>

</html>

Figure 1.1

Page 6: 4. HTML Guide - To Print

Web Designing with HTML, CSS and JavaScript

Page 2

Sri Lanka Anti Narcotics Association

Example Explained:

The DOCTYPE declaration defines the document type

The text between <html> and </html> describes the web document

The text between <head> and </head> describes the meta data

The text between <title> and </title> is the title of the document

The text between <body> and </body> describes the visible page content

The text between <h1> and </h1> describes a heading

The text between <p> and </p> describes paragraph

Using the description, a web browser can display a document with a heading and a paragraph.

1.4 HTML Page Structure

Below is a visualization of an HTML page structure:

Only the content in the body section is visible to the viewer.

Text, images, videos, etc. will be contained in body section.

1.5 HTML Versions Since the early days of the web, there have been many versions of HTML:

Versions Year

HTML 1991

HTML+ 1993

HTML 2.0 1995

HTML 3.2 1997

HTML 4.01 1999

XHTML 2000

HTML 5 2012

1.6 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 correctly if it knows the HTML version and type.

Figure 1.2

Table1.1

Page 7: 4. HTML Guide - To Print

Web Designing with HTML, CSS and JavaScript

Page 3

Sri Lanka Anti Narcotics Association

1.7 Common Declarations HTML5

<!DOCTYPE html>

HTML 4.01

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"

"http://www.w3.org/TR/html4/loose.dtd">

XHTML 1.0

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

1.8 The HTML <head> Element

The HTML <head> element has nothing to do with HTML headings. The HTML <head>

element only contains metadata. The HTML <head> element is placed between the <html> tag

and the <body> tag.

1.9 The HTML <title> Element

The HTML <title> element is metadata. It defines the HTML document's title. It will not

be displayed in the document. However, it might be displayed in one of the browser tabs.

<title>My First HTML</title>

1.10 Paragraphs The HTML <p> element defines a paragraph.

Example:

Code: Output:

1.11 HTML Display

You cannot be sure how HTML will be displayed. Large or small screens and resized

windows will create different results. With HTML, you cannot change the output by adding extra

spaces or extra lines in your HTML code. The browser will remove extra spaces and extra lines

when the page is displayed. Any number of spaces, and any number of new lines, counts as only

one space.

Therefore if you need to add spaces or line breaks you have to add relevant element for

that.

i.e.: <br> for new line &nbsp; for space

Figure 1.3

Figure 1.4

Page 8: 4. HTML Guide - To Print

Web Designing with HTML, CSS and JavaScript

Page 4

Sri Lanka Anti Narcotics Association

Example:

Code:

Output:

1.12 The HTML <pre> Element The HTML <pre> element defines a block of pre-formatted text, with structured spaces

and lines. To display anything, with right spacing and line-breaks, you must wrap the text in a

<pre> element:

Code:

Figure 1.5

Page 9: 4. HTML Guide - To Print

Web Designing with HTML, CSS and JavaScript

Page 5

Sri Lanka Anti Narcotics Association

Output:

1.13 HTML Headings

Headings are defined with the <h1> to <h6> tags.<h1> defines the most important

heading. <h6> defines the least important heading. Use HTML headings for headings only. Don't

use headings to make text BIG or bold. Search engines use your headings to index the structure

and content of your web pages. Users skim your pages by its headings. It is important to use

headings to show the document structure.h1 headings should be main headings, followed by h2

headings, then the less important h3, and so on.

1.14 HTML Text Formatting Formatting elements were designed to display special types of text:

Tag Description Example

<b></b> Defines bold text bold

<em></em> Defines emphasized text emphasized

<i></i> Defines italic text italic

<small></small> Defines smaller text small

<strong></strong> Defines important text important

<sub></sub> Defines subscripted text subscript

<sup></sup> Defines superscripted text superscript

<ins></ins> Defines inserted text inserted

<del></del> Defines deleted text deleted

<mark></mark> Defines marked/highlighted text marked

<u></u> Defines underlined text underlined

Figure 1.6

Figure 1.7

Table 1.2

Page 10: 4. HTML Guide - To Print

Web Designing with HTML, CSS and JavaScript

Page 6

Sri Lanka Anti Narcotics Association

Chapter 2 Styles & CSS 2.1 HTML Styling

Every HTML element has a default style (background color is white, text color is black,

text-size is 12px, etc.)Changing the default style of an HTML element, can be done with the style

attribute. We can change these default values using “<style>” tag. The HTML style attribute has

the following syntax:

style="property:value"

The property is a CSS property. The value is a CSS value.Styling the HTML this method is

known as Inline Styling. Here are few examples.

<h1 style="color:blue">This is a heading</h1>

<p style="background-color:red">This is a paragraph.</p>

2.2 Styling HTML with CSS CSS stands for Cascading Style Sheets. Styling can be added to HTML elements in 3

ways:

Inline - using a style attribute in HTML elements.

Internal - using a <style> element in the HTML <head> section.

External - using one or more external CSS files.

The most common way to add styling is to keep the CSS syntax in separate CSS files

(external css) because in this way we can reuse the same stylesheet in many pages.

2.3 CSS Syntax

CSS styling has the following syntax:

element { property:value ; property:value }

The element is an HTML element name. The property is a CSS property. The value is a CSS

value.Multiple styles are separated with semicolon.

Example: body {background-color:lightgrey}

h1 {color:blue}

p {color:green}

2.4 Inline Styling

Inline styling uses the style attribute. Inline styling is useful for applying a unique style to a

single HTML element.

Example:

Code: Output:

Figure 2.1

Page 11: 4. HTML Guide - To Print

Web Designing with HTML, CSS and JavaScript

Page 7

Sri Lanka Anti Narcotics Association

2.5 Internal Styling (Internal CSS)

An internal style sheet can be used to define a common style for all HTML elements on a

page. This technique is recommended when we are using relatively small number of pages or

each page’s styling is defers from others. Internal styling is defined in the <head> section of an

HTML page, using a <style> element:

Example:

Code:

Output:

2.6 External Styling (External CSS) External style sheet are ideal when the style is applied to many pages. With external style

sheets, you can change the look of an entire site by changing one file. External styles are defined

in the <head> section of an HTML page, in the <link> element.

Example:

Code:

style.css (External Style file)

HTML Page

Output:

Figure 2.2

Figure 2.3

Page 12: 4. HTML Guide - To Print

Web Designing with HTML, CSS and JavaScript

Page 8

Sri Lanka Anti Narcotics Association

2.7 CSS Selectors CSS selectors allow you to select and manipulate HTML element(s).CSS selectors are

used to "find" (or select) HTML elements based on their id, classes, types, attributes, values of

attributes and much more.

1. The element Selector

The element selector selects elements based on the element name. You can select all

<p> elements on a page like this: (all <p> elements will be center-aligned, with a red

text color)

Example:

p { text-align: center;color: red;}

2. The id Selector

The id selector uses the id attribute of an HTML tag to find the specific element. An

id should be unique within a page, so you should use the id selector when you want to

find a single, unique element. To find an element with a specific id, write a hash

character, followed by the id of the element. The style rule below will be applied to

the HTML element with id="para1":

Example:

#para1 { text-align: center;color: red; }

3. The class Selector

The class selector finds elements with the specific class. The class selector uses the

HTML class attribute. To find elements with a specific class, write a period character,

followed by the name of the class. In the example below, all HTML elements with

class="center" will be center-aligned:

Example:

.center { text-align: center; color: red; }

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; color: red; }

4. Grouping Selectors

In style sheets there are often elements with the same style. To minimize the code,

you can group selectors. To group selectors, separate each selector with a comma. In

the example below we have grouped the selectors from the code above:

Page 13: 4. HTML Guide - To Print

Web Designing with HTML, CSS and JavaScript

Page 9

Sri Lanka Anti Narcotics Association

2.8 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-position

1. 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(150,150,150)"

a color name - like "red"

Example:

2. 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"); }

3. 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. If the image needs to be repeated only horizontally use repeat-x or if it

needs to repeat vertically use repeat-y. Use no repeat if you don’t need to repeat it at all.

Example: body {background-image:url("gradient_bg.png");background-repeat:repeat-x;}

body {background-image:url("gradient_bg.png");background-repeat:repeat-y;}

body {background-image:url("gradient_bg.png");background-repeat:no-repeat;}

4. Background Image - Set position

The position of the image is specified by the background-position property:

Example: body {

background-image: url("img_tree.png");

background-repeat: no-repeat;

background-position: right top;

}

Page 14: 4. HTML Guide - To Print

Web Designing with HTML, CSS and JavaScript

Page 10

Sri Lanka Anti Narcotics Association

2.9 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: #ffffffurl("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-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.

2.10 CSS with Text

Text of a paragraph or heading can be styled by editing CSS properties.

1. Text Color

The color property is used to set the color of the text.

Example:

2. 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:

3. 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

and it can also be used to decorate text:

Example:

Page 15: 4. HTML Guide - To Print

Web Designing with HTML, CSS and JavaScript

Page 11

Sri Lanka Anti Narcotics Association

4. 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:

5. Text Indentation

The text-indent property is used to specify the indentation of the first line of a text.

Example: p { text-indent: 50px; }

2.11 CSS Font CSS font properties define the font family, boldness, size, and the style of a text.

1. 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")

2. 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. If the name of a

font family is more than one word, it must be in quotation marks, like: "Times New Roman".

More than one font family is specified in a comma-separated list:

Example: p { font-family: "Times New Roman", Times, serif;}

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

Table 2.1

Page 16: 4. HTML Guide - To Print

Web Designing with HTML, CSS and JavaScript

Page 12

Sri Lanka Anti Narcotics Association

3. 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:

4. 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 .If you do not specify a

font size, the default size for normal text, like paragraphs, is 16px. 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

Set Font Size with Pixels

Setting the text size with pixels gives you full control over the text size:

Example:

Set Font Size with Em

To allow users to resize the text (in the browser menu), many developers use em

instead of pixels.Theem 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:

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.

Page 17: 4. HTML Guide - To Print

Web Designing with HTML, CSS and JavaScript

Page 13

Sri Lanka Anti Narcotics Association

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.

2.12 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:

Our code now works great! It shows the same text size in all browsers, and allows all

browsers to zoom or resize the text!

2.13 Other CSS Font Properties

Property Description

font-variant Specifies whether or not a text should be displayed in a small-caps font

font-weight Specifies the weight of a font

Table 2.2

Page 18: 4. HTML Guide - To Print

Web Designing with HTML, CSS and JavaScript

Page 14

Sri Lanka Anti Narcotics Association

Chapter 3 HTML Links 3.1 HTML Links - Hyperlinks Links are found in nearly all web pages. Links allow users to click their way from page to

page. HTML links are hyperlinks. A hyperlink is an element, a text, or an image that you can

click on, and jump to another document.

3.2 HTML Links - Syntax In HTML, links are defined with the <a> tag:

<a href="url">link text</a>

Example:

<a href="http://www.slana.lk">Visit SLANA website</a>

The href attribute specifies the destination address (http://www.slana.lk)

The link text is the visible part (Visit SLANA website).

Clicking on the link text, will send you to the specified address.

The link text does not have to be text. It can be an HTML image or any other HTML

element.

3.3 Local Links

The example above used an absolute URL (A full web address). A local link (link to the

same web site) is specified with a relative URL (without http://www....).

Example:

<a href="html_images.html">HTML Images</a>

3.4 HTML Links - The target attribute

The target attribute specifies where to open the linked document. This example will open

the linked document in a new browser window or in a new tab:

Example:

<a href="http://www.slana.lk" target="_blank">Visit SLANA website</a>

Target Value Description

_blank Opens the linked document in a new window or tab

_self

Opens the linked document in the same frame as it was

clicked(this is default)

_parent Opens the linked document in the parent frame

_top Opens the linked document in the full body of the window

framename Opens the linked document in a named frame

Table 3.1

Page 19: 4. HTML Guide - To Print

Web Designing with HTML, CSS and JavaScript

Page 15

Sri Lanka Anti Narcotics Association

If your webpage is locked in a frame, you can use target="_top" to break out of the frame:

Example:

<a href="http://www.slana.lk" target="_top">Visit SLANA website</a>

3.5 HTML Links - The id attribute The id attribute can be used to create bookmarks inside HTML documents. Bookmarks are

not displayed in any special way. They are invisible to the reader.

Example:

Add an id attribute to any <a> element:

<a id="tips">Useful Tips Section</a>

Then create a link to the <a> element (Useful Tips Section):

<a href="#tips">Visit the Useful Tips Section</a>

Or, create a link to the <a> element (Useful Tips Section) from another page:

<a href="http://www.slana.lk\index.htm#tips">Visit the Useful Tips

Section</a>

3.6 Styling Links Links can be styled with any CSS property (e.g. color, font-family, background, etc.).In

addition, links 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.

When you move the mouse cursor over a link, two things will normally happen:

The mouse arrow will turn into a little hand

The color of the link element will change

By default, links will appear as this in all browsers:

An unvisited link is underlined and blue

A visited link is underlined and purple

An active link is underlined and red

You can change the defaults, using styles:

Example:

When setting the style for several link states, there are some order rules:

1. a:hover MUST come after a:link and a:visited

a:active MUST come after a:hover

Page 20: 4. HTML Guide - To Print

Web Designing with HTML, CSS and JavaScript

Page 16

Sri Lanka Anti Narcotics Association

3.7 Text Decoration

The text-decoration property is mostly used to remove underlines from links:

Example:

3.8 Background Color

The background-color property specifies the background color for links. You can set either

a color or an image to the background.

Example:

Page 21: 4. HTML Guide - To Print

Web Designing with HTML, CSS and JavaScript

Page 17

Sri Lanka Anti Narcotics Association

Chapter 4 Images

4.1 HTML Images Syntax In HTML, images are defined with the <img> tag.The<img> tag is empty; it contains

attributes only, and does not have a closing tag.The src attribute defines the URL (web address)

of the image: <img src="url" alt="some_text">

4.2 The alt Attribute The alt attribute specifies an alternate text for the image, if it cannot be displayed. The

value of the alt attribute should describe the image in words. The alt attribute is required. A web

page will not validate correctly without it. Screen readers the alt attribute can be read by Screen

readers.

Screen readers are software programs that can read what is displayed on a screen. Used

on the web, screen readers can "reproduce" HTML as text-to-speech, sound icons, or braille

output. Screen readers are used by people who are blind, visually impaired, or learning disabled.

Example

<img src="html5.gif" alt="The official HTML5 Icon">

4.3 Image Size - Width and Height You can use the style attribute to specify the width and height of an image. The values

are specified in pixels (use px after the value):

Example <img src="html5.gif" alt="HTML5 Icon" style="width:128px;height:128px">

Alternatively, you can use width and height attributes. The values are specified in pixels

(without px after the value):

Example <img src="html5.gif" alt="HTML5 Icon" width="128" height="128">

We suggest you use the style attribute. It prevents styles sheets from changing the default

size of images:

Page 22: 4. HTML Guide - To Print

Web Designing with HTML, CSS and JavaScript

Page 18

Sri Lanka Anti Narcotics Association

4.4 Images in another Folder If not specified, the browser expects to find the image in the same folder as the web page.

However, it is common on the web, to store images in a sub-folder, and refer to the folder in the

image name. If you want to access parent folder you have to use “/.. “

Example <img src="/images/html5.gif" alt="HTML5Icon" style="width:128px;

height:128px">

<img src="../html5.gif" alt="HTML5Icon" style="width:128px;

height:128px">

If a browser cannot find an image, it will display a broken link icon with the text in the alt

attribute:

4.5 Images on another Server Some web sites store their images on image servers. Actually, you can access images

from any web address in the world:

Example <img src="http://slana.lk/web/images/events/1.jpg">

4.6 Using an Image as a Link

It is common to use images as links. We have added “border:0” to prevent IE9 (and

earlier) from displaying a border around the image.

Example

Figure 4.1

Figure 4.2

Page 23: 4. HTML Guide - To Print

Web Designing with HTML, CSS and JavaScript

Page 19

Sri Lanka Anti Narcotics Association

4.7 Image Maps

For an image, you can create an image map, with clickable areas:

Example:

4.8 Image Floating

You can let an image float to the left or right of a paragraph:

Example:

Page 24: 4. HTML Guide - To Print

Web Designing with HTML, CSS and JavaScript

Page 20

Sri Lanka Anti Narcotics Association

Chapter 5 HTML Tables

Example explained:

Tables are defined with the <table> tag.

Tables are divided into table rows with the <tr> tag.

Table rows are divided into table data with the <td> tag.

A table row can also be divided into table headings with the <th> tag.

If you do not specify a border for the table, it will be displayed without borders. A border

can be added using the border attribute:

5.2 HTML Table Headings Table headings are defined with the <th> tag. By default, all major browsers display table

headings as bold and centered. If we want to left align it we have to specify it in CSS.

Example

th { text-align: left; }

5.1 Defining HTML Table

Figure 5.1

Page 25: 4. HTML Guide - To Print

Web Designing with HTML, CSS and JavaScript

Page 21

Sri Lanka Anti Narcotics Association

5.3 An HTML Table with Border Spacing Border spacing specifies the space between the cells. To set the border spacing for a table,

use the CSS border-spacing property:

Example table { border-spacing: 5px; }

5.4 Rowsapan and Colspan of table To make a cell span more than one row, use the rowspan attribute.

To make a cell span more than one column, use the colspan attribute.

Example

5.5 An HTML Table with a Caption To add a caption to a table, use the <caption> tag. The <caption> tag must be inserted

immediately after the <table> tag to display it above the table.

Example <caption>GreatScientists</caption>

5.6 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.

Figure 5.2

Page 26: 4. HTML Guide - To Print

Web Designing with HTML, CSS and JavaScript

Page 22

Sri Lanka Anti Narcotics Association

5.7 Collapse Borders The border-collapse property sets whether the table borders are collapsed into a single

border or separated. If the table has collapsed borders, border-spacing has no effect.

Example table { border-collapse: collapse; }

table, th, td { border: 1px solid black; }

5.8 Table Width and Height Width and height of a table and table elements (th, td, tr, caption) are 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; }

5.9 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. The vertical-align property

sets the vertical alignment, like top, bottom, or middle.

Example

5.10 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; }

5.11 Table Color

The example below specifies the color of the borders, and the text and background color

of th elements:

Example

Page 27: 4. HTML Guide - To Print

Web Designing with HTML, CSS and JavaScript

Page 23

Sri Lanka Anti Narcotics Association

5.12 Different Styles for Different Tables

Most of the examples above use a style attribute (width="100%") to define the width of

each table. This makes it easy to define different widths for different tables. The styles in the

<head> section, however, define a style for all tables in a page. To define a special style for a

special table, add an id attribute to the table.

Page 28: 4. HTML Guide - To Print

Web Designing with HTML, CSS and JavaScript

Page 24

Sri Lanka Anti Narcotics Association

Chapter 6 HTML Lists

6.1. HTML Lists HTML can have Unordered Lists, Ordered Lists, or Description Lists

Example:

I. Unordered HTML Lists

An unordered list starts with the <ul> tag. Each list item starts with the <li> tag.The list

items will be marked with bullets (small black circles).

Unordered List:

Unordered HTML Lists - The Style Attribute

A style attribute can be added to an unordered list, to define the style of the marker.

Using a type attribute <ul type="disc">, instead of <ul style="list-style-type:disc">, also

works. But in HTML5, the type attribute is not valid in unordered lists, only in ordered

list.

Example:

Style Description

list-style-type:disc The list items will be marked with bullets (default)

list-style-type:circle The list items will be marked with circles

list-style-type:square The list items will be marked with squares

list-style-type:none The list items will not be marked

Table 6.1

Figure 6.1

Figure 6.2

Page 29: 4. HTML Guide - To Print

Web Designing with HTML, CSS and JavaScript

Page 25

Sri Lanka Anti Narcotics Association

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; }

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 cross browser solution is explained

below.

Cross browser Solution

The following example displays the image-marker equally in all browsers:

Example:

Example explained:

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:

Set the URL of the image, and show it only once (no-repeat)

Position the image where you want it (left 0px and down 5px)

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 is:

list-style-type

list-style-position (for a description, see the CSS properties table below)

list-style-image

Page 30: 4. HTML Guide - To Print

Web Designing with HTML, CSS and JavaScript

Page 26

Sri Lanka Anti Narcotics Association

It does not matter if one of the values above is missing, as long as the rest are in the specified

order.

Ordered HTML Lists

An ordered list starts with the <ol> tag. Each list item starts with the <li> tag. The list

items will be marked with numbers.

Ordered List:

Ordered HTML Lists - The Type Attribute

A type attribute can be added to an ordered list, to define the type of the marker:

Example:

HTML Description Lists

A description list is a list of terms, with a description of each term. The <dl> tag defines

a description list. The <dt> tag defines the term (name), and the <dd> tag defines the

data (description).

Description List:

Nested HTML Lists

List can be nested (lists inside lists).List items can contain new list, and other HTML

elements, like images and links, etc.

Style Description

type="1" The list items will be numbered with numbers (default)

type="A" The list items will be numbered with uppercase letters

type="a" The list items will be numbered with lowercase letters

type="I" The list items will be numbered with uppercase roman numbers

type="i" The list items will be numbered with lowercase roman numbers

Table 6.2

Figure 6.3

Figure 6.4

Figure 6.5

Page 31: 4. HTML Guide - To Print

Web Designing with HTML, CSS and JavaScript

Page 27

Sri Lanka Anti Narcotics Association

Horizontal Lists

HTML lists can be styled in many different ways with CSS. One popular way, is to style

a list to display horizontally:

Horizontal List:

With a little extra style, you can make it look like a menu:

Figure 6.8

Figure 6.6

Figure 6.7

Page 32: 4. HTML Guide - To Print

Web Designing with HTML, CSS and JavaScript

Page 28

Sri Lanka Anti Narcotics Association

Chapter 7 HTML Layouts

7.1 HTML Block Elements and Inline Elements Most HTML elements are defined as block level elements or inline elements. Block level

elements normally start (and end) with a new line, when displayed in a browser.

Example: <h1>, <p>, <ul>, <table>

Inline elements are normally displayed without line breaks.

Example: <b>, <td>, <a>, <img>

7.2 The HTML <div> Element The HTML <div> element is a block level element that can be used as a container for

other HTML elements. The<div> element has no special meaning. It has no required

attributes, but style and class are common. Because it is a block level element, the

browser will display line breaks before and after it. When used together with CSS, the

<div> element can be used to style blocks of content.

7.3 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. It has no required attributes,

but style and class are common. Unlike<div>, which is formatted with line breaks, the

<span> element does not have any automatic formatting. When used together with CSS,

the <span> element can be used to style parts of the text:

Example: <h1>My <span style="color:red">Important</span>Heading</h1>

7.4 Classing HTML Elements Classing HTML elements, makes it possible to define CSS styles for classes of elements.

Equal styles for equal classes or different styles for different classes.

The HTML <div> element is a block level element. It can be used as a container for other

HTML elements. Classing<div> elements, makes it possible to define equal styles for

equal <div> elements:

Figure 7.1

Page 33: 4. HTML Guide - To Print

Web Designing with HTML, CSS and JavaScript

Page 29

Sri Lanka Anti Narcotics Association

Example:

The HTML <span> element is an inline element that can be used as a container for text.

Classing<span> elements makes it possible to design equal styles for equal <span>

elements.

Example:

7.5 HTML Layouts Websites often display content in multiple columns (like a magazine or newspaper).

The <div> element is often used as a layout tool, because it can easily be positioned with

CSS. This example uses 4 <div> elements to create a multiple column layout.

Page 34: 4. HTML Guide - To Print

Web Designing with HTML, CSS and JavaScript

Page 30

Sri Lanka Anti Narcotics Association

Figure 7.2

Page 35: 4. HTML Guide - To Print

Web Designing with HTML, CSS and JavaScript

Page 31

Sri Lanka Anti Narcotics Association

7.6 Website Layout Using HTML5

HTML5 offers new semantic elements that define different parts of a web page. Because

of this predefined element we don’t need to define <div> tags to most frequently using

areas.

This example uses <header>, <nav>, <section>, and <footer> to recreate previous

example

7.7 HTML Layout Using Tables The <table> element was not designed to be a layout tool. The purpose of the <table>

element is to display tabular data. Layout can be achieved using the <table> element,

because table elements can be styled with CSS.

header Defines a header for a document or a section

nav Defines a container for navigation links

section Defines a section in a document

article Defines an independent self-contained article

aside Defines content aside from the content (like a

sidebar)

footer Defines a footer for a document or a section

details Defines additional details

summary Defines a heading for the details element

Figure 7.3 Table 7.1

Page 36: 4. HTML Guide - To Print

Web Designing with HTML, CSS and JavaScript

Page 32

Sri Lanka Anti Narcotics Association

Chapter 8 HTML Forms

8.1. The <form> Element HTML forms are used to collect user input. The <form> element defines an HTML form:

Example: <form>

.

form elements

.

</form>

HTML forms contain form elements.

Form elements are different types of input elements, checkboxes, radio buttons, submit

buttons, and more.

8.2. The <input> Element

The <input> element is the most important form element. The<input> element has many

variations, depending on the type attribute. Here are the types used in this chapter.

Type Description

text Defines normal text input

password Defines password text input(content type won’t be desplayed)

radio Defines radio button input (for selecting one of many choices)

checkbox Defines checkbox input (for selecting one or more of many choices)

submit Defines a submit button (for submitting the form)

button Defines a button

file Defines file input to upload one or more files

1. Input Type: text

<input type="text"> defines a one-line input field for text input:

Example:

2. Input Type: password

<input type="password"> defines a password field:

Figure 8.1

Table 8.1

Page 37: 4. HTML Guide - To Print

Web Designing with HTML, CSS and JavaScript

Page 33

Sri Lanka Anti Narcotics Association

Example:

3. Input Type: submit

<input type="submit"> defines a button for submitting form input to a form-

handler. The form-handler is typically a server page with a script for processing input

data. The form-handler is specified in the form's action attribute. With the submit button

you can also add a button to clear all the input fields using <input type=”reset”>tag.

Example:

4. Input Type: radio

<input type="radio"> defines a radio button. Radio buttons let a user select ONLY

ONE of a limited number of choices:

Example:

5. Input Type: checkbox

<input type="checkbox"> defines a checkbox. Checkboxes let a user select ZERO or

MORE options of a limited number of choices.

Example:

Figure 8.2

Figure 8.3

Figure 8.4

Figure 8.5

Page 38: 4. HTML Guide - To Print

Web Designing with HTML, CSS and JavaScript

Page 34

Sri Lanka Anti Narcotics Association

6. Input Type: button

<input type="button”> defines a button.

Example:

Its behavior is identical to the behavior of form element <button>

7. Input Type: file

<input type="file”> defines a file element: with this you can upload a file to server.

Example:

8.3. HTML5 Input Types HTML5 added several new input types. Some of these tags won’t be supported in old

versions of browsers they will behave as input type text.

Input type Description

color Is used for input fields that should contain a color.

date Is used for input fields that should contain a date.

datetime Allows the user to select a date and time (with time zone).

datetime-local Allows the user to select a date and time (no time zone).

email Is used for input fields that should contain an e-mail address.

month Allows the user to select a month and year.

number Is used for input fields that should contain a numeric value

range Is used for input fields that should contain a value within a range.

search Is used for search fields (a search field behaves like a regular text field).

tel Is used for input fields that should contain a telephone number (supported

only in Safari 8.)

time Allows the user to select a time (no time zone).

url Is used for input fields that should contain a URL address.

week Allows the user to select a week and year.

Figure 8.6

Figure 8.7

Table 8.2

Page 39: 4. HTML Guide - To Print

Web Designing with HTML, CSS and JavaScript

Page 35

Sri Lanka Anti Narcotics Association

Input Restrictions

Here is a list of some common input restrictions (some are new in HTML5):

Attribute Description after HTML5

disabled Specifies that an input field should be disabled No

max Specifies the maximum value for an input field Yes

maxlength Specifies the maximum number of character for an input field No

min Specifies the minimum value for an input field Yes

pattern Specifies a regular expression to check the input value against Yes

readonly Specifies that an input field is read only (cannot be changed) No

required Specifies that an input field is required (must be filled out) Yes

size Specifies the width (in characters) of an input field No

step Specifies the legal number intervals for an input field Yes

value Specifies the default value for an input field No

8.4. HTML Form Elements

The most important form element is the <input> element. The<input> element can vary

in many ways, depending on the type attribute.

1. The <select> Element (Drop-Down List)

The <select> element defines a drop-down list:

Example:

The <option> elements define the options to select. The list will normally show the first

item as selected. You can add a selected attribute to define a predefined option.

Example:

2. The <textarea> Element

The <textarea> element defines a multi-line input field (a text area):

Example:

Figure 8.8

Figure 8.9

Table 8.3

Page 40: 4. HTML Guide - To Print

Web Designing with HTML, CSS and JavaScript

Page 36

Sri Lanka Anti Narcotics Association

8.5. HTML5 Form Elements HTML5 added the following form elements:

<datalist>

<keygen>

<output>

By default, browsers do not display unknown elements. New elements will not destroy

your page.

8.6. HTML5 <datalist> Element

The <datalist> element specifies a list of pre-defined options for an <input>element.

Users will see a drop-down list of pre-defined options as they input data. The list attribute

of the <input> element, must refer to the id attribute of the <datalist> element.

Example:

An <input> element with pre-defined values in a <datalist>:

8.7. Iframes An iframe is used to display a web page within a web page.

The syntax for adding an iframe is: <iframe src="URL"></iframe>

The src attribute specifies the URL (web address) of the iframe page.

Use the height and width attributes to specify the size.

The attribute values are specified in pixels by default, but they can also be in percent (like

"80%").

Example:

Scroll bar

IFrame

Figure 8.10

Figure 8.11

Page 41: 4. HTML Guide - To Print

Web Designing with HTML, CSS and JavaScript

Page 37

Sri Lanka Anti Narcotics Association

8.8. Colors

Colors are displayed combining RED, GREEN, and BLUE light.

The combination of Red, Green and Blue values from 0 to 255 gives a total of more than

16 million different colors to play with (28 x 2

8 x 2

8= 2

24≈ 16 million).

Most modern monitors are capable of displaying at least 16384 different colors.

When computers only supported 256 different colors, a list of 216 "Web Safe Colors"

was suggested as a Web standard, reserving 40 fixed system colors.

This 216 cross-browser color palette was created to ensure that all computers would

display colors correctly.

Web Safe Colors:

Figure 8.12

Page 42: 4. HTML Guide - To Print

Web Designing with HTML, CSS and JavaScript

Page 38

Sri Lanka Anti Narcotics Association

8.9. Symbols

Many mathematical, technical, and currency symbols, are not present on a normal

keyboard.

To add these symbols to an HTML page, you can use an HTML entity name.

If no entity name exists, you can use an entity number; a decimal (or hexadecimal)

reference.

Mathematical Symbols:

Char Number Entity Description

∀ &#8704; &forall; FOR ALL

∂ &#8706; &part; PARTIAL DIFFERENTIAL

∃ &#8707; &exist; THERE EXISTS

∅ &#8709; &empty; EMPTY SETS

∇ &#8711; &nabla; NABLA

∈ &#8712; &isin; ELEMENT OF

∉ &#8713; &notin; NOT AN ELEMENT OF

∋ &#8715; &ni; CONTAINS AS MEMBER

∏ &#8719; &prod; N-ARY PRODUCT

∑ &#8721; &sum; N-ARY SUMMATION

Other Symbols:

Example:

Char Number Entity Description

© &#169; &copy; COPYRIGHT SIGN

® &#174; &reg; REGISTERED SIGN

€ &#8364; &euro; EURO SIGN

™ &#8482; &trade; TRADEMARK

← &#8592; &larr; LEFTWARDS ARROW

↑ &#8593; &uarr; UPWARDS ARROW

→ &#8594; &rarr; RIGHTWARDS ARROW

↓ &#8595; &darr; DOWNWARDS ARROW

♠ &#9824; &spades; BLACK SPADE SUIT

♣ &#9827; &clubs; BLACK CLUB SUIT

♥ &#9829; &hearts; BLACK HEART SUIT

♦ &#9830; &diams; BLACK DIAMOND SUIT

Figure 8.12

Table 8.4

Table 8.5

Page 43: 4. HTML Guide - To Print

Web Designing with HTML, CSS and JavaScript

Page 39

Sri Lanka Anti Narcotics Association

Chapter 9 HTML5

9.1. HTML5 Introduction

HTML5 is the fifth revision and newest version of the HTML standard. It offers new

features that provide not only rich media support, but also enhance support for creating web

applications that can interact with the user, his/her local data, and servers, more easily and

effectively than was possible previously.

The DOCTYPE declaration for HTML5:

The character encoding (charset) declaration:

Sample Code:

9.2. HTML5 Supports

HTML5 is supported in all modern browsers.

In addition, all browsers, old and new, automatically handle unrecognized elements as

inline elements.

9.3. HTML5 Elements

Many web sites contain HTML code like: <div id="nav"><div class="header"><div

id="footer">to indicate navigation, header, and footer.

HTML5 offers new semantic elements to define different parts of a web page:

<article>

<aside>

<details>

<section>

<figcaption>

<figure>

<footer>

<nav>

<header>

<main>

<time>

<summary>

Page 44: 4. HTML Guide - To Print

Web Designing with HTML, CSS and JavaScript

Page 40

Sri Lanka Anti Narcotics Association

Design view of HTML5 page:

Example:

Figure 9.1

Page 45: 4. HTML Guide - To Print

Web Designing with HTML, CSS and JavaScript

Page 41

Sri Lanka Anti Narcotics Association

Output:

9.4. HTML5 Migration

Figure 9.2

Figure 9.3

Page 46: 4. HTML Guide - To Print

Web Designing with HTML, CSS and JavaScript

Page 42

Sri Lanka Anti Narcotics Association

Chapter 10 HTML Media 10.1. Introduction

Multimedia comes in many different formats. It can be almost anything you can hear or

see.

Examples: Pictures, music, sound, videos, records, films, animations, and more.

Web pages often contain multimedia elements of different types and formats.

1. Multimedia Formats

Multimedia elements (like sounds or videos) are stored in media files.

The most common way to discover the type of a file, is to look at the file extension.

When a browser sees the file extension .htm or .html, it will treat the file as an HTML

file. The .xml extension indicates an XML file, and the .css extension indicates a style

sheet file. Pictures are recognized by extensions like .gif, .png and .jpg.

Multimedia files also have their own formats and different extensions like: .swf, .wav,

.mp3, .mp4, .mpg, .wmv, and .avi.

2. Common Video Formats

MP4 is the new and upcoming format for internet video.

MP4 is recommended by YouTube.

MP4 is supported by Flash Players

MP4 is supported by HTML5.

Format File Description

MPEG .mpg

.mpeg

MPEG. Developed by the Moving Pictures Expert Group. The first

popular video format on the web. Used to be supported by all browsers,

but it is not supported in HTML5 (See MP4).

AVI .avi AVI (Audio Video Interleave). Developed by Microsoft. Commonly

used in video cameras and TV hardware. Plays well on Windows

computers, but not in web browsers.

WMV .wmv WMV (Windows Media Video). Developed by Microsoft. Commonly

used in video cameras and TV hardware. Plays well on Windows

computers, but not in web browsers.

QuickTime .mov QuickTime. Developed by Apple. Commonly used in video cameras

and TV hardware. Plays well on Apple computers, but not in web

browsers. (See MP4)

RealVideo .rm

.ram

RealVideo. Developed by Real Media to allow video streaming with

low bandwidths. It is still used for online video and Internet TV, but

does not play in web browsers.

Flash .swf

.flv

Flash. Developed by Macromedia. Often requires an extra component

(plug-in) to play in web browsers.

Ogg .ogg TheoraOgg. Developed by the Xiph.Org Foundation. Supported by

HTML5.

Page 47: 4. HTML Guide - To Print

Web Designing with HTML, CSS and JavaScript

Page 43

Sri Lanka Anti Narcotics Association

WebM .webm WebM Developed by the web giants, Mozilla, Opera, Adobe, and

Google. Supported by HTML5.

MPEG-4

or MP4

.mp4 MP4. Developed by the Moving Pictures Expert Group. Based on

QuickTime. Commonly used in newer video cameras and TV hardware.

Supported by all HTML5 browsers. Recommended by YouTube.

3. Sound Formats

MP3 is the newest format for compressed recorded music. The term MP3 has become

synonymous with digital music.

If your website is about recorded music, MP3 is the choice.

10.2. HTML5 Media Elements

1. HTML5 Audio

Before HTML5, there was no standard for playing audio files on a web page.

Before HTML5, audio files could only be played with a plug-in (like flash).

The HTML5 <audio> element specifies a standard way to embed audio in a web page.

The controls attribute adds audio controls, like play, pause, and volume.

Text between the <audio> and </audio> tags will display in browsers that do not

support the <audio> element.

Multiple <source> elements can link to different audio files. The browser will use the

first recognized format.

Format File Description

MIDI .mid

.midi

MIDI (Musical Instrument Digital Interface). Main format for all

electronic music devices like synthesizers and PC sound cards. MIDI files

do not contain sound, but digital notes that can be played by electronics.

Plays well on all computers and music hardware, but not in web browsers.

RealAudio .rm

.ram

RealAudio. Developed by Real Media to allow streaming of audio with

low bandwidths. Does not play in web browsers.

WMA .wma WMA (Windows Media Audio). Developed by Microsoft. Commonly

used in music players. Plays well on Windows computers, but not in web

browsers.

AAC .aac AAC (Advanced Audio Coding). Developed by Apple as the default

format for iTunes. Plays well on Apple computers, but not in web

browsers.

WAV .wav WAV. Developed by IBM and Microsoft. Plays well on Windows,

Macintosh, and Linux operating systems. Supported by HTML5.

Ogg .ogg Ogg. Developed by the Xiph.Org Foundation. Supported by HTML5.

MP3 .mp3 MP3 files are actually the sound part of MPEG files. MP3 is the most

popular format for music players. Combines good compression (small

files) with high quality. Supported by all browsers.

MP4 .mp4 MP4 is a video format, but can also be used for audio. MP4 video is the

upcoming video format on the internet. This leads to automatic support

for MP4 audio by all browsers.

Table 10.1

Table 10.2

Page 48: 4. HTML Guide - To Print

Web Designing with HTML, CSS and JavaScript

Page 44

Sri Lanka Anti Narcotics Association

HTML5 Audio - Media Types

To play an audio file in HTML, use the <audio> element:

2. HTML5 Video

To show a video in HTML, use the <video> element:

HTML5Video - Media Types

File Format Media Type

MP3 audio/mpeg

Ogg audio/ogg

Wav audio/wav

File Format Media Type

MP4 video/mp4

WebM video/webm

Ogg video/ogg

Enable Player Controls

Play source when page loads

File name to play

File type

Table 10.3

Table 10.4

Page 49: 4. HTML Guide - To Print

Web Designing with HTML, CSS and JavaScript

Page 45

Sri Lanka Anti Narcotics Association

Chapter 11 JavaScript 11.1. Introduction

JavaScript is the scripting language of the Web.

JavaScript is used in millions of Web pages to improve the design, validate forms, detect

browsers, create cookies, and much more.

JavaScript is the most popular scripting language on the internet.

1. What is JavaScript?

JavaScript was designed to add interactivity to HTML pages.

JavaScript is a scripting language.

A scripting language is a lightweight programming language.

A JavaScript consists of lines of executable computer code.

A JavaScript is usually embedded directly into HTML pages.

JavaScript is an interpreted language. (This means that scripts execute without

preliminary compilation)

Everyone can use JavaScript without purchasing a license.

2. What can a JavaScript Do?

JavaScript gives HTML designers a programming tool.

HTML authors are normally not programmers, but JavaScript is a scripting

language with a very simple syntax. Almost anyone can put small "snippets" of code into

their HTML pages.

3. JavaScript Syntax

To insert a JavaScript into an HTML page, we use the <script> tag. Inside the

<script> tag we use the type attribute to define the scripting language.

So, the <script type="text/javascript"> and </script> tells where

theJavaScript starts and ends:

Syntax:

The two forward slashes at the end of comment line (//) is the JavaScript comment symbol. This prevents JavaScript from executing

Page 50: 4. HTML Guide - To Print

Web Designing with HTML, CSS and JavaScript

Page 46

Sri Lanka Anti Narcotics Association

Example Code (Print Text in the web page):

document.write:

It is a standard JavaScript command for writing output to a page. By entering the

document.write command between the <script> and </script> tags, the

browser will recognize it as a JavaScript command and execute the code line. In this

case the browser will write “Hello, Welcome to JavaScript!!!!!!!”to the

page.

4. Methods to insert JavaScript to HTML page

I. Head section

II. Body section

III. External script

I. Head section

Scripts that contain functions go in the head section of the document. Then we can be

sure that the script is loaded before the function is called. JavaScript in the head section

will be executed when called…

Example Code:

II. Body section

Execute a script that is placed in the body section. JavaScript in the body section will be

executed WHILE the page loads.

Example Code:

Page 51: 4. HTML Guide - To Print

Web Designing with HTML, CSS and JavaScript

Page 47

Sri Lanka Anti Narcotics Association

Scripts in both the body and the head section: You can place any number of

scripts in your document, so you can have scripts in both the body and the head

section.

III. External script

Using an External JavaScript, You can write a JavaScript in an external file as we did

with the CSS. Save the external JavaScript file with.js file extension.

The external script cannot contain the <script> tag. To use the external script, point

tothe.js file in the "src" attribute of the <script> tag.

Example Code:

11.2. Variables in JavaScript

A variable is a "container" for information you want to store. A variable's value can

change during the script. You can refer to a variable by name to see its value or tochange

its value.

1. Rules for variable names:

Variable names are case sensitive.

They must begin with a letter or the underscore character.

You can declare JavaScript variables with the “var” keyword.

Example:

After the declaration shown above, the variables are empty (they have no values

yet). You can also assign values to the variables when you declare them as below.

Example

After the execution of the statements above, the variable myFirstNumber will hold

HTML Page Code

ExternalScript.js

varmyFirstNumber;

var _variableString;

varmyFirstNumber = 10;

var _variableString = “ABC”;

Page 52: 4. HTML Guide - To Print

Web Designing with HTML, CSS and JavaScript

Page 48

Sri Lanka Anti Narcotics Association

the value 10, and _variableString will hold the value “ABC”. Example:

11.3. Conditional Statements with JavaScript

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 if you want to execute some code only if a specified condition is

true.

if...else statement

Use this statement if you want to execute some code if the conditions true and

another code if the condition is false.

if...else if....else statement

Use this statement if you want to select one of many blocks of code to be executed.

switch statement

Use this statement if you want to select one of many blocks of code to be executed.

1. If Statement

You should use if statement if you want to execute some code only if a specified

condition is true.

Example:

Figure 11.1

Page 53: 4. HTML Guide - To Print

Web Designing with HTML, CSS and JavaScript

Page 49

Sri Lanka Anti Narcotics Association

2. If...else Statement

If you want to execute some code if a condition is true and another code if the condition

is not true, use if...else statement.

Example:

3. If...else if...else Statement

You should use if....else if...else statement if you want to select one of many sets of lines

to execute.

Example:

Page 54: 4. HTML Guide - To Print

Web Designing with HTML, CSS and JavaScript

Page 50

Sri Lanka Anti Narcotics Association

4. Switch Statement

You should use the switch statement if you want to select one of many blocks of code to

be executed.

Example:

11.4. Operators in JavaScript

1. Arithmetic Operators

Arithmetic operators are used to perform arithmetic between variables and/or values

Operator Description Example Result

+ Addition x=5,y=2

x+y 7

- Subtraction x=9,y=2

x-y 7

* Multiplication x=10,y=9

x*y 90

/ Division x=100,y=2

x/y 50

% Modulus (Remainder) x=21,y=6

x%y 3

++ Increment x=12

x++ 13

-- Decrement x=12

x-- 11

Table 11.1

Page 55: 4. HTML Guide - To Print

Web Designing with HTML, CSS and JavaScript

Page 51

Sri Lanka Anti Narcotics Association

2. Assignment Operators

Assignment operators are used to assign values to JavaScript variables.

Operator Example Same As

= x = y x = y

+= x += y x = x + y

-= x -= y x = x - y

*= x *= y x = x * y

/= x /= y x = x / y

%= x %= y x = x % y

3. Comparison Operators

Comparison operators are used in logical statements to determine equality or difference

between variables or values.

Assume x=5

4. Logical Operators

Logical operators are used to determine the logic between variables or values.

Assume x=6 and y=3

Operator Description Example

&& and (x < 10 && y > 1) is true

|| or (x == 5 || y == 5) is false

! not !(x == y) is true

11.5. Loops in JavaScript

Very often when you write code, you want the same block of code to run over and over again

in a row. Instead of adding several almost equal lines in a script we can use loops to perform

a task like this.

In JavaScript there are four different kinds of loops:

for - loops through a block of code a specified number of times

for/in - for/in statement loops through the properties of an object.

while - loops through a block of code while a specified condition is true.

do/while - also loops through a block of code while a specified condition is true.

Operator Description Comparing Result

= = equal to x == 8 false

x == 5 true

= = = equal value and equal type x === "5" false

x === 5 true

!= not equal x != 8 true

!= = not equal value or not equal type x !== "5" true

x !== 5 false

> greater than x > 8 false

< less than x < 8 true

>= greater than or equal to x >= 8 false

<= less than or equal to x <= 8 true

Table 11.2

Table 11.3

Table 11.4

Page 56: 4. HTML Guide - To Print

Web Designing with HTML, CSS and JavaScript

Page 52

Sri Lanka Anti Narcotics Association

1. The For Loop

The for loop is often the tool you will use when you want to create a loop.

The for loop has the following syntax:

Execution of loop:

I. Statement 1 is executed before the loop (the code block) starts.

II. Statement 2 defines the condition for running the loop (the code block).

III. Statement 3 is executed each time after the loop (the code block) has been executed.

Example:

2. The For/In Loop

The JavaScript for/in statement loops through the properties of an object.

Example:

3. The While Loop

The while loop loops through a block of code as long as a specified condition is true.

for (statement 1; statement 2; statement 3)

{

//code block to be executed

}

Figure 11.3

Figure 11.2

Page 57: 4. HTML Guide - To Print

Web Designing with HTML, CSS and JavaScript

Page 53

Sri Lanka Anti Narcotics Association

Syntax:

Example:

4. The Do/While Loop

The do/while loop is a variant of the while loop. This loop will execute the code block

once, before checking if the condition is true, then it will repeat the loop as long as the

condition is true.

Syntax:

Example:

while (condition)

{

//code block to be executed

}

do {

//code block to be executed

} while (condition);

Figure 11.4

Figure 11.5

Page 58: 4. HTML Guide - To Print

Web Designing with HTML, CSS and JavaScript

Page 54

Sri Lanka Anti Narcotics Association

11.6. The Break Statement

The break statement can also be used to jump out of a loop.

The break statement breaks the loop and continues executing the code after the loop (if

any)

Example:

11.7. The Continue Statement

The continue statement breaks one iteration (in the loop), if a specified condition occurs,

and continues with the next iteration in the loop.

Example:

11.8. Functions in JavaScript

A JavaScript function is a block of code designed to perform a particular task.

A JavaScript function is executed when "something" invokes it (calls it).

Example for creating function:

functionmyFunction(p1, p2)

{

// Content goes here

}

Use of “function” keyword

Figure 11.6

Figure 11.7

Page 59: 4. HTML Guide - To Print

Web Designing with HTML, CSS and JavaScript

Page 55

Sri Lanka Anti Narcotics Association

Example:

11.9. User Interaction through Dialog Boxes in JavaScript

JavaScript provides several pre-defined pop-up dialog boxes

These can be used to interact with users.

Three types of dialog boxes Alert Dialog Box Confirm Dialog Box

PromptDialogBox

1. Alert Dialog 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.

Example:

2. Confirm Dialog 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.

Figure 11.8

Figure 11.9

Page 60: 4. HTML Guide - To Print

Web Designing with HTML, CSS and JavaScript

Page 56

Sri Lanka Anti Narcotics Association

Example:

3. Prompt Dialog 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 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.

Example:

Figure 11.10

Figure 11.11

Page 61: 4. HTML Guide - To Print

Web Designing with HTML, CSS and JavaScript

Page 57

Sri Lanka Anti Narcotics Association

Get Inputs with JavaScript

Use getElementById() method to access the specified object id in JavaScript.

The innerHTML property sets or returns the HTML content (inner HTML) of an element.

onClick property of button - Execute a JavaScript when a button is clicked.

Example:

Figure 11.12

Page 62: 4. HTML Guide - To Print

Web Designing with HTML, CSS and JavaScript

Page 58

Sri Lanka Anti Narcotics Association

References

W3 Schools for HTML(1999). [ONLINE] Available at:

http://www.w3schools.com/html/. [Last Accessed 2015 January 02].

W3 Schools for CSS(1999). [ONLINE] Available at:

http://www.w3schools.com/css/. [Last Accessed 2015 January 06].

W3 Schools for JavaScript (1999). [ONLINE] Available at:

http://www.w3schools.com/js/. [Last Accessed 2015 January 12].

Stack Exchange. [ONLINE] Available at: http://stackoverflow.com/.

[Last Accessed 2015 January 23].

Tutorials Point. [ONLINE] Available at: http://www.tutorialspoint.com/.

[Last Accessed 2015 January 15].