LifeRing.png
SAVE OUR COMMUNITY POOL
Friends of Maryborough Outdoor Pool

HTML for beginners

parent tags, child tags & inherritance

You find this concept very intuitive in everyday life, even if you are not familiar with this programming terminology. Consider the concept of a 'car'. There are many different types of cars but we always characterise them as a car.

CAR
SUV SEDAN UTE PANEL VAN VAN STATION WAGON HATCH BACK

All these automobiles have the common characteristics of a 'car', in addition to their own individual characteristics. You can say the 'car' is the 'parent' of all those automobiles, while each individual type of automobile is a child of the parent 'car'

So in a similar way <div> and <span> are the parent tags in HTML. All the tags described below are children of one of these two parent tags. Another way of stating it is that all the other tags described on this page are 'derived' from either <div> or <span>. As with the different types of cars above, all the HTML tags 'derived' from <div> 'inherit' its particular way of arranging itself on the screen when combined with other <div>s, but each derived tag adds a bunch of other unique characteristics to the mix. Just like a 'sedan' adds a bunch of unique characteristics to the common charactersistics of a car.

Please note that there are dozens more HTML tags available to you, but you have little hope in remembering the details of all them. I only ever use and remeber a small subset of them, most of them i have never had a reason to use them in a web page. But if you want to view the full list of HTML tags then click on this link W3Schools HTML Tag Reference.The small subset listed on this page are the most frequently used tags in this web site and are worth while getting to know.

Family tree for <div> derived HTML tags

<div>(parent tag)

<h1> <h2> <h3> <h4> <h5> <h6> <hr> <ol> <p> <table> <tr> <ul>

 

Family tree for <span> derived HTML tags

<span>(parent tag)

<b> <i> <u> <s> <pre> <a> <img> <li> <td>

So what is the difference between <div> and <span> tags? The difference is in how they arrange themselves on a screen.

<div>s

<div> elements (by default) arrange themselves the second below the first, and the third below the second etc. With <div> elements you can also set an explicit height and width as in the following example.

FIRST DIV
SECOND DIV

A different way to visualise it:

If you don't explicitly set a width and height for your divs then they look like following. The content of the div determines its height of your divs, while they 'inherit' with width of their parent element.

FIRST DIV
SECOND DIV

Parent & child HTML elements

There is also the concept of parent HTML elements containing child HTML elements, demonstrated in the following example. Note how I have used code indenting to show you the heirarchy of the divs in the HTML code. Using code indenting is VERY important in order to make your code easily comprehensible for the next person, or even yourself in 12 months time.

<div style="width:400px;height:400;background-color:blue;">
	This is the parent div.
	<div style="width:200px;height:200px;background-color:green;top:50px;left:20px;">
		This is the child div and it is contained inside the parent div.
</div> </div>
This is the parent div.
This is the child div and it is contained inside the parent div.

A different way to visualise it:
CubeInCube.jpg

Here the same example as above but showing you more explicitly that the child div is contained within the parent div.

This is the parent div.
This is the child div and it is contained inside the parent div.

A different way to visualise it:
CubeHalfInCube.jpg

In this example width of the outer or parent div (blue) has been set a width of 100% of ITS parent.

This is the parent div.
This is the child div and it is contained inside the parent div.

You have to imagine that the browser window itself...
BrowserWindow.jpg
is also a <div> and it is the great great great great grandparent of every HTML element that makes up the web page.

A different way to visualise it, with the purple cube being representing the web browser window.
BrowserWindowBoxWidth.jpg
So if you tell the blue <div> to be 100% of its parent's width then it will inherit the width of the purple <div> that represents the web browser window.

In this example width of the inner or child div (green) has been set a width of 100% of ITS parent.

This is the parent div.
This is the child div and it is contained inside the parent div.

A different way to visualise it:
CubeInCubeWidth.jpg

<span>s

<span> elements (by default) display side by side, until they run out of horizontal space, and then they wrap to the next line. <span> ignores explicitly set width and height - its dimensions are determined soley by its contents.

XXXX SPAN 1 XXXX XXXX SPAN 2 XXXX XXXX SPAN 3 XXXX XXXX SPAN 4 XXXX XXXX SPAN 5 XXXX XXXX SPAN 6 XXXX XXXX SPAN 7 XXXX XXXX SPAN 8 XXXX XXXX SPAN 9 XXXX XXXX SPAN 10 XXXX XXXX SPAN 11 XXXX XXXX SPAN 12 XXXX XXXX SPAN 13 XXXX XXXX SPAN 14 XXXX XXXX SPAN 15 XXXX XXXX SPAN 16 XXXX

A different way to visualise it:
SpansInDiv.jpg

<span>s as child elements of a <div>

In this example I have made all the above span elements a child of the blue div element. Again, please note how I have used code indenting to make the parent/child heirarchy of these tags clear in the HTML code.

<div style="width:400px;height:400px;background-color:BurlyWood;">
	This is the parent div. And all these span elements are its children.
<span style="background-color:blue">XXXX SPAN 1 XXXX</span> <span style="background-color:green">XXXX SPAN 2 XXXX</span> <span style="background-color:yellow">XXXX SPAN 3 XXXX</span> <span style="background-color:red">XXXX SPAN 4 XXXX</span> <span style="background-color:cyan">XXXX SPAN 5 XXXX</span> <span style="background-color:orange">XXXX SPAN 6 XXXX</span> <span style="background-color:navy">XXXX SPAN 7 XXXX</span> <span style="background-color:teal">XXXX SPAN 8 XXXX</span> <span style="background-color:maroon">XXXX SPAN 9 XXXX</span> <span style="background-color:purple">XXXX SPAN 10 XXXX</span> <span style="background-color:silver">XXXX SPAN 11 XXXX</span> <span style="background-color:olive">XXXX SPAN 12 XXXX</span> <span style="background-color:Honeydew">XXXX SPAN 13 XXXX</span> <span style="background-color:CornflowerBlue">XXXX SPAN 14 XXXX</span> <span style="background-color:DarkOrchid">XXXX SPAN 15 XXXX</span> <span style="background-color:Chocolate">XXXX SPAN 16 XXXX</span> </div>
This is the parent div. And all these span elements are its children. XXXX SPAN 1 XXXX XXXX SPAN 2 XXXX XXXX SPAN 3 XXXX XXXX SPAN 4 XXXX XXXX SPAN 5 XXXX XXXX SPAN 6 XXXX XXXX SPAN 7 XXXX XXXX SPAN 8 XXXX XXXX SPAN 9 XXXX XXXX SPAN 10 XXXX XXXX SPAN 11 XXXX XXXX SPAN 12 XXXX XXXX SPAN 13 XXXX XXXX SPAN 14 XXXX XXXX SPAN 15 XXXX XXXX SPAN 16 XXXX

Minimum structure of a HTML document

In MS Expression Web you can create a new HTML document or web page by clicking the following:
NewHTML.jpg
And you will get a new text file containing the following:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Untitled 1</title>
</head>

<body>

</body>

</html>

Notice how it is done a poor job of code indenting. There is a heirarchy of HTML tags here but you would be hard pressed to discern it from this. So lets fix the indenting and the HTML tag heirarchy will reveal itself.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

	<head>
		<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
		<title>Untitled 1</title>
	</head>

	<body>
		
	</body>

</html>

Now you should be able to see that the <html ...> and </html> tags are the 'granparent' tags. All the other tags or between those to tags or 'inside' that 'html' element. Then there are 2 child tags:

  • <head ...> ... </head>
  • <body ...> ... </body>

In turn the <head ...> ... </head> tags also contains 2 child tags:

  • <meta .... / >
  • <title> ... </title>

This page structure emulates that of a MS Word document and you can go as far as the following if you wish.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

	<head>
		<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
		<title>Untitled 1</title>
		<style>
			...
		<style>
		<link href="styles/style4PC.css" rel="stylesheet" type="text/css" />
	</head>

	<header>
		
	</header>

	<body>
	
	</body>
	
	<footer>
	
	</footer>

</html>

Make sure you use indenting like this in your HTML code to show the tag heirarchy and make your code more easily readable by those who come after you. Or even yourself when you return to your HTML code after 12 months or whatever.

Details of these HTML tags are as follows:

  • <!DOCTYPE ...>: You can learn more about this tag by clicking here.

    REQUIRED

    MS Expression Web generates this line every time you create a new HTML document. You don't necessarily need to understand fully what it does - just accept it or copy and paste if needed. Without this tag at the top of your HTML document you can run into problems with the way web browsers render your web page.
  • <html>: You can learn more about this tag by clicking here.

    REQUIRED

    MS Expression Web generates the 'html' tags every time you create a new HTML document. You don't necessarily need to understand fully what it does - just accept it or copy and paste if needed. In short it lets a web browser know what version of the HTML standard the web pages uses.
  • <head>: You can learn more abut this tag by clicking here.

    REQUIRED

    The idea is put all those HTML tags that DO NOT form part of your visible page content between these tags. Including:
    • <title>Untitled 1</title>: the text between these tags is the title of your web page. Note that the document title IS NOT part of your visible page content. The page title ('Untitled 1' in this case) appears as the name of the page tab in your web browser! You can learn more about this HTML tag by clicking here. MS Expression Web generates the 'title' tags every time you create a new HTML document.
    • <style>...</style>: you place all page specific CSS styling between these tags. MS Expression Web will enforce correct CSS syntax for amything your type between these tags. You can learn more about thos tag by clicking here. MS Expression Web does not generate the 'style' tags when you create a new HTML document.
    • <link ... />: you also place any 'link' tags in between your 'head' tags. You use 'link' tags to 'link' external resources into your HTML document so you can use them in your HTML code. In this example the style.css (containing global CSS styling) into the HTML document. Yo can also use 'link' tags to link in google fonts, icons, multi-language support and many other types of web resources. You can learn more about this HTML tag by clicking here. MS Expression Web generates a 'link' tag for the file 'style.css' every time you create a new HTML document.
  • <header> OPTIONAL

    You could use this tag to 'house' any of your visible page content that is common across all your web pages. The idea is similar to the 'header' section of a MS Word document. You can learn more about this tag by clicking here. MS Expression Web does not generate the 'header' tags when you create a new HTML document.
  • <body> REQUIRED

    Generally you put all your page specific content bewteen these tags. You can learn more about this tag by clicking here. MS Expression Web generates the 'body' tags every time you create a new HTML document.
  • <footer> OPTIONAL

    You could use this tag to 'house', for example, any of hyperlinks to Facebook and Twitter pages that is common across all your web pages. The idea is similar to the 'footer' section of a MS Word document. You can learn more about this tag by clicking here. MS Expression Web does not generate the 'footer' tags when you create a new HTML document.

Simple tags

Text styles

The parent tag for all these is <span>

<b>BOLD</b>

<i>ITALIC</i>

<u>UNDERLINE</u>

<s>STRIKE THROUGH</s>

Headings

The parent tag for all these is <div>

<h1>HEADING LEVEL 1</h1>

<h2>HEADING LEVEL 2</h2>

<h3>HEADING LEVEL 3</h3>

<h4>HEADING LEVEL 4</h4>

<h5>HEADING LEVEL 5</h5>
<h6>HEADING LEVEL 6</h6>

Horizontal line

<hr/>(shorthand)
<hr></hr>(longhand)

Spaces

You get one space character for free by simply hitting the space bar on the keyboard.
But of you want more than one space character then you will need to type &nbsp; as
as many times as needed.
E.G. #one space# or #five&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;spaces# (#five  spaces#)

Line breaks

You need to type <br/> to get one.
E.G. No line break:
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce sodales justo et ipsum tincidunt porttitor.

One line break:
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Fusce sodales justo et ipsum tincidunt porttitor.

Compound tags

Paragraphs

The parent tag is <div>

Here is the same example as above except using paragrapgh tags instead of a line break.

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
<p>Fusce sodales justo et ipsum tincidunt porttitor</p>

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Fusce sodales justo et ipsum tincidunt porttitor.

Unordered lists

The parent tag is <div>

<ul>
	<li>First item</li>
	<li>Second item</li>
	<li>Third item</li>
	<li>Fourth item</li>
	<li>...</li>
</ul>
  • First item
  • Second item
  • Third item
  • Fourth item
  • ...

Ordered lists

The parent tag is <div>

<ol>
	<li>First item</li>
	<li>Second item</li>
	<li>Third item</li>
	<li>Fourth item</li>
	<li>...</li>
</ol>
  1. First item
  2. Second item
  3. Third item
  4. Fourth item
  5. ...

Images

The parent tag is <span>

<img src="..." alt="..." width="integer" height="integer" /> (shorthand)
<img src="..." alt="..." /></img> (longhand)

src: This can be the path for an image file within the web site.
e.g. src="images/image_filename.jpg" or it can be an image file at an external
URL e.g. src="https://google.com/images/image_filename.jpg"
alt: This is alternative text to display if the image file is not found.
Commonly it is just the name of the image file e.g. alt="image_filename.jpg"
width & height: These should be integers commonly between 20 and 500, to create
a small to moderately large image on the page. If you specify EITHER a width OR a height
then the image will resize while maintaining its aspect ratio. If you specify BOTH a width
AND a height then the image may appear distorted on the page.

E.G. width="..." only
	<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/3/35/Information_icon.svg/960px-Information_icon.svg.png?_=20260201131748" alt="Google commons image" width="100" />

Google commons image

E.G. height="..." only
	<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/3/35/Information_icon.svg/960px-Information_icon.svg.png?_=20260201131748" alt="Google commons image" height="100" />

Google commons image

E.G. width="..." and height="..."
	<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/3/35/Information_icon.svg/960px-Information_icon.svg.png?_=20260201131748" alt="Google commons image" width="200" height="50" />

Google commons image

Hyperlinks

The parent tag is <span>

<a href="..." /><Text to display</a> href: This can be the path for type of file within the web site.
e.g. href="join/join.html", it can be an external URL href="https://google.com" or
or it can be a bookmark within the currently loaded page e.g. href=#bookmark_name.
Some where on the page you must have a HTML tag with an id property containing the
bookmark name. e.g. <h1 id="bookmark_name">HEADING NAME</h1>. Commonly
headings are used as bookmarks, however you can also have book marks on tables,
paragraphs and images etc.

E.G. <a href="https://google.com">Click here for google</a>

Click here for google

An image as a hyperlink

<a href="https://upload.wikimedia.org/wikipedia/commons/thumb/3/35/Information_icon.svg/960px-Information_icon.svg.png?_=20260201131748" /><<img src="image_filename.jpg" alt="Google commons image" width="30" /></a>

