AS Unit 2 Complete 2 1
AS Unit 2 Complete 2 1
HTML
1. HTML Introduction ........................................................................................................................ 2
2. HTML Basic Examples .................................................................................................................... 4
HTML Paragraphs .............................................................................................................................. 5
3. HTML Elements ............................................................................................................................. 7
4. HTML Attributes ............................................................................................................................ 9
5. HTML Headings............................................................................................................................ 12
6. HTML Paragraphs ........................................................................................................................ 13
7. HTML Styles ................................................................................................................................. 14
8. HTML Text Formatting ................................................................................................................. 16
9. HTML Quotation and Citation Elements ....................................................................................... 19
10. HTML Colors .............................................................................................................................. 22
11. HTML Links - Hyperlinks ............................................................................................................. 24
12. HTML Link Colors ....................................................................................................................... 25
13. HTML Images ............................................................................................................................. 29
14. HTML Tables .............................................................................................................................. 33
15. HTML Lists ................................................................................................................................. 37
16. HTML Block and Inline Elements ................................................................................................ 42
17. HTML The class Attribute ........................................................................................................... 44
18. HTML Forms .............................................................................................................................. 45
19. Access Key, Data, hidden and tab index ..................................................................................... 49
20. Preparing audio and video ......................................................................................................... 51
21 - Block-level elements, inline elements and content models ....................................................... 52
22 - The Semantic Web .................................................................................................................... 53
CSS 54
Java Script 78
1
IAL Information Technology Unit 2 HTML
1. HTML Introduction
HTML is the standard markup language for creating Web pages.
Example Explained
<!DOCTYPE html>
• The <!DOCTYPE html> declaration <html>
defines this document to be HTML5 <head>
• The <html> element is the root <title>Page Title</title>
element of an HTML page </head>
• The <head> element contains meta <body>
information about the document
• The <title> element specifies a title <h1>My First Heading</h1>
for the document <p>My first paragraph.</p>
• The <body> element contains the
visible page content </body>
• The <h1> element defines a large </html
heading
• The <p> element defines a paragraph
HTML Tags
HTML tags are element names surrounded by angle brackets:
Tip: The start tag is also called the opening tag, and the end tag
the closing tag.
2
IAL Information Technology Unit 2 HTML
Web Browsers
The purpose of a web browser (Chrome, IE, Firefox,
Safari, etc.) is to read HTML documents and display
them. The browser does not display the HTML tags,
but uses them to determine how to display the
document:
Note: Only the content inside the <body> section (the white area above) is
displayed in a browser.
It must only appear once, at the top of the page (before any HTML tags).
HTML Versions
Since the early days of the web, there have been many versions of HTML:
3
IAL Information Technology Unit 2 HTML
Version Year
Save the file on your computer. Select File > Save as in the Notepad menu.
Name the file "index.htm" and set the encoding to UTF-8 (which is the
preferred encoding for HTML files).
You can use either .htm or .html as file extension. There is no difference, it is
up to you.
All HTML documents must start with a document type declaration: <!DOCTYPE
html>.
The HTML document itself begins with <html> and ends with </html>.
The visible part of the HTML document is between <body> and </body>.
4
IAL Information Technology Unit 2 HTML
<!DOCTYPE html>
<html>
<body>
</body>
</html>
HTML Headings
HTML headings are defined with the <h1> to <h6> tags.
<h1> defines the most important heading. <h6> defines the least important
heading:
HTML Paragraphs
HTML paragraphs are defined with the <p> tag:
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
HTML Links
HTML links are defined with the <a> tag:
HTML Images
HTML images are defined with the <img> tag.
5
IAL Information Technology Unit 2 HTML
The source file (src), alternative text (alt), width, and height are provided
as attributes:
HTML Buttons
HTML buttons are defined with the <button> tag:
<button>Click me</button>
HTML Lists
HTML lists are defined with the <ul> (unordered/bullet list) or
the <ol> (ordered/numbered list) tag, followed by <li> tags (list items):
<ul>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
<ol>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>
</body>
</html>
6
IAL Information Technology Unit 2 HTML
3. HTML Elements
An HTML element usually consists of a start tag and end tag, with the
content inserted in between:
The HTML element is everything from the start tag to the end tag:
</body></html>
• The <html> element defines the whole
document.
o It has a start tag <html> and an end tag </html>.
• The element content is another HTML element (the <body> element).
o The <body> element defines the document body.
o It has a start tag <body> and an end tag </body>.
• The element content is two other HTML elements (<h1> and <p>).
• The <h1> element defines a heading.
o It has a start tag <h1> and an end tag </h1>.
o The element content is: My First Heading.
• The <p> element defines a paragraph.
o It has a start tag <p> and an end tag </p>.
o The element content is: My first paragraph.
Some HTML elements will display correctly, even if you forget the end tag:
<br> is an empty element without a closing tag (the <br> tag defines a line
break).
Empty elements can be "closed" in the opening tag like this: <br />.
HTML5 does not require empty elements to be closed. But if you want stricter
validation, or if you need to make your document readable by XML parsers,
you must close all HTML elements properly.
8
IAL Information Technology Unit 2 HTML
4. HTML Attributes
Attributes provide additional information about HTML elements.
<img src="img_girl.jpg">
The image size is specified in pixels: width="500" means 500 pixels wide.
9
IAL Information Technology Unit 2 HTML
The value of the attribute can be read by screen readers. This way, someone
"listening" to the webpage, e.g. a blind person, can "hear" the element.
The alt attribute is also useful if the image does not exist: What happens if
we try to display an image that does not exist?
<!DOCTYPE html>
<html lang="en-US">
<body>
...
</body>
</html>
The first two letters specify the language (en). If there is a dialect, use two
more letters (US).
10
IAL Information Technology Unit 2 HTML
The HTML5 standard does not require quotes around attribute values.
Using quotes are the most common. Omitting quotes can produce errors.
Chapter Summary
• All HTML elements can have attributes
• The title attribute provides additional "tool-tip" information
• The href attribute provides address information for links
11
IAL Information Technology Unit 2 HTML
• The width and height attributes provide size information for images
• The alt attribute provides text for screen readers
• At W3Schools we always use lowercase attribute names
• At W3Schools we always quote attribute values with double quotes
Attribute Description
Specifies an alternative text for an image, when the image
alt
cannot be displayed
disabled Specifies that an input element should be disabled
href Specifies the URL (web address) for a link
id Specifies a unique id for an element
src Specifies the URL (web address) for an image
style Specifies an inline CSS style for an element
Specifies extra information about an element (displayed as a
title
tool tip)
5. HTML Headings
Headings are defined with the <h1> to <h6> tags.
<h1> defines the most important heading. <h6> defines the least important
heading.
Search engines use the 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 used for main headings, followed by <h2> headings,
then the less important <h3>, and so on.
Note: Use HTML headings for headings only. Don't use headings to make
text BIG or bold.
Bigger Headings
Each HTML heading has a default size. However, you can specify the size for
any heading with the style attribute, using the CSS font-size property:
12
IAL Information Technology Unit 2 HTML
Right-click in an HTML page and select "View Page Source" (in Chrome) or
"View Source" (in IE), or similar in other browsers. This will open a window
containing the HTML source code of the page.
6. HTML Paragraphs
The HTML <p> element defines a paragraph:
13
IAL Information Technology Unit 2 HTML
The HTML <pre> <p>The pre tag preserves both spaces and line breaks:</p>
Element <pre>
7. HTML Styles
I am Red
I am Blue
I am Big
The HTML Style Attribute
Setting the style of an HTML element, can be done with the style attribute.
<tagname style="property:value;">
14
IAL Information Technology Unit 2 HTML
<body style="background-color:powderblue;">
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
15
IAL Information Technology Unit 2 HTML
HTML Fonts
The font-family property defines the font to be used for an HTML element:
Chapter Summary
• Use the style attribute for styling HTML elements
• Use background-color for background color
• Use color for text colors
• Use font-family for text fonts
• Use font-size for text sizes
• Use text-align for text alignment
Text Formatting
This text is bold
In the previous chapter, you learned about the HTML style attribute.
16
IAL Information Technology Unit 2 HTML
HTML uses elements like <b> and <i> for formatting output,
like bold or italic text.
The HTML <strong> element defines strong text, with added semantic
"strong" importance.
The HTML <em> element defines emphasized text, with added semantic
importance.
Note: Browsers display <strong> as <b>, and <em> as <i>. However, there is
a difference in the meaning of these tags: <b> and <i> defines bold and italic
text, but <strong> and <em> means that the text is "important".
17
IAL Information Technology Unit 2 HTML
18
IAL Information Technology Unit 2 HTML
19
IAL Information Technology Unit 2 HTML
20
IAL Information Technology Unit 2 HTML
Comments are also great for debugging HTML, because you can comment
out HTML lines of code, one at a time, to search for errors:
21
IAL Information Technology Unit 2 HTML
HTML colors are specified using predefined color names, or RGB, HEX,
HSL, RGBA, HSLA values.
Background Color
You can set the background color for HTML elements:
Text Color
You can set the color of text:
Border Color
You can set the color of borders
Color Values
In HTML, colors can also be specified using RGB values, HEX values, HSL
values, RGBA values, and HSLA values:
22
IAL Information Technology Unit 2 HTML
RGB Value
In HTML, a color can be specified as an RGB value, using this formula:
To display the color black, all color parameters must be set to 0, like this:
rgb(0, 0, 0).
To display the color white, all color parameters must be set to 255, like this:
rgb(255, 255, 255).
HEX Value
In HTML, a color can be specified using a hexadecimal value in the form:
#rrggbb
Where rr (red), gg (green) and bb (blue) are hexadecimal values between 00
and ff (same as decimal 0-255).
For example, #ff0000 is displayed as red, because red is set to its highest
value (ff) and the others are set to the lowest value (00).
23
IAL Information Technology Unit 2 HTML
HSL Value
In HTML, a color can be specified using hue, saturation, and lightness (HSL)
in the form:
Saturation
• Saturation can be described as the intensity of a color.
• 100% is pure color, no shades of gray
• 50% is 50% gray, but you can still see the color.
• 0% is completely gray, you can no longer see the color.
Lightness
The lightness of a color can be described as how much light you want to give
the color, where 0% means no light (black), 50% means 50% light (neither
dark nor light) 100% means full lightness (white).
Shades of gray are often defined by setting the hue and saturation to 0, and
adjust the lightness from 0% to 100% to get darker/lighter shades:
RGBA Value
RGBA color values are an extension of RGB color values with an alpha
channel - which specifies the opacity for a color. An RGBA color value is
specified with:
24
IAL Information Technology Unit 2 HTML
When you move the mouse over a link, the mouse arrow will turn into a little
hand.
Note: A link does not have to be text. It can be an image or any other HTML
element.
The link text is the visible part (Visit our HTML tutorial).
Clicking on the link text will send you to the specified address.
Note: Without a forward slash at the end of subfolder addresses, you might
generate two requests to the server. Many servers will automatically add a
forward slash to the end of the address, and then create a new request.
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....).
25
IAL Information Technology Unit 2 HTML
<style>
a:link {
color: green;
background-color: transparent;
text-decoration: none;
}
a:visited {
color: pink;
background-color: transparent;
text-decoration: none;
}
a:hover {
color: red;
background-color: transparent;
text-decoration: underline;
}
a:active {
color: yellow;
background-color: transparent;
text-decoration: underline;
}
</style>
26
IAL Information Technology Unit 2 HTML
This example will open the linked document in a new browser window/tab:
<a href="default.asp">
<img src="smiley.gif" alt="HTML
tutorial" style="width:42px;height:42px;border:0;">
</a>
Link Titles
The title attribute specifies extra information about an element. The
information is most often shown as a tooltip text when the mouse moves
over the element.
27
IAL Information Technology Unit 2 HTML
HTML bookmarks are used to allow readers to jump to specific parts of a Web
page. Bookmarks can be useful if your webpage is very long. To make a
bookmark, you must first create the bookmark, and then add a link to it.
When the link is clicked, the page will scroll to the location with the
bookmark.
Example
First, create a bookmark with the id attribute:
Then, add a link to the bookmark ("Jump to Chapter 4"), from within the
same page:
Or, add a link to the bookmark ("Jump to Chapter 4"), from another page:
External Paths
External pages can be referenced with a full URL or with a path relative to
the current web page.
This example links to a page located in the html folder on the current web
site:
This example links to a page located in the same folder as the current page:
28
IAL Information Technology Unit 2 HTML
Chapter Summary
• Use the <a> element to define a link
• Use the href attribute to define the link address
• Use the target attribute to define where to open the linked document
• Use the <img> element (inside <a>) to use an image as a link
• Use the id attribute (id="value") to define bookmarks in a page
• Use the href attribute (href="#value") to link to the bookmark
29
IAL Information Technology Unit 2 HTML
The width and height attributes always defines the width and height of the
image in pixels.
Actually, you can access images from any web address in the world:
Image as a Link
To use an image as a link, put the <img> tag inside the <a> tag
<a href="default.asp">
<img src="smiley.gif" alt="HTML
tutorial" style="width:42px;height:42px;border:0;">
</a>
Image Maps
30
IAL Information Technology Unit 2 HTML
In the image below, click on the computer, the phone, or the cup of coffee:
<map name="workmap">
<area shape="rect" coords="34,44,270,350" alt="Computer" href="computer.htm">
<area shape="rect" coords="290,172,333,250" alt="Phone" href="phone.htm">
<area shape="circle" coords="337,300,44" alt="Coffee" href="coffee.htm">
</map>
The name attribute of the <map> tag is associated with the <img>'s usemap
attribute and creates a relationship between the image and the map.
The <map> element contains a number of <area> tags, that define the
clickable areas in the image-map.
Background Image
To add a background image on an HTML element, use the CSS
property background-image:
<body style="background-image:url('clouds.jpg')">
<h2>Background Image</h2></body>
<p style="background-image:url('clouds.jpg')">
...
</p>
</body>
31
IAL Information Technology Unit 2 HTML
Each <source> element have attributes describing when their image is the
most suitable.
The browser will use the first <source> element with matching attribute
values, and ignore any following <source>elements.
<picture>
<source media="(min-width: 650px)" srcset="img_pink_flowers.jpg">
<source media="(min-width: 465px)" srcset="img_white_flower.jpg">
<img src="img_orange_flowers.jpg" alt="Flowers" style="width:auto;
">
</picture>
32
IAL Information Technology Unit 2 HTML
Each table row is defined with the <tr> tag. A table header is defined with
the <th> tag. By default, table headings are bold and centered. A table
data/cell is defined with the <td> tag.
Example
<table style="width:100%">
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
</table>
33
IAL Information Technology Unit 2 HTML
table, th, td {
border: 1px solid black;
}
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 15px;
}
th {
text-align: left;
}
34
IAL Information Technology Unit 2 HTML
To set the border spacing for a table, use the CSS border-spacing property:
table {
border-spacing: 5px;
}
<table style="width:100%">
HTML Table - <tr>
<th>Name</th>
Cells that Span <th colspan="2">Telephone</th>
</tr>
Many Columns
<tr>
<td>Bill Gates</td>
<td>55577854</td>
To make a cell span more than <td>55577855</td>
one column, use </tr>
the colspan attribute: </table>
<table style="width:100%">
<tr>
<th>Name:</th>
<td>Bill Gates</td>
HTML Table - Cells
</tr>
<tr>
that Span Many Rows
<th rowspan="2">Telephone:</th>
<td>55577854</td> To make a cell span more than one
</tr> row, use the rowspan attribute:
<tr>
<td>55577855</td>
</tr>
</table>
<table style="width:100%">
<caption>Monthly savings</caption>
35
IAL Information Technology Unit 2 HTML
Table
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
To define a special style for a special table, </tr>
add an id attribute to the table <tr>
<td>Eve</td>
Now you can define a special style for <td>Jackson</td>
<td>94</td>
this table: </tr>
</table>
table#t01 {
width: 100%;
background-color: #f1f1c1; table#t01 tr:nth-child(even) {
background-color: #eee;
}
}
Chapter Summary
• Use the HTML <table> element to define a table
• Use the HTML <tr> element to define a table row
• Use the HTML <td> element to define a table data
• Use the HTML <th> element to define a table heading
• Use the HTML <caption> element to define a table caption
• Use the CSS border property to define a border
• Use the CSS border-collapse property to collapse cell borders
• Use the CSS padding property to add padding to cells
• Use the CSS text-align property to align cell text
• Use the CSS border-spacing property to set the spacing between
cells
• Use the colspan attribute to make a cell span many columns
• Use the rowspan attribute to make a cell span many rows
• Use the id attribute to uniquely define one table
36
IAL Information Technology Unit 2 HTML
The list items will be marked with bullets (small black circles) by default:
<ul>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
Example - Disc
<ul style="list-style-type:disc">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
Example - Circle
<ul style="list-style-type:circle">
<li>Coffee</li>
<li>Tea</li>
37
IAL Information Technology Unit 2 HTML
<li>Milk</li>
</ul>
Example - Square
<ul style="list-style-type:square">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
Example - None
<ul style="list-style-type:none">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
<ol>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>
38
IAL Information Technology Unit 2 HTML
Numbers:
<ol type="1">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>
Uppercase Letters:
<ol type="A">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>
Lowercase Letters:
<ol type="a">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>
39
IAL Information Technology Unit 2 HTML
<dl>
<dt>Coffee</dt>
<dd>- black hot drink</dd>
<dt>Milk</dt>
<dd>- white cold drink</dd>
</dl>
<ul>
<li>Coffee</li>
<li>Tea
<ul>
<li>Black tea</li>
<li>Green tea</li>
</ul>
</li>
<li>Milk</li>
</ul>
By default, an ordered list will start counting from 1. If you want to start
counting from a specified number, you can use the start attribute:
<ol start="50">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>
<!DOCTYPE html>
<html>
<head>
<style>
ul {
list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden;
background-color: #333333;
}
li {
float: left;
}
li a {
display: block;
color: white;
text-align: center;
padding: 16px;
text-decoration: none;
}
li a:hover {
background-color: #111111;
}
</style>
</head>
<body>
<ul>
<li><a href="#home">Home</a></li>
<li><a href="#news">News</a></li>
<li><a href="#contact">Contact</a></li>
<li><a href="#about">About</a></li>
</ul>
41
IAL Information Technology Unit 2 HTML
</body>
</html>
Chapter Summary
• Use the HTML <ul> element to define an unordered list
• Use the CSS list-style-type property to define the list item marker
• Use the HTML <ol> element to define an ordered list
• Use the HTML type attribute to define the numbering type
• Use the HTML <li> element to define a list item
• Use the HTML <dl> element to define a description list
• Use the HTML <dt> element to define the description term
• Use the HTML <dd> element to describe the term in a description list
• Lists can be nested inside lists
• List items can contain other HTML elements
• Use the CSS property float:left or display:inline to display a list
horizontally
Block-level Elements
A block-level element always starts on a new line and takes up the full width
available (stretches out to the left and right as far as it can).
<div>Hello</div>
<div>World</div>
42
IAL Information Technology Unit 2 HTML
Inline Elements
An inline element does not start on a new line and only takes up as much
width as necessary.
<span>Hello</span>
<span>World</span>
The <div> element has no required attributes, but style, class and id are
common.
When used together with CSS, the <div> element can be used to style blocks
of content:
<div style="background-color:black;color:white;padding:20px;">
<h2>London</h2>
<p>London is the capital city of England. It is the most populous city
in the United Kingdom, with a metropolitan area of over 13 million
inhabitants.</p>
</div>
The <span> element has no required attributes, but style, class and id are
common.
When used together with CSS, the <span> element can be used to style parts
of the text:
43
IAL Information Technology Unit 2 HTML
The class name can be used by CSS and JavaScript to perform certain tasks
for elements with the specified class name.
In CSS, to select elements with a specific class, write a period (.) character,
followed by the name of the class:
Use CSS to style all elements with the class name "city":
<style>
.city {
background-color: tomato;
color: white;
padding: 10px;
}
</style>
<h2 class="city">London</h2>
<p>London is the capital of England.</p>
<h2 class="city">Paris</h2>
<p>Paris is the capital of France.</p>
<h2 class="city">Tokyo</h2>
<p>Tokyo is the capital of Japan.</p>
44
IAL Information Technology Unit 2 HTML
id
The Id is used to identify the form distinctly from other elements on the page (and
is often used by scripts — such as those that check you have entered information into fields
that require values).
45
IAL Information Technology Unit 2 HTML
<input type="radio"> Defines a radio button (for selecting one of many choices)
Text Input
<input type="text"> defines a one-line input field for text input:
<form>
First name:<br>
<input type="text" name="firstname"><br>
Last name:<br>
<input type="text" name="lastname">
</form>
If the type attribute is omitted, the input field gets the default type: "text".
<form>
<input type="radio" name="gender" value="male" checked> Male<br>
<input type="radio" name="gender" value="female"> Female<br>
<input type="radio" name="gender" value="other"> Other
</form>
46
IAL Information Technology Unit 2 HTML
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:
<form action="/action_page.php">
First name:<br>
<input type="text" name="firstname" value="Mickey"><br>
Last name:<br>
<input type="text" name="lastname" value="Mouse"><br><br>
<input type="submit" value="Submit">
</form>
Visible Values:
47
IAL Information Technology Unit 2 HTML
Use the multiple attribute to allow the user to select more than one value:
The rows attribute specifies the visible number of lines in a text area.
In the example above, the form data is sent to a page on the server called
"/action_page.php". This page contains a server-side script that handles the
form data: <form action="/action_page.php">
If the action attribute is omitted, the action is set to the current page.
The default value is "_self" which means the form will be submitted in the
current window.
To make the form result open in a new browser tab, use the value " _blank"
48
IAL Information Technology Unit 2 HTML
<form action="/action_page.php">
<fieldset>
<legend>Personal information:</legend>
First name:<br>
<input type="text" name="firstname" value="Mickey"><br>
Last name:<br>
<input type="text" name="lastname" value="Mouse"><br><br>
<input type="submit" value="Submit">
</fieldset>
</form>
<ul>
</ul>
</body> </html>
The tabindex attribute specifies the tab order of an element (when
the "tab" button is used for navigating).
<!DOCTYPE html>
<html> <body>
<a href="https://www.w3schools.com/" tabindex="2">W3Schools</a><br>
49
IAL Information Technology Unit 2 HTML
</body> </html>
The hidden attribute is a boolean attribute. When present, it specifies that an element is
not yet, or is no longer, relevant. Browsers should not display elements that have the
hidden attribute specified.
<!DOCTYPE html>
<html><body>
<p hidden>This paragraph should be hidden.</p>
<p>This is a visible paragraph.</p>
Email Link
<p>
50
IAL Information Technology Unit 2 HTML
<html><body>
<p>The following example displays product names but also associates each name with a product number:</p>
<ul>
</ul>
</body></html>
• <audio></audio>
• <video></video>
• controls
• <source> (can include multiple sound files in different formats to combat possible
browser playback issues)
• type
• autoplay
• loop
<audio controls autoplay loop>
<source src=“barkingDogs.mp3” type=“audio/mpeg”>
<source src=“barkingDogs.wav type=“audio/wav”>
</audio>
<video controls width=“320” height=“240”>
<source src=“barkingDogs/mp4”>
<source src=“barkingDogs/ogg “>
</video>
51
IAL Information Technology Unit 2 HTML
52
IAL Information Technology Unit 2 HTML
53
CSS Tutorial
<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 websites, 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.
• CSS removed the style formatting from the HTML page!
CSS Syntax
54
CSS Tutorial
CSS Selectors
CSS selectors are used to "find" (or select) HTML
elements based on their element name, id, class,
attribute, and more.
The id Selector
The id selector uses the id attribute of
an HTML element to select a specific
element.
55
CSS Tutorial
You can also specify that only specific HTML elements should be affected by a class. In the
example below, only <p> elements with class="center" will be center-aligned:
HTML elements can also refer to more than one class. In the
example below, the <p> element will be styled according to
class="center" and to class="large":
56
CSS Tutorial
Grouping Selectors
If you have elements with the same style definitions, like this ->
It will be better to group the selectors, to minimize the code. To
group selectors, separate each selector with a comma.
In the example below we have grouped the selectors from the
code above:
CSS Comments
Comments are used to explain the code, and may help when you edit the source code at a
later date. Comments are ignored by browsers.
A CSS comment starts with /* and ends with */. Comments can also span multiple lines:
Exercises
1. Change the color of all <p> elements to "red".
2. Change the color of the element with id="para1", to "red".
3. Change the color of all elements with the class "colortext", to "red".
4. Change the color of all <p> and <h1> elements, to "red". Group the
selectors to minimize code.
57
CSS Tutorial
Do not add a space between the property value and the unit (such as margin-left: 20 px;).
58
CSS Tutorial
Inline Styles
An inline style may be used to apply a unique style for a single element.
To use inline styles, add the style attribute to the relevant element. The style attribute can
contain any CSS property.
The example below shows how to change the color and the left margin of a <h1> element:
An inline style loses many of the advantages of a style sheet (by mixing content with
presentation). Use this method sparingly.
Assume that an external style sheet has the following style for the <h1> element: set to navy blue.
Then, assume that an internal style sheet also has the following style for the <h1> element to
orange. If the internal style is defined after the link to the external style sheet, the <h1>
elements will be "orange":
Cascading Order
What style will be used when there is more than one style specified for an HTML element?
Generally speaking we can say that all the styles will "cascade" into a new "virtual" style sheet
by the following rules, where number one has the highest priority:
59
CSS Tutorial
The CSS margin properties are used to create space around elements,
outside of any defined borders.
With CSS, you have full control over the margins. There are properties for
setting the margin for each side of an element (top, right, bottom, and left).
• margin-top
• margin-right
• margin-bottom
• margin-left
p {
margin-top: 100px;
margin-bottom: 100px;
margin-right: 150px;
margin-left: 80px;
}
div {
width: 300px;
margin: auto;
border: 1px solid red;
}
60
CSS Tutorial
div {
border: 1px solid red;
margin-left: 100px;
}
p.ex1 {
margin-left: inherit;
}
Margin Collapse
Top and bottom margins of elements are sometimes collapsed into a single
margin that is equal to the largest of the two margins.
This does not happen on left and right margins! Only top and bottom
margins!
h1 {
margin: 0 0 50px 0;
}
h2 {
margin: 20px 0 0 0;
}
Note: The height and width properties do not include padding, borders, or
margins; they set the height/width of the area inside the padding, border,
and margin of the element!
61
CSS Tutorial
Setting max-width
The max-width property is used to set the maximum width of an element.
The max-width can be specified in length values, like px, cm, etc., or in
percent (%) of the containing block, or set to none (this is default. Means
that there is no maximum width).
The problem with the <div> above occurs when the browser window is
smaller than the width of the element (500px). The browser then adds a
horizontal scrollbar to the page.
The following example shows a <div> element with a height of 100 pixels
and a max-width of 500 pixels:
div {
max-width: 500px;
height: 100px;
background-color: powderblue;
}
CSS Padding
The CSS padding properties are used to generate space around an element's
content, inside of any defined borders.
With CSS, you have full control over the padding. There are properties for
setting the padding for each side of an element (top, right, bottom, and left).
62
CSS Tutorial
div {
padding: 25px 50px 75px 100px;
}
63
CSS Tutorial
• padding: 25px;
o all four paddings are 25px
So, if an element has a specified width, the padding added to that element
will be added to the total width of the element. This is often an undesirable
result.
With the CSS box-sizing Property. The box-sizing property allows us to include
the padding and border in an element's total width and height. If you set box-sizing:
border-box; on an element padding and border are included in the width and height:
Both divs are the same size now!
div {
width: 300px;
padding: 25px;
}
div {
width: 300px;
padding: 25px;
64
CSS Tutorial
box-sizing: border-box;
}
The CSS box model is essentially a box that wraps around every HTML
element. It consists of: margins, borders, padding, and the actual content.
The image below illustrates the box model:
• Content - The content of the box, where text and images appear
• Padding - Clears an area around the content. The padding is
transparent
• Border - A border that goes around the padding and content
• Margin - Clears an area outside the border. The margin is transparent
The box model allows us to add a border around elements, and to define
space between elements.
div {
background-color: lightgrey;
width: 300px;
padding: 25px;
margin: 25px;
Important: When you set the width and height properties of an element
with CSS, you just set the width and height of the content area. To
calculate the full size of an element, you must also add padding, borders and
margins.
65
CSS Tutorial
Total element width = width + left padding + right padding + left border +
right border + left margin + right margin
Total element height = height + top padding + bottom padding + top border
+ bottom border + top margin + bottom margin
CSS Outline
An outline is a line that is drawn around elements, OUTSIDE the borders, to
make the element "stand out".
• outline-style
• outline-color
• outline-width
• outline-offset
• outline
66
CSS Tutorial
Note: Outline differs from borders! Unlike border, the outline is drawn
outside the element's border, and may overlap other content. Also, the
outline is NOT a part of the element's dimensions; the element's total width
and height is not affected by the width of the outlin
Outline Style
p{
The outline-style property specifies the style
border: 2px solid black;
of the outline, and can have one of the
following values: outline: #4CAF50 solid 10px;
margin: auto;
• dotted - Defines a dotted outline,
• dashed - Defines a dashed outline, padding: 10px;
• etc.
text-align: center;
Note: None of the other outline properties will }
have any effect, unless the outline-
style property is set!
<style> p {outline-color:red;}
67
CSS Tutorial
web-safe fonts
• each device comes with its own pre-installed font selection based largely on its
operating system
• problem is systems can differ
• if this is not taken into account then the font a user sees when they view a web
page may not be the font that was intended
• web-safe fonts are fonts that will appear across all operating systems
• designers should specify fonts to fall back to if the font they use is not recognised
by a particular operating system
• common web safe fonts include Arial, Helvetica, Times New Roman etc
• embedding web fonts
The ‘Web safe’ ones, appear across all operating systems. They’re the small collection of fonts
that overlap from Windows to Mac to Google.
Improved Design - Using the same old, plain fonts that have been used for years previously
just doesn’t stand out in the same way it did before. Standard web safe fonts are still great
for large blocks of content, but headers today call for cleaner fonts, more professional fonts,
and better designed fonts. Plus, from a design perspective, we can have more creative
freedom.
Better SEO - Search engines find content and prioritize it on a webpage based on the tags
they’re in. Header tags will take on much more leverage than the alt tag of an image, so it’s
easy to see why using font embedding for headlines, blog post titles, and other important
pieces of content can be better off in a header tag, rather than used as an image.
Ease of Use - Get the font(s) of your choice set up during the development process, and
enjoy lighter maintenance later. No need to create custom images for headers, sliders, or
otherwise. Simply style, and type out whatever content is needed. That content can then
change easily, which is great for updates on your end, and ease of use on a client’s end
Activity 25: Semantic mark up
68
CSS Tutorial
69
CSS Tutorial
White or black can be added to each color to create a different tint or shade until the number
of colors becomes infinite.
Color theory in web design comes down to three main things:
2. Contrast: How we use colors to reduce eyestrain and focus users’ attention to certain
elements on a page.
3. Vibrancy: How we use color to influence the emotions of users or attract a specific target
market.
COMPLEMENTATION
Opposite colors on the color wheel – such as red and green, or purple and yellow – are
complementary. They create a strong contrast, which results in a balance that can draw a
user’s attention and help to build a specific energy.
Split complementary, or compound color schemes, gives designers more wiggle room. Using
two colors from each opposing end of the color wheel, it still provides a contrast, but one
that’s a little softer.
CONTRAST
Contrast is the area of color theory with the biggest impact on the usability of a website. It
refers to the level of clarity between two objects on a page, most notably between text and
background color. Low contrast may look beautiful and harmonious, but it’s much harder to
read, especially if you have a sight disability or are using a mobile device outside on a sunny
day.
The safest choice is a dark color on a light background, or vice versa, although try to avoid
using pure black – in real life, it’s rarely seen and you want to reflect real-world believability.
70
CSS Tutorial
If you’re working with a light background, opt for a dark grey, or a deep blue, green, purple,
etc. for your text instead.
The level of contrast on your website has a profound effect on its accessibility for people with
disabilities that affect their sight. Some 8% of the population suffer from a form of color
blindness. That means choosing the wrong colors, such as red and green, will make your
website virtually unreadable for them. Always choose a high contrast, such as blues and
yellows, and ensure that color is not the only visual cue on the website.
Of course, sometimes your colors are dictated by the logo or wider branding material of the
business or organization. Or you’re targeting a particular community where certain colors
hold certain associations. For example, in China red symbolizes prosperity and happiness.
• Orange: Less overwhelming than red, orange is a cheerful color that evokes joy and
happiness, and is regarded as friendly. Due to its association with the changing seasons, it can
be used to symbolize movement.
• Yellow: The brightest color and often considered the most energizing. Associated with joy,
happiness, sunshine, and intelligence, it’s a positive, optimistic color. Unless you’re in Egypt
where it’s the color of mourning.
71
CSS Tutorial
• Green: Bridging the gap between warm and cool colors, green symbolizes nature and has a
healing quality, therefore has a lot of positive connotations. It’s also used for growth,
harmony, and the environment.
• Blue: A very dependable color, blue signifies stability, expertise, and trust. It’s a calming color,
though the exact hue varies its meaning, with darker tones used for corporate website and
light blues for friendly, open sites, such as social media.
• Purple: Traditionally the color of royalty, dark shades signify sophistication, wealth, and
luxury, while the lighter hues represent spring and romance. Also used for creativity,
imagination, and spirituality, it has different meanings around the world, such as Thailand
where it’s the traditional mourning color for widows.
Neutral colors are mainly used for backgrounds and are often accented with brighter colors
that provide the real impact on the page. They do, however, hold their own associations:
But get your combinations right, and they’ll influence the entire design, from the tone, style
and emotions, to the usability of the website.
72
CSS Tutorial
Principles of accessibility
73
CSS Tutorial
Principles of usability
Usability - when you can conveniently use a product or service and it meets your
expectations.
"The 10 most general principles for interaction design. They are called 'heuristics' because
they are more in the nature of rules of thumb than specific usability guidelines."
• Visibility of system status - The system should always keep users informed about what
is going on, through appropriate feedback within reasonable time.
• Match between system and the real world - The system should speak the users'
language, with words, phrases and concepts familiar to the user, rather than system-
oriented terms.
• User control and freedom - Users often choose system functions by mistake and will
need a clearly marked "emergency exit"
• Consistency and standards - Users should not have to wonder whether different
words, situations, or actions mean the same thing.
• Error prevention - Even better than good error messages is a careful design which
prevents a problem from occurring in the first place.
• Recognition rather than recall - Minimize the user's memory load by making objects,
actions, and options visible. Instructions for use of the system should be visible or
easily retrievable whenever appropriate.
Other menu systems include horizontal scroll, vertical, drop down and button
groups.
74
CSS Tutorial
Cross browser compatible - The ability for a website, web application, HTML
construct or client-side script to support all the web browsers.
Multi-browser means a website will work in several web browsers like Safari, Chrome, Firefox,
Internet Explorer. While cross-browser means a website works in any browser, and any
version of the browser, being used. This can be a struggle for developers throughout the
creation of their websites. Something that makes a website great is when it is
compatible in multiple browsers regardless of version. Technically this is referre d to
as cross browser compatibility.
If a user cannot view your website properly, he will not blame the operating system or
his browser…he will blame the website itself. The goal as developers is to avoid that.
That’s why there are tools available for free, or purchase, to make your cross-browser
checking easier. Examples of software include browser shots, IE tester, sauce labs.
Functional testing is carried out to ensure that the product behaves according to the
functional requirements without taking design principles into consideration. This entails a
series of tests which perform a feature-by-feature validation of behaviour, using a wide range
of normal and erroneous input data.
In contrast, usability testing focuses on customer acceptance and how well the customer
can use the product to complete the required task. Usability testing investigates all aspects
of the usability of a product, including overall structure, navigational flow, and layout of
elements on a page, clarity of content, and overall behaviour
Code validation is the process of checking that the coding of a web page is in compliance
with the standards and recommendations set by the World Wide Web Consortium (W3C) for
the web. Code validation helps to produce clean code.
Web development tools (often called devtools) allow web developers to test and debug their
code. They are different from website builders and integrated development environments
(IDEs) in that they do not assist in the direct creation of a webpage, rather they are tools used
for testing the user interface of a website or web application.
Web development tools come as browser add-ons or built-in features in web browsers.
How do I open browser developer tools?
The JavaScript debugger
1. Firefox: Select ➤ Web Developer ➤ Debugger or press Ctrl + Shift + S to open the JavaScript
Debugger. ...
2. Chrome: Open the Developer tools and then select the Sources tab. ...
3. Edge and Internet Explorer 11: Press F12 and then, Ctrl + 3 , or if the tools are
already displayed, click on the Debugger tab.
Activity 30: Accessibility
75
CSS Tutorial
• Web accessibility is the inclusive practice of ensuring there are no barriers that
prevent interaction with, or access to, websites on the World Wide Web by people
with disabilities
• All users should have equal access to information and functionality
• Web accessibility aims to include
o visual impairments including blindness, various common types of low
vision and poor eyesight and various types of colour blindness
o mobility issues eg difficulty or inability to use hands
o auditory (hearing) issues eg deaf or hard of hearing
o seizures eg people who suffer from epileptic seizures caused by flashing
effects etc
o cognitive and intellectual issues eg developmental or learning difficulties
etc
• WCAG
o guidelines
▪ perceivable – information cannot be invisible to all of a user’s
senses
▪ operable – interface cannot require interaction that a user cannot
perform
▪ understandable – content or operation cannot be beyond their
understanding
▪ robust – interpreted reliably by a wide variety of user agents,
including assistive technologies
• WAI-ARIA
o technical specification published by W3C that specifies how to increase the
accessibility of web pages for assistive technologies such as screen
readers
o set of attributes for plugging the accessibility gaps in HTML5 semantics
o has no effect on how page elements are displayed or behave in browsers
o only use where HTML5 semantics are not available or not enough
o functionality through roles – enables the classification of otherwise
meaningless tags
o states and properties – information on how to interact with a particular
widget
o live regions for dynamic content – allow notifications whenever there are
changes in that particular part of the page
o enhanced keyboard navigation – allows every HTML element to receive
keyboard focus
o things to think about
▪ images
▪ audio and video
▪ colours
▪ text
▪ links
▪ forms
▪ navigation and site structure
(see checklist 1 below)
▪ page regions
▪ labelling regions
▪ headings
▪ content structure
(see checklist 2 below)
o tabindex, data, hidden
▪ tabindex – can be used to set the focus on elements in a particular
order when the user uses the tab key. tabindex=0 is default order,
-1 means no tab stop. Only use them where absolutely necessary
76
CSS Tutorial
77
Java Script
JavaScript
JavaScript is the programming language of HTML and the Web. JavaScript is one of the 3 languages
all web developers must learn:
With the object model, JavaScript gets all the power it needs to create
dynamic HTML:
The HTML DOM is a standard for how to get, change, add, or delete
HTML elements.
In the DOM, all HTML elements are defined as objects. The programming
interface is the properties and methods of each object.
78
Java Script
79
Java Script
This example uses the method to "find" an HTML element (with id="demo")
and changes the element content (innerHTML) to "Hello JavaScript":
<!DOCTYPE html>
<html>
<body>
</html>
<button type="button"
onclick="document.getElementById('demo').style.fontSize='35px'">Click Me!</button>
Hiding an element
<button type="button"
onclick="document.getElementById('demo').style.display='none'">Click Me!</button>
<button type="button"
onclick="document.getElementById('demo').style.display='block'">Click Me!</button
80
Java Script
To manipulate HTML elements you have to find the elements first. There are a couple of
ways to do this:
Exercise 17a
81
Java Script
Exercise 18a
82
Java Script
<script>
document.getElementById("demo").innerHTML = "My First JavaScript";
</script
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>
</head>
<body>
</body>
</html>
External JavaScript
Scripts can also be placed in external files:
83
Java Script
External scripts are practical when the same code is used in many different
web pages. JavaScript files have the file extension .js.
To use an external script, put the name of the script file in the src (source)
attribute of a <script> tag:
<script src="myScript.js"></script>
You can place an external script reference in <head> or <body> as you like.
The script will behave as if it was located exactly where the <script> tag is
located.
To add several script files to one page - use several script tags:
<script src="myScript1.js"></script>
<script src="myScript2.js"></script>
84
Java Script
External References
External scripts can be referenced with a full URL or with a path relative to
the current web page.
<script src="https://www.w3schools.com/js/myScript1.js"></script>
This example uses a script located in a specified folder on the current web
site:
<script src="/js/myScript1.js"></script>
This example links to a script located in the same folder as the current page:
<script src="myScript1.js"></script>
<script>
document.getElementById("demo").innerHTML = 15 + 6;
</script>
Using document.write()
For testing purposes, it is convenient to use document.write():
<script>
document.write(5 + 6);
</script>
Using window.alert()
85
Java Script
<script>
window.alert(5 + 6);
</script>
Using console.log()
For debugging purposes, you can use the console.log() method to display
data
<script>
console.log(5 + 6);
</script>
JavaScript Statements
JavaScript Programs
86
Java Script
JavaScript Statements
JavaScript statements are composed of:
Semicolons ;
Semicolons separate JavaScript statements.
a = 5; b = 6; c = a + b;
If a JavaScript statement does not fit on one line, the best place to break it is
after an operator:
87
Java Script
JavaScript Syntax
JavaScript syntax is the set of rules, how JavaScript programs are
constructed:
JavaScript Values
The JavaScript syntax defines two types of values: Fixed values and variable
values.
Fixed values are called literals. Variable values are called variables.
JavaScript Literals
The most important rules for writing fixed values are:
10.50
1001
"John Doe"
'John Doe'
JavaScript Expressions
An expression is a combination of values, variables, and operators, which
computes to a value.
88
Java Script
5 * 10
JavaScript Keywords
JavaScript keywords are used to identify actions to be performed.
JavaScript Comments
Not all JavaScript statements are "executed".
89
Java Script
JavaScript Identifiers
Identifiers are names.
The rules for legal names are much the same in most programming
languages.
Hyphens:
Hyphens are not allowed in JavaScript. They are reserved for subtractions.
Underscore:
90
Java Script
JavaScript Variables
JavaScript variables are containers for storing data values.
var x = 5;
From the example above, you can calculate the total to be 11.
JavaScript Identifiers
All JavaScript variables must be identified with unique names.
The general rules for constructing names for variables (unique identifiers)
are:
91
Java Script
This is different from algebra. The following does not make sense in algebra:
x = x + 5
(It calculates the value of x + 5 and puts the result into x. The value of x is
incremented by 5.)
JavaScript can handle many types of data, but for now, just think of numbers
and strings.
Strings are written inside double or single quotes. Numbers are written
without quotes.
Example
var pi = 3.14;
var person = "John Doe";
var answer = 'Yes I am!';
92
Java Script
var carName;
After the declaration, the variable has no value. (Technically it has the value
of undefined). To assign a value to the variable, use the equal sign:
carName = "Volvo";
Operator Description
+ Addition
- Subtraction
* Multiplication
** Exponentiation (ES6)
/ Division
Modulus (Division
%
Remainder)
++ Increment
-- Decrement
var x = 10;
x += 5;
93
Java Script
== equal to
=== equal value and equal type
!= not equal
not equal value or not equal
!==
type
> greater than
< less than
>= greater than or equal to
<= less than or equal to
? ternary operator
94
Java Script
JavaScript Functions
A JavaScript function is a block of code designed to perform a particular
task.
Function names can contain letters, digits, underscores, and dollar signs
(same rules as variables).
95
Java Script
Function Invocation
The code inside the function will execute when "something" invokes (calls)
the function:
Function Invocation
The code inside the function will execute when "something" invokes (calls)
the function:
Why Functions?
You can reuse code: Define the code once, and use it many times.
You can use the same code many times with different arguments, to produce
different results.
Example
Convert Fahrenheit to Celsius:
function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}
document.getElementById("demo").innerHTML = toCelsius(77);
96
Java Script
Example
function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}
document.getElementById("demo").innerHTML = toCelsius;
Local Variables
Variables declared within a JavaScript function, become LOCAL to the
function.
Example
// code here can NOT use carName
function myFunction() {
var carName = "Volvo";
// code here CAN use carName
}
Since local variables are only recognized inside their functions, variables with
the same name can be used in different functions.
Local variables are created when a function starts, and deleted when the
function is completed.
97
Java Script
JavaScript Objects
Properties Methods
A car has properties like weight and color, and methods like start and
stop: All cars have the same properties, but the property values differ from
car to car. All cars have the same methods, but the methods are
performed at different times.
JavaScript Objects
You have already learned that JavaScript variables are containers for data
values.
Objects are variables too. But objects can contain many values.
This code assigns many values (Fiat, 500, white) to a variable named car:
The values are written as name:value pairs (name and value separated by a
colon).
Object Definition
You define (and create) a JavaScript object with an object literal:
98
Java Script
Spaces and line breaks are not important. An object definition can span
multiple lines:
var person = {
firstName:"John",
lastName:"Doe",
age:50,
eyeColor:"blue"
};
Object Properties
The name:values pairs in JavaScript objects are called properties:
objectName.propertyName or objectName["propertyName"]
person.lastName;
or
person["lastName"];
Object Methods
Objects can also have methods.
99
Java Script
var person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
objectName.methodName()
name = person.fullName();
name = person.fullName;
JavaScript Events
HTML events are "things" that happen to HTML elements.
HTML Events
An HTML event can be something the browser does, or something a user
does.
100
Java Script
Example
<button onclick="document.getElementById('demo').innerHTML = Date()">The
time is?</button>
In the example above, the JavaScript code changes the content of the
element with id="demo".
In the next example, the code changes the content of its own element
(using this.innerHTML):
Example
<button onclick="this.innerHTML = Date()">The time is?</button>
JavaScript code is often several lines long. It is more common to see event
attributes calling functions:
Example
<button onclick="displayDate()">The time is?</button>
101
Java Script
Event Description
onchange An HTML element has been changed
onclick The user clicks an HTML element
onmouseover The user moves the mouse over an HTML element
The user moves the mouse away from an HTML
onmouseout
element
onkeydown The user pushes a keyboard key
onload The browser has finished loading the page
Many different methods can be used to let JavaScript work with events:
Special Characters
Because strings must be written within quotes, JavaScript will misunderstand
this string:
The backslash (\) escape character turns special characters into string
characters:
102
Java Script
String Length
The length property returns the length of a string:
Both methods accept a second parameter as the starting position for the
search:
103
Java Script
They accept the same arguments (parameters), and return the same value?
The two methods are NOT equal. These are the differences:
104
Java Script
Syntax switch(expression) {
case x:
This is how it works: // code block
break;
• The switch expression is evaluated once. case y:
• The value of the expression is compared // code block
with the values of each case. break;
• If there is a match, the associated block default:
of code is executed. // code block
}
105
Java Script
A break can save a lot of execution time because it "ignores" the execution of
all the rest of the code in the switch block.
In this example case 4 and 5 share the same code block, and 0 and 6 share
another code block:
106
Java Script
JavaScript Loops
Loops are handy, if you want to run the same code over and over again,
each time with a different value.
Instead of writing:
text += cars[0] + "<br>";
text += cars[1] + "<br>";
text += cars[2] + "<br>";
text += cars[3] + "<br>";
text += cars[4] + "<br>";
text += cars[5] + "<br>";
From the example above, you can read: for (i = 0; i < 5; i++) {
text += "The number is
Statement 1 sets a variable before the loop " + i + "<br>";
starts (var i = 0). }
Statement 3 increases a value (i++) each time the code block in the loop has
been executed.
107
Java Script
do {
text += "The number is " + i;
i++;
}
while (i < 10);
Do not forget to increase the variable used in the condition, otherwise the
loop will never end!
108
Java Script
What is an Array?
An array is a special variable, which can hold more than one value at a time.
Creating an Array
Using an array literal is the easiest way to create a JavaScript Array.
109
Java Script
<!DOCTYPE html>
<html> <body>
<script>
var i;
for(i=0;i<=3;i++){
document.getElementById('demo').innerHTML = txt;
110
Java Script
myArray[0] = Date.now;
myArray[1] = myFunction;
myArray[2] = myCars;
111
Java Script
Array.forEach()
The forEach() method calls a function (a callback function) once for each
array element. The output will be the contents of the array.
<p id="demo"></p>
<script>
numbers.forEach(myFunction);
document.getElementById("demo").innerHTML = txt;
function myFunction(value) {
</script>
New element can also be added to an array using the length property:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[fruits.length] = "Lemon"; // adds a new element (Lemon) to
fruits
Adding elements with high indexes can create undefined "holes" in an array:
112
Java Script
Errors can be coding errors made by the programmer, errors due to wrong
input, and other unforeseeable things.
<p id="demo"></p>
<script>
try {
adddlert("Welcome guest!");
}
catch(err) {
document.getElementById("demo").innerHTML = err.message;
}
</script>
113
Java Script
Mouse Events
<!DOCTYPE html>
<html>
<body>
<h1 onmouseover="style.color='red'" onmouseout="style.color='black'">Mouse over this
text</h1>
</body>
</html>
On mouse Down
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction(elmnt, clr) {
elmnt.style.color = clr;
}
</script>
</head>
<body>
<p onmousedown="myFunction(this,'red')" onmouseup="myFunction(this,'green')">
Click the text to change the color. A function, with parameters, is triggered when the mouse
button is pressed down, and again, with other parameters, when the mouse button is
released.
</p>
</body>
</html>
114
Java Script
<!DOCTYPE html>
<script>
function validateF(iform){
iform.namestring.value ); }
</script> </head>
<body>
</form>
</body></html>
115
Java Script
The focus event occurs when an element gets focus (when selected by a
mouse click or by "tab-navigating" to it).
The focus() method triggers the focus event, or attaches a function to run
when a focus event occurs.
The blur event occurs when an element loses focus. The blur() method triggers the
blur event, or attaches a function to run when a blur event occurs.
!DOCTYPE html>
<html> <head>
<style>
a:focus, a:active {
color: green;
</style>
</head> <body>
<p>Click the buttons to give focus and/or remove focus from the link above.</p>
<script>
</script>
</body> </html>
116
Java Script
Validation Check
Validation is a process used to ensure that computer systems will produce information
or data that meet a set of defined requirements.
• Range check – marks entered is within the accepted range
• Presence check – information has been entered and not left blank
Q-1: create a program to accept a given line of text. The user then enters a particular
character that is to be searched in the entered line of text. Display the number of times the
given character appears in the line of text. Use loops and the charAt() function.
Q.2 Write functions to convert lower to uppercase and upper to lower case. Have a text box
to enter the text and two buttons to invoke the functions.
<p id="demo"></p>
<script>
function myCapital(myform) {
var str = myform.txtInput.value
var res = str.toUpperCase();
document.getElementById("demo").innerHTML = res;
} </script>
<form name ="demo_form">
<input type="text" name="txtInput" value="Capitalise">
<input type="button" onclick="myCapital(this.form)" value="Capitalise">
</form> </body></html>
Q-3: Have two text boxes for the user to enter the username and password.
Valid users are Tom and Jack whose passwords are Mary and Jill respectively.
The user names and passwords are not case sensitive. Show a message
“Welcome” to valid user logins and an error message otherwise.
117