In this example the hyperlink is to the image that is being used as the clickable page element. Clicking it
will result in the image being opened in the web browser in its own right.

E.G. <a href="https://upload.wikimedia.org/wikipedia/commons/thumb/3/35/Information_icon.svg/960px-Information_icon.svg.png?_=20260201131748"><img src="https://upload.wikimedia.org/wikipedia/commons/thumb/3/35/Information_icon.svg/960px-Information_icon.svg.png?_=20260201131748" alt="Google commons image" width="100" /></a> Google commons image

Tables

The parent tag is <div>

Apart from using HTML tables for conventional purposes, you can also use them th structure web pages. If you use <div>s to structure your web pages then they have the unfortunate disadvantage of re-arranging themselves, in ways you as the web page designer do not anticipate, when the viewer re-sizes their web browser window. This can completely muck up the lay out of your web page. But if you structure your web page via a table then your web page is 'fixed in stone' and its structure cannot be re-arranged when the viewer re-sizes their web browser window.

<table border="1" cellspacing="5" cellpadding="5">
	<thead><!--START HEADER-->
		<tr><!--START HEADER ROW-->
			<th>COLUMN 1 HEADING</th>
			<th>COLUMN 2 HEADING</th>
			<th>COLUMN 3 HEADING</th>
		</tr><!--END HEADER ROW-->
	</thead><!--END HEADER-->
	<tr><!--START ROW 1-->
		<td>COLUMN 1, ROW 1</td>
		<td>COLUMN 2, ROW 1</td>
		<td>COLUMN 3, ROW 1</td>
	</tr><!--END ROW 1-->
	<tr><!--START ROW 2-->
		<td>COLUMN 1, ROW 2</td>
		<td>COLUMN 2, ROW 2</td>
		<td>COLUMN 3, ROW 2</td>
	</tr><!--END ROW 2-->
	<tr><!--START ROW 3-->
		<td>COLUMN 1, ROW 3</td>
		<td>COLUMN 2, ROW 3</td>
		<td>COLUMN 3, ROW 3</td>
	</tr><!--END ROW 3-->
</table>

border="0" cellspacing="0" cellpadding="0"

COLUMN 1 HEADING COLUMN 2 HEADING COLUMN 3 HEADING
COLUMN 1, ROW 1 COLUMN 2, ROW 1 COLUMN 3, ROW 1
COLUMN 1, ROW 2 COLUMN 2, ROW 2 COLUMN 3, ROW 2
COLUMN 1, ROW 3 COLUMN 2, ROW 3 COLUMN 3, ROW 3


border="1" cellspacing="0" cellpadding="0"

COLUMN 1 HEADING COLUMN 2 HEADING COLUMN 3 HEADING
COLUMN 1, ROW 1 COLUMN 2, ROW 1 COLUMN 3, ROW 1
COLUMN 1, ROW 2 COLUMN 2, ROW 2 COLUMN 3, ROW 2
COLUMN 1, ROW 3 COLUMN 2, ROW 3 COLUMN 3, ROW 3


border="1" cellspacing="10" cellpadding="0"

COLUMN 1 HEADING COLUMN 2 HEADING COLUMN 3 HEADING
COLUMN 1, ROW 1 COLUMN 2, ROW 1 COLUMN 3, ROW 1
COLUMN 1, ROW 2 COLUMN 2, ROW 2 COLUMN 3, ROW 2
COLUMN 1, ROW 3 COLUMN 2, ROW 3 COLUMN 3, ROW 3


border="1" cellspacing="0" cellpadding="10"

COLUMN 1 HEADING COLUMN 2 HEADING COLUMN 3 HEADING
COLUMN 1, ROW 1 COLUMN 2, ROW 1 COLUMN 3, ROW 1
COLUMN 1, ROW 2 COLUMN 2, ROW 2 COLUMN 3, ROW 2
COLUMN 1, ROW 3 COLUMN 2, ROW 3 COLUMN 3, ROW 3


Using colspan to merge columns

	<table border="1" cellspacing="5" cellpadding="5">
		<thead><!--START HEADER-->
			<tr><!--START HEADER ROW-->
				<th>COLUMN 1 HEADING</th>
				<th>COLUMN 2 HEADING</th>
				<th>COLUMN 3 HEADING</th>
			</tr><!--END HEADER ROW-->
		</thead><!--END HEADER-->
		<tr><!--START ROW 1-->
			<td colspan="2">COLUMN 1 & 2, ROW 1</td>
			<!-- OMITT COLUMN 2 -->
<td>COLUMN 3, ROW 1</td> </tr><!--END ROW 1--> <tr><!--START ROW 2--> <td>COLUMN 1, ROW 2</td> <td>COLUMN 2, ROW 2</td> <td>COLUMN 3, ROW 2</td> </tr><!--END ROW 2--> <tr><!--START ROW 3--> <td>COLUMN 1, ROW 3</td> <td>COLUMN 2, ROW 3</td> <td>COLUMN 3, ROW 3</td> </tr><!--END ROW 3--> </table>
COLUMN 1 HEADING COLUMN 2 HEADING COLUMN 3 HEADING
COLUMN 1 & 2, ROW 1 COLUMN 2, ROW 1
COLUMN 1, ROW 2 COLUMN 2, ROW 2 COLUMN 3, ROW 2
COLUMN 1, ROW 3 COLUMN 2, ROW 3 COLUMN 3, ROW 3


Using rowspan to merge rows

	<table border="1" cellspacing="5" cellpadding="5">
		<thead><!--START HEADER-->
			<tr><!--START HEADER ROW-->
				<th>COLUMN 1 HEADING</th>
				<th>COLUMN 2 HEADING</th>
				<th>COLUMN 3 HEADING</th>
			</tr><!--END HEADER ROW-->
		</thead><!--END HEADER-->
		<tr><!--START ROW 1-->
			<td rowspan="2">COLUMN 1, ROW 1 & 2</td>
			<td>COLUMN 2, ROW 1</td>
			<td>COLUMN 2, ROW 1</td>
			<td>COLUMN 3, ROW 1</td>
		</tr><!--END ROW 1-->
		<tr><!--START ROW 2-->
			<!-- OMITT COLUMN 1 ON ROW 2 -->
<td>COLUMN 2, ROW 2</td> <td>COLUMN 3, ROW 2</td> </tr><!--END ROW 2--> <tr><!--START ROW 3--> <td>COLUMN 1, ROW 3</td> <td>COLUMN 2, ROW 3</td> <td>COLUMN 3, ROW 3</td> </tr><!--END ROW 3--> </table>
COLUMN 1 HEADING COLUMN 2 HEADING COLUMN 3 HEADING
COLUMN 1, ROW 1 & 2 COLUMN 2, ROW 1 COLUMN 3, ROW 1
COLUMN 2, ROW 2 COLUMN 3, ROW 2
COLUMN 1, ROW 3 COLUMN 2, ROW 3 COLUMN 3, ROW 3

Nesting tags

You can freely nest those tags that are 'children' of or derived from <span>. So tags like of <b>, <a> , <u> and <i> etc. can be freely nested one inside another and inside another. For example these nestings are perfectly fine in HTML:

  • <a href="..."><img src="..." alt="..." /></a>
  • <b><u><i>XXXXXXX</i></u></b>
  • <img src="..." alt="..."><b>XXXXXX</b></img>

The only thing to be mindful of is to make sure you close the opening tags in the matching sequence. Doing this, for example, might lead to unexpected results: <b><u><i>XXXXXXX</b></u></i>

You can freely nest <div>s (specifically) inside each other as deeply as you want. However you should not nest tags that are children of or derived from <div> inside each other.For example, do not nest a <ul> tag inside a <p> tag. Expression Web will tell you that you have an error in your HTML and you can get some rather mysterious and unpredictable results in your web page. However you can nest a <p> tag, for example, inside a <div> tag (spcifically).

Now at this point I bet you are confused as hell about what I am trying to explain to you. But there is an everyday analogy that can go a long way to helping you comprehend all this. Let's consider the following substitutions:

  • <div>...</div> becomes <mechanics_garage>...</mechanics_garage>
  • <ul>...</ul> becomes <holden_body>...</holden_body>
  • <p>...</p> becomes <toyota_engine>...</toyota_engine>

Now, if you do this nesting of tags then all is as you expect it...
<mechanics_garage> <holden_body>...</holden_body> <toyota_engine>...</toyota_engine> </mechanics_garage>

But, if you do this nesting of tags then disaster will occur. Because you can't put a toyota engine in a holden body.
<mechanics_garage> <holden_body> <toyota_engine>...</toyota_engine> </holden_body> </mechanics_garage>

<pre> & <p> tags

<pre> What you type is what you get.</pre>
Hello        world      &<>      !@#$%^*()_-+=:;"{',./
<p> What you type is mostly what you get.</p>

Hello world &<> !@#$%^*()_-+=:;"{',./

In the case of <p> tags you get one space character for free. If you want more than that in a row then you have to use &amp;&amp;&amp;&amp;&amp;. Or you could nest <pre> tags inside <p> tags.

<p><pre> What you type is what you get.</pre></p>

Hello        world      &<>      !@#$%^*()_-+=:;"{',./

Expression Web will highlight HTML errors if you type an & inside <pre> tags, for example, but just ignore it. Web browsers do not have a problem with this.

Try all this!

While MS Expression Web makes editing web pages and entire web sites much easier. You don't actually need any special software to create a HTML web page. You could do ALL of this with MS Windows Notepad, available in the Accesories section of the start menu of any version of MS Windows. Simply copy any of this HTML code, paste it into Notepad, save the file as 'example.htm', use File Explorer or This Computer to browse your way to the file's folder location (likely in your 'documents' folder) and double click on the file - it should come up in your web browser. If not then right click on 'example.htm', select 'open with' and then select your web browser from the list of options.

HTML Emojis

You can insert the same emojis in your content as you can in Facebook and Facebook messengers. Here are a few of them:

  • &#x1F600: 😀
  • &#x1F601: 😁
  • &#x1F602: 😂
  • &#x1F603: 😃
  • &#x1F604: 😄
  • &#x1F605: 😅
  • &#x1F606: 😆

You can see the full list of available emojis by clicking here.

CSS for beginners

CSS stands for Cascading Style Sheets. CSS provides a way to apply different sets of formatting styles to the same HTML document. You could use them, for example, to make the text in a HTML document larger and more easily readable by vision impaired visitors, without effecting what vistors with normal vision see.

There are HUNDREDS of different CSS properties that you can change to have a wide variety of effects on the individual behavior and appearance of your HTML elements. There is no hope of trying to describe all of them here so we will simply explore a few of the most commonly used properties and selectors. For a full reference for ALL the CSS properties please click here for the excellent W3Schools CSS reference.

How do you apply CSS styling?

Definitions and terminology

  • HTML web page or just web page

    Typically they are text files that have the extension .html or .htm. The you open these file types in your web browser, it reads the HTML instructions and 'renders' the web page.

What is 'scope'

Well no doubt you are familiar with the concept of scope when it comes to writing some sort of organisational report or proposal. For example, the scope of your report might be limited to the next 5 yeasr only or to the VIC operation but not the national operation. Scope in the context of CSS is somewhat similar. The scope of your CSS styling can apply:

  • To a single instance of a HTML tag (one off) in a particular HTML web page.
  • A set of styles that apply to one or more HTML elements on a particular HTML web page.
  • A 'global' set of styles that can apply to any HTML element in any HTML web page in the entire website.

Inline CSS

This is used for 'one off' styling of particular HTML elements within the current web page.
StyleProperty.jpg
HTML Elements 2, 3 and 4 cannot 'see' HTML element 1's inline styles. Those inline styles are said to be 'out of scope' for HTML elements 2, 3 and 4.

You insert your CSS styling into the 'style' property between the double quotes, e.g. <div style="background-color:blue;">...</div>. The 'style' property is one of the generic HTML tag properties that you can apply to ANY HTML element.

<style> / </style> tags

This is used for styling of one or more elements but in the current web page only. HTML elements on other web pages CANNOT 'see' the CSS styles between the <style>...</style> on other web pages.
StyleTags.jpg
HTML Elements 2 and 3 can 'see' your styles you have put between the <style> tags at the top of your web page. They are said to be 'in scope' for HTML elements 2 and 3.

However HTML elements 3 and 4 cannot 'see' the styles on HTML page 1. The styles on web page 1 are said to be 'out of scope' for HTML elements 3 and 4 on web page 2.

Remember the basic tag structure of a HTML document? Click here if you need to read it again. The style tags are typically located within the head tags, like this:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

        <head>
                <meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
                <title>Untitled 1</title>
                <style>
                        ...
                </style>
        </head>

        <body>
			...
        </body>

</html>

The file style.css

This is used for 'global' or 'god' styling of one or more HTML elements across multiple HTML web pages. MS Expression web likes to use the file name 'style.css' for this but you do not have stick this this file name if you do not want to. You could two style sheets in principle - 'StyleVisionImpaired.css' and StyleNormalVision.css' for example. It is up to you what filename you give your style sheet(s). MS Expression Web also likes to store your 'style.css' file in a sub-folder named 'styles'. But again you can store then in any sub-folder you chose, or not store them in any sub-folder at all.

However every HTML web page in which you want to use your style sheet(s) MUST have this line of HTML code in them:

<link href="styles/style4PC.css" rel="stylesheet" type="text/css" />

You can read all bout the HTML <Link ... > tag here if you wish to. Or just do what i do - copy and paste the text from another HTML web page. The link tag must correctly tell the web browser what sub-folder (or not) where it will find your .css file, and its correct filename.

As long as you include an appropriate <link ... > tag in both web pages 1 and 2 then all the styles you put in your style.css then they are 'in scope' for both web pages 1 and 2, and HTML elements 1, 2, 3 and 4.
StyleCSS.jpg

What is the purpose of this 'scoping'?

The purpose of all this is to allow you you to 're-use' your CSS styling across multiple elements and multiple web pages, without having to tyoe the same CSS styling over and over again for individual elements and individual HTML web pages.

But the system ALSO allows you to 'compartmentalise' your CSS styling. For example, if web page 1 has CSS style that you don't need use in web page 2 then you put them between the <style> tags OF web page 1. If you have styles that you need to apply to a particular HTML element and other then use inline styling (style="...").

Via ID selectors

This method employs the use of the HTML tag property 'id' as the means of selecting those HTML elements to which a set of CSS styles will be applied. Remember the HTML tag property 'id' can be applied to ANY type of HTML element - it is generic property. E.G.

	<div id="green_div">######</div>
	<div id="other_div">$$$$$$</div>
	<div id="green_div">@@@@@@</div>

Then, either between the <style">...</style>vin your HTML web page or in 'style.css' you do this:

#green_div
{
		  background-color: green;
		  border-style: solid;
		  border-color: red;
		  border-width: thick;
}

And here are the results:

######
$$$$$$
@@@@@@

Notice that only the top and bottom divs (with id="green_div") have green backgrounds and thick red borders. The middle div (with id="other_div" and text content "$$$$$$") does not.

However I recomend against using this technique as it can cause problems if you use Javascript in your web page. Particularly with the Javascript function document.getElementById("unique_element_id"). It requires that the HTML element you are trying to 'get' has a unique name for its 'id' property. Using the CSS id selector requires mutiple HTML elements to have a shared name for their 'id' property. Hence document.getElementById("unique_element_id") simply will not work as you expect it to.

Via class selectors

This is a better way of appying CSS styles to multiple HTML elements.

<div class="green_div big_white_text">######</div>
<div class="other_div">$$$$$$</div>
<div class="green_div">@@@@@@</div>
You utilise the 'class' property instead and specify one or more a unique 'class' names. This method has a major 
advantage over the 'id' method in that you can apply multiple class names with different sets of CSS styles as in 
this example. 
Then, either between the <style">...</style> in your HTML web page or in 'style.css' you do this:
.green_div
{
	background-color: green;
	border-style: solid;
	border-color: red;
	border-width: thick;
}
.big_white_text
{
	color: white;
	font-size: xx-large;
}

And here are the results:

######
$$$$$$
@@@@@@

Via tag selectors

You can also apply selectively apply CSS styles via tag selectors. You use tag selectors if you want your styles applied to every single isntance of any particular tag.

<span>######</span>
<span>$$$$$$</span>
<span>@@@@@@</span>

Notice that neither the 'id' or 'class' properties are specified for these spans.

And between the between the <style">...</style> in your HTML web page or in 'style.css' you do the following with the tag name you want the styles applied to.

span
{
	background-color: green;
	border-style: solid;
	border-color: red;
	border-width: thick;
	color: white;
	font-size: xx-large;
}

And here are the results:

###### $$$$$$ @@@@@@

All 3 HTML elements are spans therefore all three have green backgrounds, thick red borders and big white text.

And you have now learned how to use your first six CSS properties. MS Expression Web will show you a popup lists of CSS properties you can use, and popup lists of values you can apply to each attribute, as you type within style="..." and the <style>...</style> tags.

Specifying colors

There are many named colors that you can apply to the 'background-color' and 'color' properties and you can read about them here. Or you can invent your own colors via hex values, rgb(...) and rgba(...), hls(...) and hlsa(...). Simple named colours are the most convenient to use.

Borders

You have VERY fine control over borders so let's look at some quick examples. And you can read all about CSS borders by clicking here.

border-style

	<div style="border-style:solid;width:100px;">XXXXXXX</div>
	<div style="border-style:dotted;width:100px;">XXXXXXX</div>
	<div style="border-style:dashed;width:100px;">XXXXXXX</div>
	<div style="border-style:double;width:100px;">XXXXXXX</div>
	<div style="border-style:inset;width:100px;">XXXXXXX</div>
	<div style="border-style:outset;width:100px;;">XXXXXXX</div>
	<div style="border-style:ridge;width:100px;">XXXXXXX</div>
	<div style="border-style:groove;width:100px;;">XXXXXXX</div>
	The results are:
XXXXXXX

XXXXXXX

XXXXXXX

XXXXXXX

XXXXXXX

XXXXXXX

XXXXXXX

XXXXXXX

Or...

	<div style="border-left-style:solid;border-top-style:dotted;border-right-style:dashed;border-bottom-style:double;width:100px;">XXXXXXX</div>
	<div style="border:solid dotted dashed double;width:100px;">XXXXXXX</div>
	The results are:
XXXXXXX

;XXXXXXX

border-width

DEFAULT VALUE: "thin"

	<div style="border-style:solid;border-width:thin;width:100px;">XXXXXXX</div>
	<div style="border-style:solid;border-width:medium;width:100px;">XXXXXXX</div>
	<div style="border-style:solid;border-width:thick;width:100px;">XXXXXXX</div>
	<div style="border-style:solid;border-width:20px;width:100px;">XXXXXXX</div>
	The results are:
XXXXXXX

XXXXXXX

XXXXXXX

XXXXXXX

border-color

DEFAULT VALUE: "black"

	<div style="border-style:solid;border-width:medium;border-color:red;width:100px;">XXXXXXX</div>
	<div style="border-style:solid;border-width:medium;border-color:green;width:100px;">XXXXXXX</div>
	<div style="border-style:solid;border-width:medium;border-color:blue;width:100px;">XXXXXXX</div>
	The results are:
XXXXXXX

XXXXXXX

XXXXXXX

border-radius

DEFAULT VALUE: "0px" (sharp corners)

	<div style="border-style:solid;border-width:medium;border-color:red;border-radius:3px;width:100px;">XXXXXXX</div>
	<div style="border-style:solid;border-width:medium;border-color:green;border-radius:5px;width:100px;">XXXXXXX</div>
	<div style="border-style:solid;border-width:medium;border-color:blue;border-radius:10px;width:100px;">XXXXXXX</div>
	<div style="border-style:solid;border-width:medium;border-color:blue;border-radius:20px;width:100px;">XXXXXXX</div>
	The results are:
XXXXXXX

XXXXXXX

XXXXXXX

XXXXXXX

Shorthand

	<div style="border:solid thin red;width:100px;">XXXXXXX</div>
	<div style="border:dashed thin red;width:100px;">XXXXXXX</div>
	<div style="border:solid thin red;width:100px;">XXXXXXX</div>
	<div style="border:solid medium red;width:100px;">XXXXXXX</div>
	<div style="border:solid thin red;width:100px;">XXXXXXX</div>
	<div style="border:solid thin blue;width:100px;">XXXXXXX</div>
	The results are:
XXXXXXX

XXXXXXX

XXXXXXX

XXXXXXX

XXXXXXX

XXXXXXX

display

This CSS attribute controls how an element is displayed on the web page. Note that there are many other values that you can apply to this CSS attribute, than those detailed here. But those other values are really only suited for advanced web programmers. But you can read about all of the values by clicking here if you wish.

DEFAULT VALUE FOR DIV & DIV TYPE ELEMENTS: "block" DEFAULT VALUE FOR SPAN & SPAN TYPE ELEMENTS: "inline"

"block"

	<div style="background-color:blue;width:100px;height:100px;display:block;">XXXXXXX</div>
	<div style="background-color:green;width:100px;height:100px;display:block;">XXXXXXX</div>
	<div style="background-color:red;width:100px;height:100px;display:block;">XXXXXXX</div>
	The results are:
XXXXXXX
XXXXXXX
XXXXXXX

"none"

	<div style="background-color:blue;width:100px;height:100px;display:block;">XXXXXXX</div>
	<div style="background-color:green;width:100px;height:100px;display:none;">XXXXXXX</div>
	<div style="background-color:red;width:100px;height:100px;display:block;">XXXXXXX</div>
	The results are:
XXXXXXX
XXXXXXX
XXXXXXX

Note, that if you specify "none" for the 'display' attribute, then the element disappears entirely from the web page. You can use this attribute to temporarily hide an element.

"inline-block"

<div style="background-color:blue;width:100px;height:100px;display:inline-block;">XXXXXXX</div>
<div style="background-color:green;width:100px;height:100px;display:inline-block;">XXXXXXX</div>
<div style="background-color:red;width:100px;height:100px;display:inline-block;">XXXXXXX</div>
	The results are:
XXXXXXX
XXXXXXX
XXXXXXX

"inline"

<div style="background-color:blue;width:100px;height:100px;display:inline;">XXXXXXX</div>
<div style="background-color:green;width:100px;height:100px;display:inline;">XXXXXXX</div>
<div style="background-color:red;width:100px;height:100px;display:inline;">XXXXXXX</div>
The results are:
XXXXXXX
XXXXXXX
XXXXXXX

Note, that if you specify that an element should be displayed 'inline' then you can no longer control its width and height. They are controlled exclusively by the elements' contents.

Fonts

font-family

There are several generic fonts that all web browsers are likely to have 'built in'. And you can read about them and the 'font-family' attribute by clicking here.

However there are thousands of web fonts available from Google. Click here to browse through some of them. Each one provides you with the HTML code that you need to paste into your HTML web page in order to use them.

<p style="font-family:Arial, Helvetica, sans-serif">Hello World</p>
<p style="font-family:Cambria, Cochin, Georgia, Times, 'Times New Roman', serif">Hello World</p>
<p style="font-family:'Courier New', Courier, monospace">Hello World</p>
<p style="font-family:'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif">Hello World</p>
<p style="font-family:'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif">Hello World</p>
<p style="font-family:Georgia, 'Times New Roman', Times, serif">Hello World</p>
<p style="font-family:'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif">Hello World</p>
<p style="font-family:Impact, Haettenschweiler, 'Arial Narrow Bold', sans-serif">Hello World</p>
And here are the results:

Hello World

Hello World

Hello World

Hello World

Hello World

Hello World

Hello World

Hello World

font-weight

This attribute controls how thick the text appears. You can read more about it by clicking here.

<p style="font-weight:normal">Hello World</p>
<p style="font-weight:bold">Hello World</p>
<p style="font-weight:100">Hello World</p>
<p style="font-weight:200">Hello World</p>
<p style="font-weight:300">Hello World</p>
<p style="font-weight:400">Hello World</p>
<p style="font-weight:500">Hello World</p>
<p style="font-weight:600">Hello World</p>
<p style="font-weight:700">Hello World</p>
<p style="font-weight:800">Hello World</p>
<p style="font-weight:900">Hello World</p>
And here are the results:

Hello World

Hello World

Hello World

Hello World

Hello World

Hello World

Hello World

Hello World

Hello World

Hello World

Hello World

font-style

This attribute controls the font style, e.g. nornal of italic. You can read more about it by clicking here.

<p style="font-style:normal">Hello World</p>
<p style="font-style:italic">Hello World</p>
<p style="font-style:oblique">Hello World</p>
And here are the results:

Hello World

Hello World

Hello World

font-size

This attribute controls the font size. You can read more about it by clicking here.

<p style="font-size:xx-small;">Hello World</p>
<p style="font-size:x-small;">Hello World</p>
<p style="font-size:small;">Hello World</p>
<p style="font-size:medium;">Hello World</p>
<p style="font-size:large;">Hello World</p>
<p style="font-size:x-large;">Hello World</p>
<p style="font-size:xx-large;">Hello World</p>
<p style="font-size:40px;">Hello World</p>
<p style="font-size:60px;">Hello World</p>
And here are the results:

Hello World

Hello World

Hello World

Hello World

Hello World

Hello World

Hello World

Hello World

Hello World

color

This attribute sets the text color for any HTML element. You can read more about it here.

<p style="color:red;">Hello World</p>
<p style="color:green;">Hello World</p>
<p style="color:blue;">Hello World</p>
<p style="color:cyan";>Hello World</p>
<p style="color:magenta;">Hello World</p>
<p style="color:yellow;">Hello World</p>
<p style="color:black;">Hello World</p>
<p style="color:grey;">Hello World</p>
And here are the results:

Hello World

Hello World

Hello World

Hello World

Hello World

Hello World

Hello World

Hello World

position, left & top

These attributes are typically used in together to modify the position of an element on the screen. You can read more about this attribute by clicking here. The allowed values are thus:

static

If you specify this value then any 'top' and 'left' attributes you specify will be ignored. Click here to see an example.

fixed

If you specify this value then any 'top' and 'left' attributes you specify will be relative to the web browser window. Click here to see an example.

absolute

If you specify this value then any 'top' and 'left' attributes you specify will be relative to the element's parent position. Click here to see an example.

Sticky

If you specify this value then any 'top' and 'left' attributes you specify will be relative to the user's scroll position. Click here to see an example.

relative

If you specify this value then you can specify either negative values for 'top' and 'left', which move the element up and to the left from its default position. Or positive values, which move the element down and to the right from its default position. Here is and example.

No change in default position of the second div.
<div style="background-color:green;width:100px;height:100px;">XXXXXX</div> <div style="background-color:blue;width:100px;height:100px;position:relative;top:0px;left:0px;">XXXXXX</div>

XXXXXX
XXXXXX

The second div is moved up and to the left by 20 pixels.
<div style="background-color:green;width:100px;height:100px;">XXXXXX</div> <div style="background-color:blue;width:100px;height:100px;position:relative;top:-20px;left:-20px;">XXXXXX</div>

XXXXXX
XXXXXX

The second div is moved down and to the right by 20 pixels.
<div style="background-color:green;width:100px;height:100px;">XXXXXX</div> <div style="background-color:blue;width:100px;height:100px;position:relative;top:20px;left:20px;">XXXXXX</div>

XXXXXX
XXXXXX

Alignment

text-align

DEFAULT VALUE: "left"

<div style="background-color:blue;color:white;margin:5px;width:200px;height:100px;">XXXXXX</div>
<div style="background-color:blue;color:white;margin:5px;width:200px;height:100px;text-align:left;">XXXXXX</div>
<div style="background-color:blue;color:white;margin:5px;width:200px;height:100px;text-align:center;">XXXXXX</div>
<div style="background-color:blue;color:white;margin:5px;width:200px;height:100px;text-align:right;">XXXXXX</div>
XXXXXX
XXXXXX
XXXXXX
XXXXXX

vertical-align

DEFAULT VALUE: "middle"

If you are trying to align plain text inside a div, as in the example below, then you must also specify a value for the 'height' attribute greater than the height of the text. Otherwise 'vertical-align' will have no effect on the text. In this example the 'height' is 100 pixels.

The 'verical-align' attribute has no effect at all on 'block' elements such as <div>. For 'inline-block' elements it controls the vertical alignment of the block itself, while text inside is unaffected. So I have used a table to demonstrate its effect. I know - it is confusing but CSS can be like hearding cats sometimes.

<table border="1" cellpadding="0" cellspacing="0">
	<tr>
		<td style="color:blue;">XXXX</td>
		<td style="color:blue;vertical-align:top;height:100px;">XXXX</td>
		<td style="color:blue;vertical-align:middle;height:100px;">XXXX</td>
		<td style="color:blue;vertical-align:bottom;height:100px;">XXXX</td>
	</tr>
</table>
XXXX XXXX XXXX XXXX

To force text to align inside block and inline-block elements you have to use other methods:

  • Insert one or more <br/> elements before the text.
  • place your text inside a one line and one column table and use the 'vertical-align' property on the tabel cell.

These examples represent simplest cases of using 'vertical-align', however there are other values you can use for this attribute. They are concerned with how text arranges itself vetically in relation to, for example, images in the middle of the text. You can read all about it and see other examples of its use by clicking here.

Margins & Padding

Margins are the spacing between a given HTML element and those above and below, and those to the left and to the right. Padding is the space between the 4 margins of the HTML element and any of is contents.

DEFAULT FOR MARGINS: 0px(pixels).

DEFAULT FOR PADDING: 0px(pixels).

You can read more about margins by clicking here and more about padding by clicking here.

You can specify both padding and margins in 3 different ways:

  • SHORTHAND:
     margin: 10px;
     padding:10px;
    
     This way sets left, right, top & bottom margins and left, right, top & bottom padding via a single value, 
     in this case 10px(pixels).
    		
  • LONG HAND:
     margin: 10px 10px 1
     padding:10px 10px
     margin: 10px 10px 10px
     padding:10px 10px 10px
     margin: 10px 10px 10px 10px;
     padding:10px 10px 10px 10px;
     
     This way sets left, right, top & bottom margins and left, right, top & bottom padding via 2 to 4 values, 
     in this case 10px(pixels). The order of the individual padding and margins is as follows:

    padding: top right bottom left; margin: top right bottom left;
  • INDIDUALLY:
     margin-left: 10px;
     margin-right: 10px;
     margin-top: 10px;
     margin-bottom: 10px;
    
     And...
    padding-left: 10px; padding-right: 10px; padding-top: 10px; padding-bottom: 10px;

No margins or padding

<div style="display:inline-block;background-color:blue;color:white;width:200px;height:100px;">XXXXXX</div>
<div style="display:inline-block;background-color:green;color:white;width:200px;height:100px;">XXXXXX</div>
<div style="display:inline-block;background-color:red;color:white;width:200px;height:100px;">XXXXXX</div>
<div style="display:inline-block;background-color:cyan;color:white;width:200px;height:100px;">XXXXXX</div>
<div style="display:inline-block;background-color:purple;color:white;width:200px;height:100px;">XXXXXX</div>
<div style="display:inline-block;background-color:magenta;color:white;width:200px;height:100px;">XXXXXX</div>
<div style="display:inline-block;background-color:yellow;color:white;width:200px;height:100px;">XXXXXX</div>
<div style="display:inline-block;background-color:navy;color:white;width:200px;height:100px;">XXXXXX</div>
<div style="display:inline-block;background-color:maroon;color:white;width:200px;height:100px;">XXXXXX</div>
XXXXXX
XXXXXX
XXXXXX

XXXXXX
XXXXXX
XXXXXX

XXXXXX
XXXXXX
XXXXXX

Margins at 40 pixels and no padding

<div style="display:inline-block;background-color:blue;color:white;width:200px;height:100px;margin:40px;">XXXXXX</div>
<div style="display:inline-block;background-color:green;color:white;width:200px;height:100px;margin:40px;">XXXXXX</div>
<div style="display:inline-block;background-color:red;color:white;width:200px;height:100px;margin:40px;">XXXXXX</div>
<div style="display:inline-block;background-color:cyan;color:white;width:200px;height:100px;margin:40px;">XXXXXX</div>
<div style="display:inline-block;background-color:purple;color:white;width:200px;height:100px;margin:40px;">XXXXXX</div>
<div style="display:inline-block;background-color:magenta;color:white;width:200px;height:100px;margin:40px;">XXXXXX</div>
<div style="display:inline-block;background-color:yellow;color:white;width:200px;height:100px;margin:40px;">XXXXXX</div>
<div style="display:inline-block;background-color:navy;color:white;width:200px;height:100px;margin:40px;">XXXXXX</div>
<div style="display:inline-block;background-color:maroon;color:white;width:200px;height:100px;margin:40px;">XXXXXX</div>
XXXXXX
XXXXXX
XXXXXX

XXXXXX
XXXXXX
XXXXXX

XXXXXX
XXXXXX
XXXXXX

Padding at 40 pixels and no margins

<div style="display:inline-block;background-color:blue;color:white;width:200px;height:100px;padding:40px;">XXXXXX</div>
<div style="display:inline-block;background-color:green;color:white;width:200px;height:100px;padding:40px;">XXXXXX</div>
<div style="display:inline-block;background-color:red;color:white;width:200px;height:100px;padding:40px;">XXXXXX</div>
<div style="display:inline-block;background-color:cyan;color:white;width:200px;height:100px;padding:40px;">XXXXXX</div>
<div style="display:inline-block;background-color:purple;color:white;width:200px;height:100px;padding:40px;">XXXXXX</div>
<div style="display:inline-block;background-color:magenta;color:white;width:200px;height:100px;padding:40px;">XXXXXX</div>
<div style="display:inline-block;background-color:yellow;color:white;width:200px;height:100px;padding:40px;">XXXXXX</div>
<div style="display:inline-block;background-color:navy;color:white;width:200px;height:100px;padding:40px;">XXXXXX</div>
<div style="display:inline-block;background-color:maroon;color:white;width:200px;height:100px;padding:40px;">XXXXXX</div>
XXXXXX
XXXXXX
XXXXXX

XXXXXX
XXXXXX
XXXXXX

XXXXXX
XXXXXX
XXXXXX

Note how the divs have been enlarged in order to accomodate the internal padding along all sides.

Overflow

Another important CSS attribute is 'overflow'. Or in other words, what happens to the contents of a HTML element if it does not fit within the boundaries of the element. You can read more about this CSS attribute by clicking here.

DEFAULT: visible.

overflow: visible;

<div style="display:block;background-color:black;color:white;width:400px;height:100px;overflow:visible;">
		Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard 
		dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen 
		book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially 
		unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more 
		recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</div>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

 

 

 

 

overflow: hidden;

<div style="display:block;background-color:blue;color:black;width:400px;height:100px;overflow:hidden;">
		Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard 
		dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen 
		book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially 
		unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more 
		recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</div>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

overflow: scroll;

	<div style="display:block;background-color:blue;color:black;width:400px;height:100px;overflow:scroll;">
			Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard 
			dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen 
			book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially 
			unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more 
	recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</div>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

overflow: auto;

<div style="display:block;background-color:blue;color:black;width:400px;height:100px;overflow:auto;">
		Lorem Ipsum is simply dummy text
</div>
Lorem Ipsum is simply dummy text
<div style="display:block;background-color:blue;color:black;width:400px;height:100px;overflow:auto;">
		Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard 
		dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen 
		book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially 
		unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more 
		recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</div>
 
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
Notice that, 'overflow' set on 'auto' the HTML element shows the scroll bar(s) only if the size of content exceeds the size of HTML element.

Action selectors

These are also reffered to as 'pseudo-classes'. Don't concern yourself with what that term means, just be aware that it is used interchangeably with 'action selectors'. There are MANY 'action selectors' and you can read all about them by clicking here. But the most frequently used on is the 'hover' selector. I.E. When the mouse cursor hovers within the boundaries of a HTML element. Let's explore some examples of its use.

Change background color on mouse cursor hover

In this example the div element will change its back ground color when the mouse cursor hovers over the top of it.

HTML

<div class="div2">XXXXX<div">

CSS between the style tags <style>...</style>

<style>
.div2
{
	background-color: navy;
	color: white;
	font-weight: bold;
}
.div2:hover
{
	background-color: blue;
	color: white;
	font-weight: bold;
}
</style>
XXXXXXXXX

Make an element disappear on mouse cursor hover

In this example the div element will disappear when the mouse cursor hovers over the top of it.

HTML code
<div class="div3">XXXXX<div">

CSS between the style tags
<style>
	.div3
	{
	    background-color: navy;
	    color: white;
	    font-weight: bold;
	}
	.div3:hover
	{
	   /* This is a CSS comment and only HTML elements with class="div3" will disappear if the mouse cursor hovers over them. */
	   visabilty: hidden;
	}
</style>
XXXXXXXXX

Change the mouse cursor on hover

In this example the mouse cursor changes when it hovers over the top of the div.

HTML code
<div class="div4">XXXXX<div">

CSS between the style tags.
<style>
.div4
{
	background-color: navy;
	color: white;
	font-weight: bold;
}
.div4:hover
{
   /* This is a CSS comment and the cursor will only change if the mouse cursor hovers over HTML 
      elements with class="div4". */
   cursor: crosshairs;
}
</style>
XXXXXXXXX

The hover action selector can also be applied to:

  • 'id' selectors, e.g. #div_name:hover (all elements with an id value of "div_name").
  • 'tag' selectors, e.g. p:hover (all p or paragraph elements).

Further learning

There are hundreds more CSS attributes than you can experiment with, and see what they do. Some attributes work on particular types of HTML elements but have no effect on others. The best way to learn about them is to experiment. You can learn about them through the CSS reference at W3 Schools. It includes a bunch of tutorials you can work your way through. And plenty of 'try it yourself' spaces where you can experiment with different values for each CSS attribute and see exactly how they effect the way the HTML appears in a web browser.

Javascript for beginners

Intoduction

JavaScript is the programming language of the web, and is supported by all major web browsers. It can calculate, manipulate and validate data. And it can change both HTML and CSS, and in so doing, generate dynamic HTML content that is responsive to user input The syntax rules and constructs of JavaScript very closely resemble those of the programming language C, with minor differences.

This is not intended as a comprehensive tutorial on JavaScript. Rather the intention is to give you a general feel of the language, and detail some of its constructs. More comprehensive JavaScript tutorials are available here:

  • Tutroials for raw beginners, click here
  • Tutorials for those with some programming knowledge, click here.

What is programming language?

A programming language occupies a niche some where between plain English and binary computer language that consists only of 1's and 0's. Higher level programming languages, like C and JavaScript, are closer to the English end of the spectrum. While assmebly language is much closer to binary computer language.

In the case of programming languages like C, your program must be compiled and linked into a '.exe' or executable file. These contain binary computer language instructions that allow the computer CPU to 'implement' your program. In the case of script language like JavaScript, your program remains permanently as human readable text, and the web browser converts it, one line at a time, to binary computer language. And passes each set of instrictions, in turn, onto the CPU to carry out and 'implement' your program.

Reserved words

In JavaScript you cannot use these reserved words as variables, labels, or function names. Now this rule is VERY literal! The following function declaration will cause a JavaScript syntax error in a web browser:

	function if(arg1, arg2){...};
	
	However any of these function declarations are perfectly legal in JavaScript:
	
	function i_f(arg1, arg2){...};
	function _if(arg1, arg2){...};
	function if_(arg1, arg2){...};
	function If(arg1, arg2){...};
	function iF(arg1, arg2){...};
	function IF(arg1, arg2){...};
abstract arguments async await boolean break
byte case catch char class const
continue debugger default delete do double
else enum eval export extends false
final finally float for function goto
if implements function import in instanceof
int interface let long native new
null package private protected public return
short static super switch synchronized this
throw throws transient true try typeof
using var void volatile while with
yield

Data types

JavaScript has the following data types:

Type Description Examples Using typeof
number A whole number or a decimal number.

Maximum safe integer: 9007199254740991 or Number.MAX_SAFE_INTEGER

Minumum safe integer: -9007199254740991 or Number.MIN_SAFE_INTEGER

Maximum safe decimal number: 1.7976931348623157e+308 or Number.MAX_VALUE

Minimum safe decimal number: 5e-324 or Number.MIN_VALUE

These are in scientific notation,
e.g. 1.7976931348623157e+308 means
1.7976931348623157 x 10308
10, -1, 1257, -385, 3.142, -3.142 typeof x & typeof(x) returns number
Bigint A large integer exceeding 9007199254740991 12345678901234567890n or BigInt("12345678901234567890") typeof x & typeof(x) returns Bigint
boolean A data type representing true or false Only two possible values: either literal value true or false typeof x & typeof(x) returns boolean
Undefined A variable with no assigned value let x; /* x has no defined value. */
let x - 10; /* x has a defined value of 10. */
typeof x & typeof(x) returns undefined
Symbol Essentially special characters, e.g. the symbol for the British pound, and emojies that are not available on your keyboard. COPYRIGHT / ©: &#169; or &copy typeof x & typeof(x) returns symbol
Array You can think of these like a row of office pigeon holes for mail. let arrayInts = {2, 45, 23, 56, 32}; document.write("Array element 2 contains " + arrayInts[1]); // Outputs the string "Array element 2 contains 24"
let arrayInts = {2, "Helo world, true, 3.142, false}; document.write("Array element 2 contains " + arrayInts[1]); // Outputs the string "Array element 2 contains Hello world"
typeof x & typeof(x) returns Array
Object A collection of key-value pairs of data. This is a very simple example of an object:

let objectMap = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"}; In programming it is also called a map, and you access its contents like this:

objectMap.firstName /* Contains the string "John" */
objectMap["firstName"] /* Contains the string "John" */
objectMap.age /* Contains the integer 50 */
objectMap["age"] /* Contains the integer 50 */

Objects can be huge nested data structures, for example, we could add another value pair to the above example:

let objectMap = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue", education:{.......}}; Where 'education' is itself an object listing all the qualifications that John has.
typeof x & typeof(x) returns object
Null A value representing object absence typeof x & typeof(x) returns null
String A string of characters or text. You can enclose string in either double quite " or single quote '. "Hello world" or 'Hello world'

You can also nest a string within a string by doing this:

"Hello 'XXXXX' world" or
"Hello \"XXXXX\" world" or
'Hello \'XXXXX\' world'

It might seem weird but the necessity to nest strings within strings does crop up.
typeof x & typeof(x) returns string

Literal values

We have seen some examples of literal values in the previous section.

E.G. "Hello world", 10, 3.142, true and false.

Variables explained

Another programming construct that needs to be explained is a 'variable'. You have come across this concept before when studying algebra in high school maths class, with linear equations, e.g. y = 3x + 5. Choose a value for x and you can calculate a value for y, e.g. if x = 2 then y = 2 * 2 + 5 = 9. The letter x is a variable and it is a place holder for some numeric value. You can think of it as an empty box into which you can place a numeric value written down on a piece of paper.
JavascriptVariable.jpg
Assign a new value to a variable:
JavascriptVariableNewValue.jpg

In reality a variable is a small chunk of the computer RAM or Random Access Memory. RAM as accessed via an integer address, e.g. memory slot number 1038465843. But it would be rather inconvenient to have to use variables something like this:
let '1038465843' = 20.

Instead programing languages store '1038465843' against a variable name, nStudentNumber for example. It is so much easier to remember 'nStudentNumber', in your code, than '1038465843';

In JavaScript you must 'declare' your variables before you can use them else where, otherwise the web browser will raise a syntax erroralong the lines of 'variable was not declared'. They keyword 'let' and 'var' are used for this purpose, e.g.

let x; var y;

The 'var' keyword creates a 'God' variable that is said to have 'global' scope. You can use that variable ANYWHERE throughout your code and it does not matter where you declared it. The 'let' keyword on the other hand creates a limited variable that is said to have local scope. For example, if you creata a local variable with 'let' inside a function then you can only use that variable inside your function and no where else in your code. It is best practice to use 'let' most of the time and keep the use of 'var' to an absolute minimum, or preferably avoid uisng it at all.

You can decalre multiple variables with the same let or var statements like this:

let x, y, z; var x, y, z; In this case the value of all these variables is undefined until you explicitly put a value in them. Alternatively you can initialise your variables to a known value, at the same time as declaring them, like this:

let x = 0, y = true, z = "Hello world; var x = 3.142, y = null, z = false;

One other thing that is important to note is that JavaScript is not a 'typed' language - you do not declare your variables with a data type. And you can do all of the following without generating any JavaScript errors.

let x = 0; x = "Hellow world"; x = true; x = 3.142;

The programming language 'C' is very different - it is a strictly typed language when you declare variables you must specifiy their data type:

int x = 0; All of these assignments are 'legal':

x = 20; x = 101; x = -230; But any of these assignments are 'illegal' and will cause a compile error, because they are not integer values:

x = true; x = "Hello world"; x = 3.142;

Statements

In JavaScript the semi-colon (;) is like the full stop (.) in English. All JavaScript statements must end with a ; or else you will get a JavaScript error. Here are some examples of statements:

let x = 10; x = 100; x += 1; This whole if/else construct is a compound statment:
if (x == 10) /*then*/
document.write("x is equal to 10!"); else
document.write("x is not equal to 10!"); So is this while construct:

while (x < 10)
x = x + 1; The while loop statement ends at the semi colon.

You can read more about JavaScript statements by clicking here.

Expressions

Expressions are used as part of statements. Here are some examples:

let x = 10; if (x == 10) /*then*/
document.write("x is equal to 10!"); else
document.write("x is not equal to 10!"); x = x + 1; (x == 10) is an expression that is testing the value of x against 10. If x contains 10 then (x == 10) evaluates to true. If not then it evaluates to false. Similarly x + 1 is an expression that evaluates to 2 - x contains 1, we add 1 to 1 and we get 2 and then the value 2 is put back into x. If we repeat this statement (x = x + 1;) then x will contain x + 1 = 2 + 1 = 3

If you put an epxression in your code like this:

let x = 0; x + 1; Then the expression x + 1 is 'hanging'. It will get evaluated but the result (1) will disappear into thin air, so to speak, and have no effect what so ever on your web page. It must be part of a complete statement, as in the previous examples, to be of any use to you web page.

You can read more about JavaScript expressions by clicking here.

Operators

Assignment operators

Operator Name Example Results
= Simple assign let x = 5;
x = 10;
x
= 5
x 5

x 5
= 10
x 10
+= Add & assign x += 5
x 10
= 10 + 5
x 15
-= Subtract & assign x -= 5
x 15
= 15 - 5
x 10
*= Multiply & assign let x = 10;
x *= 5
x 10
= 10 x 5
x 50
/= Divide & assign let x = 10;
x /= 5
x 50
= 50 / 5
x 10
%= Remainder & assign let x = 10;
x %= 3
x 10
= 10 % 3 = 3 with remainder 1
x
: Alternative simple assign x: 45;
x 1
45
x 45

Arithmetic operators

Operator Name Example Results
+ Addition x = x + 2;
x 45
= x + 2 = 45 + 2
x 47
- Subtraction x = x - 2;
x 47
= x - 2 = 47 - 2
x 45
+ Unary positive x= +x;
x 45
= x * +1 = 45 * +1 = 45
x 45
- Unary negative x = -x;
x 45
= =x * -1 = 45 * -1 = -45
x -45
* Multiplication x = x * 2;
x -45
= x * 2 = -45 * 2 = -90
x -90
/ Division x = x / 2;
x -90
= x / 2 = -90 / 2 = -45
x -45
** Exponentiation x = x ** 3;
x -45
= -453 = x * x * x = -45 * -45 * -45 = -91,125
x -91,125
% Remainder after division x = x % 2;
x -91,125
= x / 2 = -91,125 / 2 = -45,562 with 1 remainder
x 1
++ Increment y = x++;
x 1
y ?
y = x++, x = 1 therefore y = 1 before x is incremented
y 1
x = x + 1 = 1 + 1 = 2
x 2
++ Increment y = ++x;
x 1
y ?
x = x + 1 = 1 + 1 = 2
x 2
x = 2 therefore y = 2 before x is incremented.
y 2
x = x + 1 = 1 + 1 = 2
= x = 2
-- Decrement y = x--;
x 2
y ?
y = x--, x = 2 therefore y = 2 before x is decremented
y = 2
x = x - 1 = 2 - 1 = 1
x 1
-- Decrement y = --x;
x 2
y ?
x = x - 1 = 2 - 1 = 1
x 1
= x = 1 therefore y = 1 after x is decremented.
y 1

Comparison operators

These operators are used to make comparisons between values and always return a boolean value (either true/1 or false/0).

From above x currently contains the value 0.

Operator Name Example Results
== Equal to (data type of operands do not have to match)? x == 8, x == 0, x == false false, true,true
=== Strict equal to (data type of operands must also match)? x === 8, x === 0, x === false false, true, false
!= Not equal to (data type of operands do not have to match)? x != 8, x != 0, x != false true, false, false
!== Strict not equal to (data type of operands must also match)? x !== 8, x !== 0, x !== false true, false, true
> Greater than? x > 8, x > 0, x > -1 false, false, true
< Less than? x < 8, x < 0, x < -1 true, false, false
>= Greater than or equal to? x >= 8, x >= 0, x >= -1 false, true, false
<= Less than or equal to? x <= 8, x <= 0, x <= -1 true, true, false

Logic operators

These operators are used to combine individual comparisons into a single boolean result.

From above x currently contains the value 0.

Operator Name Examples Results
&& AND (x < 10) && (x > 1) (0 < 10) && (0 > 1) = true && false = false
|| OR (x < 10) || (x > 1) (0 < 10) || (0 > 1) = true || false = true
! NOT !(x == 0), !(x > 10) x = !(0 == 0) = !true = false, !(0 > 10) = !false = true
?? Nullish Coalescing let x = 10;
docummentwrite(x ?? "x is null or undefined");

let x;
docummentwrite(x ?? "x is null or undefined");
10

"x is null or undefined"

Bitwise operators

To understand these operators you must first understand how to count in binary or base 2. We intuitively count in decimal, in which there a 10 digits: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9. And we structure decimal or base 10 numbers with the following columns, and we start off with a 0 in the units colum and proceed to increment the digits until we reach 9 in the units column.

1000s / 103 100s / 102 10s / 101 1 / 100
0
1
2
3
4
5
6
7
8
9

Now there is no single digit that represents the value 10, so we have to represent it using the available digits. What we do is to change the units column back to 0 and put a 1 in the tens column.

1000s / 103 100s / 102 10s / 101 1 / 100
0
1
2
3
4
5
6
7
8
9
1 0
1 1

And we keep following this rule with the hundreds and thousands columns, and beyond.

Computers are built up from a simple construct called a flipflop, made from 2 transtors. And a flipflop has only 2 possible states: on (representing the digit 1) and off (representing the digit 0). So therefore computers can ONLY count in binary or base 2. The rules for counting in binary are EXACTLY the same as those for counting in decimal, except that you have only 2 digits - 0 and 1. When a column reaches 2 we change it back to 0 and add a 1 to the column to the left.

16s / 24 8s / 23 4s / 22 2s / 21 1s / 20 DECIMAL
0 0
1 1
1 0 2
1 1 3
1 0 0 4
1 0 1 5
1 1 0 6
1 1 1 7
1 0 0 0 8
1 0 0 1 9
1 0 1 0 10
1 0 1 1 11
1 1 0 0 12
1 1 0 1 13
1 1 1 0 14
1 1 1 1 15

Binary or base 2 is not the only counting system used in computer programming. Another very common counting system is hexadecimal or base 16. The digits (1 to 16) are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F. And we follow the exact same rules but using an larger number of digits.

5
65536s / 164 4096s / 163 256s / 162 16s / 161 1s / 160 DECIMAL
0 0
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
A 10
B 11
C 12
D 13
E 14
F 15
1 0 16
1 1 17
1 2 18
1 3 19
1 4 20
1 5 21
1 6 22
1 7 23
1 8 24
1 9 25
1 A 26
1 B 27
1 C 28
1 D 29
1 E 30
1 F 31
2 0 32

And you will also need to get your head around the truth tables for each of these bitwise operators. Truth tables traditionally use 1 and 0. But 1 also means true and 0 also means false. The truth tables combine single bits via the operators. A single bit is either a 0 or a 1. In the binary counting table above a 'bit' is the value (either 1 or 0) in one single column. The unit column, or the right most bit, is said to be the least signficant bit, while the 65535s column, or the left most column, is be the most signficant bit.

& / AND
If both bits are 1 then the result is 1
0 1
0 0 0
1 0 1
| / OR
If either bit is 1 then the result is 1
0 1
0 0 1
1 1 1
^ / XOR
If both bits are different then the result is 1
0 1
0 0 1
1 1 0
! / NOT
!1 is 0 and !0 is 1
0 1
1 0

Now to use these bitwise operators on numbers that have more than one bit or column you simply line them up, one above the other right justified, e.g. 5 | 8

23 22 21 20 DECIMAL
1 0 1 (5)
1 0 0 0 (8)

Any missing columns in either number you just fill in with 0s.

23 22 21 20 DECIMAL
0 1 0 1 (5)
1 0 0 0 (8)

Then you just use the appropriate truth table above for each pair of bits in the same column.

23 22 21 20 DECIMAL
0 1 0 1 (5)
| OR 1 0 0 0 (8)
1 1 0 1 (13)

Operator Name Examples Example as binary Result in binary Result in decimal
& AND x = 5 & 1 0101 & 0001 0001 1
| OR x = 5 | 1 0101 | 0001 0101 5
~ NOT x = ~ 5 ~0101 1010 10
^ XOR x = 5 ^ 1 0101 ^ 0001 0100 4
<< Shift bits to the left x = 5 << 1 0101 << 1 1010 10
>> Shift bits to the right x = 5 >> 1 00000101 >> 1 00000010 2

Miscellaneous operators

Operator Description Examples
. or period Access a member of an object.
	let objPerson = {name: "Greg", age: 60, eyes: "blue"};
	document.write(objPerson.name);
[ ] Array indexing.
	let arrayInts = {10, 45, 345, 3, 46};
	document.write(arrayInts[0] /*The first array element*/);
	document.write(arrayInts[4] /*The last array element*/);
	Arrays are 0 based so the last element is always one less than the total number of elements.
[ ] Map indexing.
	let objPerson = {name: "Greg", age: 60, eyes: "blue"};
	document.write(objPerson["name"]);
?. Optional chaining.
	// Create an object
const car = {type:"Fiat", model:"500", color:"white"}; // Ask for car name: // This would cause a JavaScript error and halt JavaScript execution, because the object 'car' does not contain a member called 'name'. document.getElementById("demo").innerHTML = car.name; //This would not cause a JavaScript error - it simply returns null or undefined and allows JavaScript execution to continue. document.getElementById("demo").innerHTML = car?.name;
... Used to append arrays or to pass array elements
to a function as individual parameters.
	const arr1 = [1, 2, 3];
	const arr2 = [4, 5, 6];
	const arr3 = [...arr1, ...arr2];/* Equivalent to const arr3 = [1, 2, 3, 4, 5, 6];*/
	
	const numbers = [23, 55, 21, 87, 56];
	let minValue = Math.min(...numbers);/* Equivalent to Math.min(23, 55, 21, 87, 56);*/
( ) Expression
	let x = 10;
	if (x < 10)
			document.write("x is less than 10!");
	else
			document.write("x is not less than 10!");
( ) Function call.
	function printText(strText)
	{
			document.write(strText);
	}
	printText("Hello world");
=> A shorthand way of defining a function.
	const add = (a, b) => a + b;
	let result = add(1, 2);		
=new Create an instance of an object.
	let today = new Date();
delete Delete an instance of an object.
	let today = new Date();
	delete today;
in Is this data in that object?
	// Create an object
const car = {type:"Fiat", model:"500", color:"white"}; if ("name" in car)
document.write("The name of the car is " + car.name + "."); else
document.write("The object car does not contain a member called 'name'.);
instanceof Is this an instance of that object or data type?
	const arrayInts = [1, 2, 3];
	if (arrayInts instanceof Array)
		document.write("arrayInts is an instance of Array!");
	else
document.write("arrayInts is not an instance of Array!");
typeof Get the data type of this variable.
	const arrayInts = [1, 2, 3];
	document.write(typeof arrayInts); /* Outputs Array*/
void A shorthand way of defining an empty function.
	<input type="button" value="CLICK ME" onclick="void(0)">
yield Pauses execution of a loop, retains the loops current state and returns excution control to the code that started the loop. The loop can then be resumed by calling the next() function

Constructs

Grouped statements

You can group more than one individual statements together, so that they behave like a single statement in the following constructs by using {(meaning begin grouped statements) and }(meaning end grouped statements). Here is an example:

let x = 0;
while (x < 10)
{
	document.write("x currently has the value of " + x + "<br/>");
	x++;/* Add 1 to x */
}

The loop will iterate 10 times and x will start of with the value 0 and end up with the value 9, before the loop terminates. So you would see the following output:

	x currently has the value of 0
	x currently has the value of 1
	x currently has the value of 2
	x currently has the value of 3
	x currently has the value of 4
	x currently has the value of 5
	x currently has the value of 6
	x currently has the value of 7
	x currently has the value of 8
	x currently has the value of 9

Conditional statements

if, else if, else

You can read more about if statements by clicking here and if/else if/else statements by clicking here.

The if...else if...else statement tests one or more conditons, sequentially, and only executes the statement or statements for the condition that evaluates to true. If none of conditions are true then it executes the statement or statements for else clause (if present). Here are some varied examples:

let x = 10;
if (x == 10)
	document.write("x does equal 10!");
let x = 10;
if (x == 10)
	document.write("x does equal 10!");
else
	document.write("x does not equal 10!");
let x = 10;
if (x == 10)
	document.write("x does equal 10!");
else if (x == 9)
	document.write("x equal 9!");
else if (x == 8)
	document.write("x equal 8!");
else if (x == 7)
	document.write("x equal 7!");
else if (x == 6)
	document.write("x equal 6!");
else if (x == 5)
	document.write("x equal 5!");
else if (x == 4)
	document.write("x equal 4!");
else if (x == 3)
	document.write("x equal 3!");
else if (x == 2)
	document.write("x equal 2!");
else if (x == 1)
	document.write("x equal 1!");
let x = 10;
if (x == 10)
	document.write("x does equal 10!");
else if (x == 9)
	document.write("x equal 9!");
else if (x == 8)
	document.write("x equal 8!");
else if (x == 7)
	document.write("x equal 7!");
else if (x == 6)
	document.write("x equal 6!");
else if (x == 5)
	document.write("x equal 5!");
else if (x == 4)
	document.write("x equal 4!");
else if (x == 3)
	document.write("x equal 3!");
else if (x == 2)
	document.write("x equal 2!");
else if (x == 1)
	document.write("x equal 1!");
else
	document.write("x does not equal 1, 2, 3, 4, 5, 6, 7, 8 or 9!");

switch/case

Switch statements are useful for testing ordinal data types, such as integers. Here is an example:

let x = 10;
switch (x)
{
	case 1:
		document.write("x is equal to 1!");
		break;
	case 2:
		document.write("x is equal to 2!");
		break;
	case 3:
		document.write("x is equal to 3!");
		break;
	case 4:
		document.write("x is equal to 4!");
		break;
	case 5:
		document.write("x is equal to 5!");
		break;
	case 6:
		document.write("x is equal to 6!");
		break;
	case 7:
		document.write("x is equal to 7!");
		break;
	case 8:
		document.write("x is equal to 8!");
		break;
	case 9:
		document.write("x is equal to 9!");
		break;
	default:
		document.write("x is not equal to 1, 2, 3, 4, 5, 6, 7, 8 or 9!");
		break;
}

Ternary operator

The ternary operator is a shorthand way of implementing simple if/else statement as an expression. Here is an example:

	let x = 10;
	document.write((x == 10) ? "x is equal to 10!" : "x is not equal to 10!");

Loops

for loop

You use for loops when you know what the start condition is and when the end condition will be reached. You typically use for loops when iterating through an array which always have a known size. Here is an example:

	let arrayInts = {12, 34, 3, 567};
	for (let nI = 0; nI < arrayInts.length; nI++)
	{
		document.write("Array element number " + nI + " contains the value " + arrayInts[nI] + "!");
	}

while loop

While loops will iterate 0 or more times. You use them when you:

  • Don't know what the start condition is, e.g. you ask the user to enter a value between 1 and 10 for x.
  • Don't know when the end condition will become true, e.g. when reading lines from a text file - you have no idea how many lines of text the file contains and you keep reading until you hit the end of the file.
	let x = 0;
	while (x < 10)
	{
		document.write("x currently has the value of " + x + "<br/>");
		x++;/* Add 1 to x */
	}

The loop will iterate 10 times and x will start of with the value 0 and end up with the value 10, after the loop terminates. So you would see the following output:

	x currently has the value of 0
	x currently has the value of 1
	x currently has the value of 2
	x currently has the value of 3
	x currently has the value of 4
	x currently has the value of 5
	x currently has the value of 6
	x currently has the value of 7
	x currently has the value of 8
	x currently has the value of 9
	let x = 10;
	while (x < 10)
	{
		document.write("x currently has the value of " + x + "<br/>");
		x++;/* Add 1 to x */
	}

The loop will iterate 0 times and x starts with the value 10 and ends with the value 10 after the loop terminates. So you will see no output.

	let x = 9;
	while (x < 10)
	{
document.write("x currently has the value of " + x + "<br/>"); x++;/* Add 1 to x */ }

The loop will iterate 1 time and x will start of with the value 9 and end up with the value 10, after the loop terminates. So you would see the following output:

x currently has the value of 9

do/while loop

Do while loops iterate 1 or more times. You use them when you know that the loop must iterate at least once but you don't know how many times. Here is an example:

	let x = 5;
	do
	{
		document.write("x currently has the value of " + x + "!");
		x++; // Increment x
	}
	while (x < 10);

You will see the following output:

	x currently has the value of 5!
	x currently has the value of 6!
	x currently has the value of 5!
	x currently has the value of 7!
	x currently has the value of 8!
	x currently has the value of 9!
	x currently has the value of 10!
	
	Note that, with a do/while loop, you see x with the value of 10. Where as with the while/do loop you do not.

Execution control

break

You can read more about 'break' by clicking here.

This is used in switch statements like this example:

let x = 10;
switch (x)
{
	case 1:
		document.write("x is equal to 1!");
		break;
	case 2:
		document.write("x is equal to 2!");
		break;
	case 3:
		document.write("x is equal to 3!");
		break;
	case 4:
		document.write("x is equal to 4!");
		break;
	case 5:
		document.write("x is equal to 5!");
		break;
	case 6:
		document.write("x is equal to 6!");
		break;
	case 7:
		document.write("x is equal to 7!");
		break;
	case 8:
		document.write("x is equal to 8!");
		break;
	case 9:
		document.write("x is equal to 9!");
		break;
	default:
		document.write("x is not equal to 1, 2, 3, 4, 5, 6, 7, 8 or 9!");
		break;
}

If you don't include them then more than the next case statement will be executed for no good reason.

It can also be used in loops as in this example:

	let x = 10;
	while (true) // This loop will execute forever.
	{
		if (x == 10)
				break; // But this if / break statement will terminate the loop.
		document.write("x currently has the value " + x + "!");
		x++; // Increment x
	}

continue

You can read more about 'contine' by clicking here.

This cause the CPU to skip back to the top of the loop without executing any of the statements below it. Here is an example.

let x = 0; while (x < 10)
{
if (x == 5)
{
x++; // Increment x
continue; // Jump back to the top of the loop and skip output
}
document.write("x currently has the value " + x + "!"); x++; // Increment x
}

You will see the following output:

x currently has the value 0
x currently has the value 1
x currently has the value 2
x currently has the value 3
x currently has the value 4
x currently has the value 6
x currently has the value 7
x currently has the value 8
x currently has the value 9

return

You can read more about 'return' by clicking here.

This cause the currently executing function to terminate and return to the caller of that function. Here is an example:

function CalculateAverage(nVal1, nVal2, nVal3, nVal4)
{
	return (nVal1 + nVal2 + nVal3 + nVal4) / 4;
}
document.write("The average of 3, 6, 78 and 34 is " + CalculateAverage(3, 6, 78, 34));

You can use return at any point in your function and you don't have to combine it with a return value. You can just do return;

throw & catch

You can read more about 'throw' by clicking here.

function myFunction()
{
	let x = document.getElementById("demo").value;
	try
	{
		if (x == "")
			throw "Contents of element with ID 'demo' is empty!";
		else if (isNaN(x))
			throw "Contents of element with ID 'demo' is not a number";
		else if (x > 10)
			throw "Contents of element with ID 'demo' is too high";
		else if (x < 5)
			throw "Contents of element with ID 'demo' is too low";
	}
	catch(strError)
	{
		document.write(strError);
	}
}

Defining and calling functions

A function is a reusable block of code designed to perform a specific task, which executes when it is "called" or "invoked". It saves you having to repeat and debug that particular segment of code in 100s of places throught your program. Or in simpler terms, it saves you a considerable amount of repeated typing. In JavaScript you define a function like this:

function FunctionName(<Optional parameter1>, <Optional parameter2>, ... , <Optional parameterN>)
{
	<Statement 1>
	<Statement 2>
	.
	.
	.
	<Statement N>
}

You can use a 'return' statement at any point in the function. This can include an optional value to return, e.g. return (Optional parameter1 + Optional parameter2 + ... Optional parameterN)/ N; Here is a specific example of a function that returns a value, with JavaScript comments to explain it.

function CalculateAverage(arrayValueList)
{
	let nTotal = 0;

	if (typeof arrayValueList != Array) // Make sure the parameter is actually an array object
		return "ERROR: Parameter arrayValueList is not an array!"; // The parameter is not an array so we can't calculate an average so abort the function.
	else
	{
		for (let nI = 0; nI < arrayValueList.length; nI++)
		{
			if (arrayValueList[nI].isFinite()) // Check if the next array element is a number.
				nTotal += arrayValueList[nI]; // The next array element is a number so add it to the total.
			else
				return "arrayValueList[" + nI + "] is not a number (" + arrayValueList[nI] + ")!"; // The next array element is not a number so we can't calculate an average so abort the function.
		}
	}
	return "The average is " + (nTotal / arrayValueList.length).toString(); // Return the average value of all the values in the array.
}

And you invoke and call the function like this:

let arrayValueList = {10, 34, 56, 78 , 98, 35, 54, 71, 43, 120};
alert(CalculateAverage(arrayValueList));// It will either display an error message or the average of all the values in the array.

Here is an example of a function that does not return an value.

function DisplayErrorMessage(strMessage)
{
	document.write("#######################################################<br/>\n");
	document.write("#######################################################<br/>\n");
	document.write("#######################################################<br/>\n");
	document.write("### AN ERROR HAS OCCURED                            ###<br/>\n");
	document.write("###                                                 ###<br/>\n");
	document.write("### " + strMessage                                  ###<br/>\n");
	document.write("###                                                 ###<br/>\n");                   
	document.write("#######################################################<br/>\n");
	document.write("#######################################################<br/>\n");
	document.write("#######################################################<br/>\n");
}

And you invoke and call the function like this:

DisplayErrorMessage("Value is not an number!");

You can read more about JavaScript functions by clicking here.

String manipulation

Using operators

You can read more about string manipulation via operators by clicking here.

You can use the assignment operators and the + operator on strings. All these string manipulations are permissable:

let str1 = "ABC", str2 = "DEF", str3 = "";
str3 = str1 + str2; // str3 now contains the string "ABCDEF"
str3 += str1; // str3 now contains the string "ABCDEFABC"

You can also use all the arithetic comparison operators with strings too. The comparisons are alphabetic, once character at a time. All these string manipulations are permissable:

let str1 = "ABC", str2 = "DEF", bResult = false;
bResult = str1 > str2; // bResult contains false because "ABC" is not alphabetically greater than "DEF"
bResult = str1 < str2 // bResult now contains false because "ABC" is not alphabetically less than "DEF"
bResult = str1 >= str2;
bResult = str1 <= str2;
bResult = str1 == str2;

String methods

You can read more about string functions by clicking here.

Here is the full list of available string functions availabe to you.

NOTE: that none of these funcion modify the original string that they are called on.

Function Usage Example
length String.length or String.length()
let x = "ABC";

x.length; // Evaluates to 3
x.length(); // Evaluates to 3
charAt() String.charAt(<Index of the character you want>)
let x = "ABC";

x.charAt(1); // Evaluates to "B"
at() String.at(<Index of the character you want>)
	let x = "ABC";
	x.at(1); // Evaluates to "B"
[ ] String[<Index of the character you want>]
let x = "ABC";

x.at[1]; // Evaluates to "B"
charCodeAt() String.charCodeAt(<Index of the character whose ASCII code you want>)
let x = "ABC";
x.charCodeAt(1); // Evaluates to 66 which is the ASCII code for the character B
codePointAt() String.codePointAt(<Index of the character whose UTF-16 code you want>)
let x = "ABC";
x.codePointAt(1); // Evaluates to 65 which is the  UTF-16 code for the character B
concat() String.concat(<The second string you want to add to the first string>)
let str1 = "ABC", str2 = "DEF";
str1.concat(str2); // Evaluates to the string "ABCDEF", the same as str1 + str2
slice() String.slice(<Index of the character to start at>, <Index of the character to end at>)
let str1 = "ABCDEF";
str1.slice(1, 4); // Evaluates to the string "BCDE"
substring() String.substring(<Index of the character to start at>, <Index of the character to end at>
let str1 = "ABCDEF";
str1.slice(1, 4); // Evaluates to the string "BCDE"
substr() String.substring(<Index of the character to start at>, <Number of character from start index>
let str1 = "ABCDEF";
str1.substr(1, 4); // Evaluates to the string "BCDEF"
toUpperCase() String.toUpperCase()
let str1 = "abcdef";
str1.toLowerCase(); // Evaluates to the string "ABCDEF"
toLowerCase() String.toLowerCase()
let str1 = "ABCDEF";
str1.toLowerCase(); // Evaluates to the string "abcdef"
isWellFormed() String.isWellFormed()
let str1 = "Hello world";
str1.isWellFormed(); // Evaluates to true - yes this string is well formed English
toWellFormed() String.toWellFormed()
let str1 = "Hello World \uD800";
str1.toWellFormed(); // Evaluates to the string "Hello world  " - any nonsense charaters are converted to the unicode replacement character)
trim() String.trim()
 style="width:94%;"
let str1 = "   ABCDEF   ";
str1.trim(); // Evaluates to the string "ABCDEF" - any leading or trailing whitespace characters are removed.
trimStart() String.trimStart()
let str1 = "   ABCDEF   ";
str1.trimStart(); // Evaluates to the string "ABCDEF   " - any leading whitespace characters are removed.
trimEnd() String.trimEnd()
let str1 = "   ABCDEF   ";
str1.trim(); // Evaluates to the string "   ABCDEF" - any trailing whitespace characters are removed.
padStart() String.padStart(<Number of charatcer to pad with>, <The character or string to pad with>)
let str1 = "1234";
str1.padStart(4, "0"); // Evaluates to the string "00001234".
padEnd() String.padEnd(<Number of charatcer to pad with>, <The character or string to pad with>)
let str1 = "1234";
str1.padEnd(4, "0"); // Evaluates to the string "12340000".
repeat() String.repeat(<Number of times to repeat the string>)
let str1 = "1234";
str1.repeat(2); // Evaluates to the string "12341234".
replace() string.replace(<Substring to find>, <String to replace it with>)
let str1 = "Please visit W3Schools";
str1.replace("W3Schools", "Microsoft"); // Evaluates to the string "Please visit Microsoft".
replaceAll() string.replace(<Substring to find>, <String to replace all occurences of it with>)
let str1 = "12341234";
str1.replaceAll("1", "X"); // Evaluates to the string "X234X234".
split() String.split(<Substring or character to split the string at>)
let str1 = "Please visit W3Schools";
str1.split(" "); // Evaluates to an array containing 3 seperate strings: {"Please", "visit", "W3Schools"}.

Miscellaneous useful functions

You can read more about these functions by clicking here. Only the functions you are most likely to use are listed here.

NAME DESCRIPTION
isFinite(ValueToCheck) Checks whether a value is a finite number. Returns true or false.
isInteger(ValueToCheck) Checks whether a value is an integer. Returns true or false.
isNaN(ValueToCheck) Checks whether a value is Number. Returns true or false.
isSafeInteger(ValueToCheck) Checks whether a value is a safe integer. Returns true or false.
MAX_SAFE_INTEGER Returns the maximum safe integer in JavaScript: (253 - 1) or (2 x 2 x 2 x ... 50 more times) - 1.
Remember counting in binary or base 2 in the section 'Bitwise operators'? 253 represents counting columns running all the way from 20 to 253. It is a VERY LARGE number of columns and they
can represent a VERY LARGE number. But if you add 1 to this number then all the columns turn back to 0 and
there no more columns on the far left to add 1 to.
MIN_SAFE_INTEGER Returns the minimum safe integer in JavaScript: -(253 - 1) or -((2 x 2 x 2 ... 50 more times) - 1)
MAX_VALUE Returns the largest number possible in JavaScript: 1.7976931348623157e+308 or 1.7976931348623157 x 10308 or 17976931348623157 followed by 292 0s
MIN_VALUE Returns the smallest number possible in JavaScript: 5e-324 or 5 x 10-324 or 0.000 ... 321 more 0s ... 5
NaN Represents a "Not-a-Number" value.
parseFloat(strTextToParse) Parses a string an returns a number. Returns a string.
parseInt(strTextToParse) Parses a string an returns a whole number. Returns a string.
toFixed(fDecimalNumber) Formats a number with x numbers of digits after the decimal point. Returns a string.
toString(Number) Converts a number to a string and returns it.

Object Orinted Programming or OOP

OOP involves self contained objects that contain a set of attributes and a set of functions. You are very familiar with this concept even though this description might seem, at face value, to be very alien to you. And therefore this method of programming makes it very much easier to do.

Consider a person such as yourself. A 'person' is a generic object that contains a bunch of common attributes that are the same for all people. E.G.

  • Legs: 2
  • Arms: 2
  • Eyes: 2
  • Fingers: 10
  • Toes: 10

A person also has a bunch of attributes that are not fixed. E.G.

  • Hair length: ?
  • Hair type: ?
  • Eye colour: ?
  • Height: ?
  • Weight: ?
  • Name: ?
  • Age: ?

So let's convert this concept to a JavaScript 'class'. A 'class' in OOP is like a set of instructions in a Ikea flat pack book shelf. The instructions are not the book shelf itself, merely describe the way you construct the book shelf. In JavaScript you need to implement a special initialisation function called a 'constructor'. You can think of yourself as a 'constructor' function as you read the Ikea instructions and put your bookshelf together.

class CPerson
{
	constructor(strHairLength, strHairType, strEyeColor, nHeight, nWeight, strName, nAge)
	{
		this.m_nNumberOfLegs = 2;
		this.m_nNumberOfArms = 2;
		this.m_nNumberOfEyes = 2;
		this.m_nNumberOfArms = 2;
		this.m_nNumberOfFingers = 10;
		this.m_nNumberOfToes = 10;
		this.m_strHairLength = strHairLength;
		this.m_strHairType = strHairType;
		this.m_strEyeColour = strEyeColor;
		this.m_nHeight = nHeight;
		this.m_nWeight = nWeight;
		this.m_strName = strName;
		this.m_nAge = nAge;
	}
}

Hungarian notation variable naming convention

I am using a very specific naming convention here called 'Hungarian notation'. And the specific Microsoft Foundation Class variant of it. Let's take 'm_nNumberOfLegs' as an example: 'm_' is short for 'member of class CPerson' (as opposed to a stand alone variable that you would instead name 'nNumberOfLegs'. The 'n' is short for integer and 'NumberOfLegs' describes the purpose of the attribute. So briefly...

  • Classes: prefix the class name with capital C, e.g. CPerson. This provides a very CLEAR way for others to distinguish between your class names (CPerson or ikea instructions) and your objects (Person or physical Ikea bookshelf)
  • Local variables:
    • Strings or text (e.g. "Hello world"): prefix the variable name with 'str', e.g. strStudentNumber indicating to the next person that this variable will always contain string values.
    • Integers or whole numbers (e.g. 3, -10, 203): prefix the variable name with 'n', e.g. nStudentNumber, indicating to the next person that this variable will always contain integer values.
    • Floating point, real or decimal numbers (e.g. 3.142): prefix the variable name with 'f', indicating to the next person that this variable will always contain decimal values.
  • Class member variables or attributes: prefix the variable with m_ (member of) and then follow the local variable naming convention above, e.g. m_strStudentNumber.
  • Global or 'God' variablesprefix the variable with g_ (global) and then follow the local variable naming convention above, e.g. g_strStudentNumber.

Data type and member indicators, i.e. str, n, f and m_ should ALWAYS be lower case. And you should capitalise the first letter of your variable name, and choose a name that intuitively describes the purpose of your variable. Following a naming convention does not really matter for a few lines of JavaScript code with a few variables. But it makes a BIG difference when you have hundreds of lines of JavaScript code spread across more than one file.

Classes explained

Let's also look at 'CPerson': 'C' denotes that CPerson is the class definition, equivalent to the Ikea instructions. 'Person' would be an instance of class CPerson and equivalent to the physical book shelf. You can read more about 'Hungarian notation by clicking here.

'this' explained

The word 'this' ia pre-defined word in JavaScript that, in this context, refers to the class CPerson. So you use it to bring your class attributes or member variables into existence. Asking why you create class member variables by means of 'this' and is there anything deeper to understand are pointless questions. You may as well ask why is the engine of a car always at the front and why is the petrol tank spout always at the rear left of your car. The answer to both questions is because that is the way the engineers arbitrarily decided to design cars!

And similarly for JavaScript, you use 'this' because that is the way that the inventors of JavaScript arbiitraily decided to design JavaScript. Just go with it ;-)

Constructor function explained

Notice that the constructor function has 7 parameters through which one passes in values for those class attributes that have no fixed values. So, JavaScript, you would create a specific instance of a person, or a person object, by doing the following

let Greg = new CPerson("short", "straight", "blue", 184, 98, "Greg", 60);

Class inherritance explained

Now let's extend class CPerson to describe an actual person. In programing we call this 'inheritance'.

class CPoliceOfficer extends CPerson
{
	constructor(strHairLength, strHairType, strEyeColor, nHeight, nWeight, strName, nAge, strBadgeNumber, strAssignedSataion, strTitle)
	{
		super("short", "straight", "blue", 184, 98, "Greg", 60);
		this.m_strBadgeNumber = strBadgeNumber;
		this.m_strAssignedSataion = strAssignedSataion;
		this.m_strTitle = strTitle;
	}
}

So you would create a specific instance of a police officer, or a police officer object, by doing the following

let PoliceOfficeGreg = new CPoliceOfficer("short", "straight", "blue", 184, 98, "Greg", 60, "098364573", "Preston", "constable");

Class methods or functions explained

We can also define methods or functions for our classs. E.G.

class CPerson
{
	constructor(strHairLength, strHairType, strEyeColor, nHeight, nWeight, strName, nAge)
	{
		this.m_nNumberOfLegs = 2;
		this.m_nNumberOfArms = 2;
		this.m_nNumberOfEyes = 2;
		this.m_nNumberOfArms = 2;
		this.m_nNumberOfFingers = 10;
		this.m_nNumberOfToes = 10;
		this.m_strHairLength = strHairLength;
		this.m_strHairType = strHairType;
		this.m_strEyeColour = strEyeColor;
		this.m_nHeight = nHeight;
		this.m_nWeight = nWeight;
		this.m_strName = strName;
		this.m_nAge = nAge;
	}
	
	DoWalk(nHowManyMeters, nCompasBearing)
	{
		.....
	}
	
	DoPayABill(strBillerName, nBillamount)
	{
		.....
	}
}

And we can invoke those methods like this:

let Greg = new CPerson("short", "straight", "blue", 184, 98, "Greg", 60); Greg.DoWalk(100 /*meters*/, 90 /*degrees or to the right*/); Greg.DoPayBill("GloBird Enery", /*$*/100)

JavaScript comments

/*meters*/ is one way you can create code plain English comments in JavaScript. Any text between the comment markers is ignored by the web browser. The other way is to use:

\\ This is a comment.

In this case all the text to the right of the \\, up till the end of the line, will be ignored by the web browser. You can use comments to explain to other programmers how your code works and what its purpose is.

Pre-dfined JavaScript Objects

There are a number of pre-defined 'objects that you have access to in JavaScript. They are vry much bigger and more complicated than the above very simple examples. But the general idea is the same.

window

You can read about the full range of functions and attributes by clicking here.

The full list of methods and properties are not detailed here, just a subset that is frequently used in this website.

Properties

These properties are avialable to you without invoking the window object, e.g. you don't necessarily need to type 'window.console', instead your can just type 'console'.

Property Description
console Returns the console Object for the window.
Click the console link to jump to the section about the console object.
document Returns the document object for the window.
Click the document link to jump to the section about the document object.
location Returns the location object for the window.
Click the location link to jump to the section about the location object.
localStorage Allows to save key/value pairs in a web browser. Stores the data with no expiration date.
Click the localStorage link to jump to the section about the localStorage object.
screen Returns the screen object for the window.
Click the screen link to jump to the section about the screen object.
sessionStorage Allows to save key/value pairs in a web browser. Stores the data for one session, that ends when you close the browser tab or the browser.
Click the sessionStorage link to jump to the section about the sessionStorage object.

Methods

Again these properties are avialable to you without invoking the window object, e.g. you don't necessarily need to type 'window.alert("Message");', instead your can just type 'alert("Message");'.

Method Description Example
alert(strMessage) Displays an alert box with a message and an OK button.
alert("Hello! I am an alert box!");
alert.png
confirm(strMessage) Displays a dialog box with a message and an OK and a Cancel button.
let strResultMessage = "";

if (confirm("Press a button!\nEither OK or Cancel.") == true)
		strResultMessage = "You pressed OK!";
else
		strResultMessage = "You pressed CANCEL!";
confirm.png
prompt(strMessage) Displays a dialog box that prompts the visitor for input.
let strName = prompt("Please enter your name", "Harry Potter"/*Default name*/);
if (strName != null)
		document.getElementById("demo").innerHTML = "Hello " + strName + "! How are you today?";
prompt.png
open(strURL) Opens a new browser tab.
open("https://www.w3schools.com");
print() Invokes your printer dialog box so you can prints the content of the current window.
print();
scrollBy(nNumPixelsHorizontal, nNumPixelsVertical) Scrolls the document by the specified number of pixels.
scrollBy(100, 0);
scrollTo(nNumPixelsHorizontalPosition, nNumPixelsVerticalPosition) Scrolls the document to the specified coordinates.
scrollTo(500, 0);

document

To read more about the document object by clicking here.

Your entire HTML document (.html or .htm file) is read by the web browser and turned into an 'object' that you then have access to in JavaScript. It is called 'document' (case sensitive). So let's have a llok at some of the items you can find and change in the JavaScript object 'document'.

Atributes or member variables

This is just a few of the attributes available to you. You can learn about the many other by clicking the above link.

  • document.title: this gives you the text that you typed between the HTML tags <title>...</title>
  • document.head: this gives you the entire contents that you placed between the HTML tags <head>...</head>
  • document.body: this gives you the entire contents that you placed between the HTML tags <body>...</body>
  • document.URL: this gives you the full website URL of the web page, e.g. https://www.millhouse.org.au/index.php

Methods or member functions

The 'document' object also contains a bunch of useful functions that you can use and these are the most frequently used ones in this website:

  • let divElement = document.getElementById("unique_id_4_div");
    This requires that you have a HTML element, some where in your web page, with this unique ID. For example:
    <div id="unique_id_4_div">Hello world!</div>
    You should not use id="unique_id_4_div" for any other HTML element on your web page. You can use id="other_unique_id_4_div" however. If you have more than one HTML element with the same ID, like this for example:
    <div id="unique_id_4_div">Hello world!</div>
    <div id="unique_id_4_div">Hello world again!</div>
    
    In this example the second div is inaccessible via document.getElementById("unique_id_4_div");
    divElement is then a 'handle' to that particular HTML element. You can:
    • Interrigate or change the element's width or height: alert(divElement.height); and divElement.width = "100px";
    • Interrigate or change the element's styles: divElement.style.display = "none");, divElement.style.backgroundColor = "red"; and alert(divElement.style.color); /*text color*/
    • Interrogate or change the element's contents as plain text: alert(divElement.innerText); and divElement.innerText = "HELLO WORLD!";
    • Interrogate or change the element's contents as HTML code: alert(divElement.innerHTML); and divElement.innerHTML = "<span style='color:red;'>HELLO WORLD!</span>";

    If an element with the specified id value 'unique_id_4_div' cannot be found then divElement will contain null. So you always need to test for this to stop your JavaScript crashing when you try to access properties and methods in divElement. You may have mispelled your id value or you may have forgotten to add an id property to your intended element.


    Click here to see a whole bunch more examples of what you can access in an HTML element.
  • document.write("<span style='color:red;>HELLO WORLD!</span>");
    This function allows you to generate dynamic web page content, e.g. based on the user's responses to questions. There are example of its use in the W3Schools description of this function, accessible if you click the hyperlink above.

console

You can read more about the console object by clicking here.

The console is one of the tabs in a web browser's 'developer tools' and you can access it in Chrome by pressing F12. You can use it as a debugging tool for your JavaScript code but you can also use it to find and fix JavaScript syntax errors by clicking the hyperlinks in the error messages. You source code will appear with the line of code that caused the syntax error clearly highlighted.
ChromeDeveloperToolsConsoleTabError.jpg

As for debugging these are some of the useful functions you can use to output variable values and other useful information that helps you to find parts of your code that are not working as you expected.

Function Description Example
assert() Logs a message only if the provided assertion is false. If true, nothing is outputted, which helps keep logs clean.
console.assert(false);
ConsoleAssert.jpg
warn(strMessage) Similar to console.log(), but displays a message with a warning format (often yellow text/background) and a different log level, allowing filtering in developer tools.
console.warn("This is a warning!");
ConsoleWarning.jpg
error(strMessage) Displays an error message (often red text/background) to the console, useful for highlighting critical issues.
console.error("This is an error!");
ConsoleError.jpg
info(strInfo) Outputs an informational message to the console.
console.info("This is information!");
ConsoleInfo.jpg
log(strMessage) The most widely used method, it outputs a general message, variable value, or object to the console. It accepts multiple arguments, allowing you to combine text and object displays.
console.log("This is a log entry!");
ConsoleLog.jpg
table() Displays tabular data as a table, which is very useful for visualizing arrays of objects.
console.table(["Audi", "Volvo", "Ford"]);
console.table({firstname:"John", lastname:"Doe"});
ConsoleTable.jpg
These functions are used in conjunction.
group()
groupCollapsed()
groupEnd()
Creates a new inline group in the console. This indents following console messages by an additional level, until console.groupEnd() is called.
Creates a new inline group in the console. However, the new group is created collapsed. The user will need to use the disclosure button to expand it.
Exits the current inline group in the console.
console.log("Hello world!");
console.group();
console.log("Hello again, this time inside a group!");
console.groupEnd();
console.groupCollapsed();
console.log("Hello again, this time inside a collapsed group!");
console.groupEnd();
ConsoleGroup.jpg
clear() Clears the console.
console.clear();
Console.jpg

Using the console tab to fix JavaScript syntax errors

The web browser will step through your HTML and JavaScript code one line at a time. If it encounters an error in your JavaScript code then the web browser just stops rendering your web page completely. You may find parts of your web page hugely distorted or entirely missing. This is the tell take sign that you have an error in your JavaScript code. So how do you find it? In Chrome you simply hit F12 and the developer tools window will appear at the bottom or the right side of the web browser window. You can drag this window with the mouse cursor to re-position it and resize it. Notice the tabs along the top edge: 'Elements', 'Console', 'sources', 'Network',... Click the 'Console' tab. Any JavaScript errors will be displayed here.
ChromeDeveloperToolsConsoleTabError.jpg
So it is telling you that there is an error in the currently loaded web page (JavaScript_4_beginners.html) on line number 397. So to see that line number simply click on the underlined hyperlink in the error message: ChromeDeveloperToolsSourceCode.jpg
The error message tells you that nMyAge is not defined. If you look at the source code I have failed to declare nMyAge via a 'let statement', and to correct it I need to make following changes to the source code in MS Expression Web:

<script type="text/javascript">
        let nMyAge = 0;
        let nAge = nMyAge;
        nAge = 30;
</script>        

HOWEVER keep in mind that, if your original web page contains any PHP code, then that PHP code will have been removed by the web server before sending the web page to your web browser. So the line number above may not match the line number in your original web page in Expression Web (that DOES contain the PHP code).

screen

You can read more about the screen object by clicking here.

Name Description
screen.width The screen.width property returns the width of the visitor's screen in pixels.
screen.height The screen.height property returns the height of the visitor's screen in pixels.
screen.availWidth The screen.availWidth property returns the width of the visitor's screen, in pixels, minus interface features like the Windows Taskbar.
screen.availHeight The screen.availHeight property returns the height of the visitor's screen, in pixels, minus interface features like the Windows Taskbar.
screen.colorDepth The screen.colorDepth property returns the number of bits used to display one color.
All modern computers use 24 bit or 32 bit hardware for color resolution:
  • 24 bits: 16,777,216 different "True Colors"
  • 32 bits = 4,294,967,296 different "Deep Colors"
  • Older computers used 16 bits: 65,536 different "High Colors" resolution
  • Very old computers, and old cell phones used 8 bits: 256 different "VGA colors"
screen.pixelDepth The screen.pixelDepth property returns the pixel depth of the screen. For modern computers, Color Depth and Pixel Depth are equal.

location

You can read more about the screen object by clicking here.

Proprty name Description Example
window.location.href Returns the href (URL) of the current page. Or redirects the browser tab to a new URL. console.log(window.location.href); // Output will be: https://www.w3schools.com/js/tryit.asp?filename=tryjs_loc_href
window.location.href = "https://www.millhouse.org.au"; // This web will open in the bbrowser tab.
window.location.hostname Returns the domain name of the web host. console.log(window.location.hostname); // Output will be: www.w3schools.com
window.location.pathname Returns the path and filename of the current page. console.log(window.location.pathname); // Output will be: /js/tryit.asp
window.location.protocol Returns the web protocol used (http: or https:). console.log(window.location.protocol); // Output will be: https:

localStorage

You can read more about the localStorage object by clicking here.

This is a place you can permantently store JavaScript data that you need for your web page. The data will be available for the specific web page even if the user closes the web browser and opens it and your web page a few days later. You have to explicity remove any data your store in the localStorage object. You store your data as key/value pairs.E.G.

localStorage.setItem("lastname", "Smith"); // Stores the key/value pair. console.log(localStorage.getItem("lastname")); // Output will be "Smith" or undefined if the key does not exist.

Values you store in localStorage remain even if the user refreshes the web page, where as the value of all your global JavaScript variables will be lost.

sessionStorage

You can read more about sessionStorage object by clicking here.

This is a place you can temprarily store JavaScript data that you need for your web page. The data will be available for the specific web page as long as the user does not close the web browser or the tab. You store your data as key/value pairs.E.G.

sessionStorage.setItem("lastname", "Smith"); // Stores the key/value pair. console.log(sessionStorage.getItem("lastname")); // Output will be "Smith" or undefined if the key does not exist

Values you store in sessionStorage remain even if the user refreshes the web page, where as the value of all your global JavaScript variables will be lost.

Math

You can read more about the Math object constant and functions by clicking here.

Constants

Name Description
Math.E Reurns Euler's number or 2.71828182845...
Math.PI Returns PI or 3.14159265359...
Math.SQRT2 Returns the square root of 2 0r 0.69314...
Math.SQRT1_2 Returns the square root of 1/2 or 0.70710678118...
Math.LN2 Returns the natural logarithm of 2 or 0.69314718056...
Math.LN10 Returns the natural logarithm of 10 or 2.30258509299...
Math.LOG2E Returns base 2 logarithm of E or 1.44269504...
Math.LOG10E Returns base 10 logarithm of E or 0.434294481...

Functions

These functions return NaN (not a number) if x is not a number.

Name Description
Math.round(x) Returns x rounded to its nearest integer.
Math.ceil(x) Returns x rounded up to its nearest integer.
Math.floor(x) Returns x rounded down to its nearest integer.
Math.trunc(x) Returns the integer part of x.
Math.pow(x, y) Returns the value of x to the power of y.
Math.sqrt(x) Returns the square root of x.
Math.abs(x) Returns the absolute (positive) value of x.
Math.sin(x) Returns the sine (a value between -1 and 1) of the angle x (given in radians).
If you want to use degrees instead of radians, you have to convert degrees to radians.
Angle in radians = Angle in degrees * PI / 180.
Math.cos(x) Returns the cosine (a value between -1 and 1) of the angle x (given in radians).
If you want to use degrees instead of radians, you have to convert degrees to radians.
Angle in radians = Angle in degrees x PI / 180.
Math.min(a, b, c, d, ...) and Math.max((a, b, c, d, ...) These return the lowest and highest value in a list of arguments.
Math.random() Returns a random number between 0 (inclusive), and 1 (exclusive)
Math.log(x) Returns the natural logarithm of x.
The natural logarithm returns the time needed to reach a certain level of growth.
Math.log2(x) Returns the base 2 logarithm of x.
Math.log10(x) Returns the base 10 logarithm of x.

MS Expression Web for beginners

Introduction

It is important to know that MS Expression Web is not industry standard web editing software. You could not use it to edit complex coporate web sites. However for much simpler not for profit organisationsm small business and personal web sites it is STILL excellent web editing software.

Microsoft 'retired' it is about 2012 and it is now FREE to use. Itdoes use an earlier verion of HTML, while modern web browsers now use the version 5 standard. However this does not present a signficant problem when editing simple web pages and site, and you can easily work around this limitation. And Expression Web has features, that make editing an entire web site really quick and easy, that are just not available in paid & licensed web editing software.

You can download it from here.

Dynamic Web Template System

The is one of the unique features of MS Expression Web that makes editing an entire web so easy. The other feature is the 'site wizard' that creates an entire functioning web site, based on the template you select, with a few clicks of your mouse. In the process of creating your new web site MS Expression Web create a template file named 'master.dwt'. Now all the other web pages in your web site are 'built' from that template file. It is a similar idea to MS Word's document templates (.dot files).

The file master.dwt sets out the editable and non-editable parts of your web pages. So, by editing this one special file, you can change the colour scheme and layout of ALL the other web pages. MS Expression Web will ask you if you want to update them all whenever you make changes to master.dwt.

MS Expression Web uses HTML comments <!-- ... -> to mark out different regions of your web pages. And web browsers ignore HTML comments. So this is what master.dwt looks like when open in Expression Web.
ExpressionDWT.jpg
You can see that it is fully editable like a regular text file. Note this HTML comment: <!-- #BeginEditable "CustomTitle" -->. This is how Expression Web marks a region of a web page that is freely editable and not specified on the template.

This is what a web page, that is built from master.dwt, looks like when opened in Expression Web.
ExpressionWebPage.jpg
Now notice that most of the text in this newly created web page has a yellowish background color. That means 'don't change this text'. All the HTML code with the yellowish background is controlled by master.dwt. If you edit any if this text and try to save the document then Expression Web will try and convince to replace your changes with what is specified in master.dwt for that region of the file.

Also notice the the bit around "Insert content here" with the white text background. That is the part of the web page that master.dwt marks as editable and should contain content that is specific for this web page. You can type freely in this part of the web page, save your changes and Expression Web will not complain.

Also notice that you have a windows file explorer like construct that allows you to see and browser through all the files and folders that make up the entire web site. You can also create new folders and files by right clicking in here. For example, if you want to create a new web page based on master.dwt, then right click on that file and select 'New from Dynamic Web Template'.
ExpressionNewDWT.jpg

Editing HTML Tags

As you edit your HTML tags Expression Web will display context sensitive popup menus that list all the option avilable to you. But remember that Expression Web uses an earlier verion of HTML than what modern web browsers use. So these popup will not show you any options that are part of HTML version 5 only. So just keep that at the back of your mind.

List of tag names

As soon as you type '<' You will see this popup menu:
ExpressionTagPopup.jpg
You can scroll through this list and press ENTER when you find the tag you are looking for and Expression Web will type the tag name for you.

The type a space and you will see this popup menu:
ExpressionPropertyPopup.jpg
So expression web gives you a list of all the properties that are valid for that tag. Scroll through the list, find the property you are looking for and press ENTER. Again Expression Web does all the typing for you. Type another space and you will get the same list of valid properties for that tag. This will continue until you close the tag with >

This is a rather convenient way for you to get to know the tag names and the different properties that you can apply to them.

Editing CSS

If you add a 'style' property to one of your HTML elements then Expression Web will show you this popup menu. E.G. <img style="|", with the cursor sitting between the double quotes. This also works when typing between the <style>...</style> tags.< br/> ExpressionPropertyPopup.jpg
This is a list of all the CSS attributes that you can apply to your HTML tag. If you select one then press ENTER then Expression Web does the typing for you. THEN if you type a colon (:) then Expression Web will show you yet another popup menu.
ExpressionPropertyValuePopup.jpg
This time containing all the valid values that you can use with this CSS property. Select a property value by pressing ENTER and Expression Web does the typing for you. If you then type a semi-colon Expression Web will show you the list of CSS properties again.

Again this a is a really convenient way to get to know many of the CSS attributes you can play around with, and the valid values that can be applied to them.

Syntax error highlighting

Another really useful feature of Expression Web is that it highlights syntax errors in both your HTML tags and your CSS. For example:
ExpressionTagError.jpg
If you look carefully at the <h1> tag below the Latin filler text you shuld notice that it has a red underline. If you hover your mouse over that re underlined tag you will see what the problem is:
ExpressionTagErrorHover.jpg
'<p> tag cannot contain a <h1> tag' means that I have opened a <p> tag before the Latin filler text, but I have failed to close the tag - the </p> is missing. If I add that missing tag then the red underlining of the <h1> tag will disappear. The error message is telling you the same thing that I have explained here.

Now in this example I have partially closed the <p> tag but I have neglected to add the closing angle bracket to my </p tag. Now notice the yellow text backround highlighting in two places.
ExpressionMissingBracket.jpg
Again, if you hover your mouse over the highlighted text you will get an error message:
ExpressionMissingBracketHover.jpg
You also get yellow text background highlighting if you accidently duplicate tags, as in this example:
ExpressionDuplicatedTags.jpg
This feature makes it particularly easy to spot common errors in your HTML code.

Code, Split & Design Tabs

These are located at the bottom left of the editing window. The 'design' tab shows you a rough rendering of your web page as it would appear in a web browser. But it is imperfect and there may be inconsistencies between how you page appears here and how it appears in your web browser.
ExpressionDesignTab.jpg

But that is not all you can do in this tab. You can actually edit the content in much the same way as you edit a Word document. You can add new paragraphs, hyperlinks, page bookmarks and images. Just explore the 'Insert' popup menu. And you can also change text characteristics (bold, italic and underlined), create bulleted and numbered lists and change text alignment (left, center and right). Just explore the toolbar at the top of the editing window.

And then switch to the code tab to see what tags and properties have been added. Again a convenient way to get to know the tags and properties. The slit view shows you both the HTML code and the rendering at the same time.

If you want to view your web page in a web browser then locate it in the file explorer on the left hand side, right click, select 'Open with' and then click on your web browser in the list. Your web page will then open in the web browser.
ExpressionOpenWith.jpg

Renaming files and folders

Another incredibly useful feature of Expression Web is, if you rename your HTML documents, your image file names or even your folders then Expression Web will search through ALL the HTML files, linked to master.dwt, find all the hyperlinks to them or involving them and change the values of their href properties accordingly. But you have to do this within Expression Web and not in Windows file explorer.

Conclusion

MS Expression Web may, deprecated software since 2012 however, with all these VERY helpful features, I have not found its match among even paid & and licensed web editing software over the last 10 years or so. And it is toally FREE to use now.