You are on page 1of 273

Copyright © 2017 Luke Fabish

Web Coding:
An absolute beginner's
guide to HTML, CSS and
JavaScript

Luke Fabish 2017

Copyright © 2017 Luke Fabish


Ó Copyright 2017 by Luke Fabish - All rights reserved.

This document is geared towards providing exact and reliable information in regards
to the topic and issue covered. The publication is sold with the idea that the publisher
is not required to render accounting, officially permitted, or otherwise, qualified
services. If advice is necessary, legal or professional, a practiced individual in the
profession should be ordered.

- From a Declaration of Principles which was accepted and approved equally by a


Committee of the American Bar Association and a Committee of Publishers and
Associations.

In no way is it legal to reproduce, duplicate, or transmit any part of this document in


either electronic means or in printed format. Recording of this publication is strictly
prohibited and any storage of this document is not allowed unless with written
permission from the publisher. All rights reserved.

The information provided herein is stated to be truthful and consistent, in that any
liability, in terms of inattention or otherwise, by any usage or abuse of any policies,
processes, or directions contained within is the solitary and utter responsibility of the
recipient reader. Under no circumstances will any legal responsibility or blame be
held against the publisher for any reparation, damages, or monetary loss due to the
information herein, either directly or indirectly.

Respective authors own all copyrights not held by the publisher.

The information herein is offered for informational purposes solely, and is universal
as so. The presentation of the information is without contract or any type of
guarantee assurance.

The trademarks that are used are without any consent, and the publication of the
trademark is without permission or backing by the trademark owner. All trademarks
and brands within this book are for clarifying purposes only and are the owned by
the owners themselves, not affiliated with this document.

Copyright © 2017 Luke Fabish i


Contents

CONTENTS ....................................................................................................... II

HELLO, AND WELCOME ................................................................................... 1

WHAT THIS E-BOOK WILL COVER ............................................................................ 1


WHO THIS E-BOOK IS FOR ..................................................................................... 2

HTML FOR ABSOLUTE BEGINNERS ................................................................ 4

WHAT WE’RE HERE FOR (IS THIS FOR YOU?) ........................................................... 4


HOW WE’LL PROCEED........................................................................................... 4
WHAT WE’LL COVER ............................................................................................. 5
WHAT WE WON’T COVER ....................................................................................... 5
WHAT YOU’LL BE ABLE TO DO BY THE END OF THIS CHAPTER ..................................... 5
HTML BACKGROUND .......................................................................................... 6
HTML TAGS ...................................................................................................... 11
HTML TAGS FOR PAGE STRUCTURE ...................................................................... 16
KEY TAKEAWAYS ............................................................................................... 22
HTML TAGS FOR CONTENT STRUCTURE ............................................................... 22
HTML TAGS FOR STYLE AND APPEARANCE ........................................................... 39
HTML RECAP, AND NEXT STEPS .......................................................................... 42
OK, WHAT HAVE WE COVERED SO FAR? ................................................................. 42
LET’S MEET AGAIN FOR MORE HTML ................................................................... 42

CSS FOR ABSOLUTE BEGINNERS ...................................................................45

WHO IS THIS CSS GUIDE IS FOR? ..........................................................................45


CSS IN ONE CHAPTER? YOU’RE CRAZY! ..................................................................45
WHAT WE’LL COVER IN THIS CHAPTER.................................................................. 46
WHAT YOU’LL BE ABLE TO DO BY THE END OF THIS CHAPTER ................................... 46
HOW DOES CSS WORK? ...................................................................................... 48
CSS PROPERTIES AND VALUES ............................................................................. 51

Copyright © 2017 Luke Fabish ii


CSS FONT-SIZE ...................................................................................................56
CSS FONT-FAMILY ..............................................................................................59
CSS FONT-STYLE ............................................................................................... 63
CSS MARGIN (INTRODUCING THE BOX MODEL) .................................................... 64
CSS TEXT-ALIGN................................................................................................. 71
CSS BACKGROUND-COLOR ................................................................................... 72
BACK TO THE BOX MODEL: CSS BORDERS AND PADDING ......................................... 73
CSS COLOR ........................................................................................................ 76
GET THE CSS OUT OF THE HTML ......................................................................... 77
WHAT HAVE WE ACHIEVED WITH OUR CSS? .......................................................... 79
SUMMARY .......................................................................................................... 81

HTML FORMS: BEGINNERS GUIDE TO BUILDING HTML FORMS AND


INTERACTING WITH THE WEB ..................................................................... 82

WHAT ARE HTML FORMS? ................................................................................. 83


HOW TO BUILD HTML FORMS ............................................................................. 86
LET’S TAKE A CLOSER LOOK AT HTML FORM ACTION .............................................. 86
HTML FORM’S METHOD ATTRIBUTE ....................................................................87
INPUT TYPES ..................................................................................................... 89
INPUT ELEMENT RADIO BUTTONS (THERE CAN BE ONLY ONE!) ................................. 91
HTML CHECKBOXES: GETTING GREEDY WITH MULTI-SELECT ................................. 93
TAKING ACTION WITH HTML FORM SUBMIT......................................................... 96
EXPANDING OUR EXAMPLE HTML FORM ............................................................100
A FINAL SUBMISSION ON <FORMS> ..................................................................... 101

COMPUTATIONAL THINKING: HOW TO THINK LIKE A PROGRAMMER AND


FIND GREAT SOLUTIONS TO TOUGH PROBLEMS ....................................... 104

WHAT WE'LL COVER ON COMPUTATIONAL THINKING ............................................. 105


WHAT YOU’LL BE ABLE TO DO BY THE END OF THIS CHAPTER .................................. 105
GET STARTED WITH COMPUTATIONAL THINKING – TRAIN THE URKELBOT! .............. 106
HOW TO MAKE TEA............................................................................................ 106
BREAKING THE TEA PROBLEM DOWN (DECOMPOSITION) ....................................... 107
HIDDEN ASSUMPTIONS ..................................................................................... 110
TURN IT INTO A RECIPE (LET'S MAKE AN ALGORITHM) ........................................... 113
ABSTRACTIONS .................................................................................................. 117
AND LET'S REPLACE URKELBOT .......................................................................... 120

Copyright © 2017 Luke Fabish iii


JAVASCRIPT PROGRAMMING FOR ABSOLUTE BEGINNERS ....................... 122

GOALS ............................................................................................................. 122


HOW TO USE THIS CHAPTER ............................................................................... 123
HOW PROGRAMMING LANGUAGES WORK ............................................................. 126
HOW JAVASCRIPT WORKS IN YOUR BROWSER ...................................................... 129
HOW JAVASCRIPT, HTML AND THE BROWSER WORK TOGETHER ........................... 130
LET’S TRY SOME JAVASCRIPT IN A SAMPLE PAGE ................................................... 135
TIME TO ROLL YOUR OWN JAVASCRIPT ................................................................ 141
USE JAVASCRIPT TO WRITE A MESSAGE ON OUR PAGE ............................................ 146
A SIMPLE ABSTRACTION WITH JAVASCRIPT .......................................................... 154
ENOUGH ALREADY! ........................................................................................... 158

JAVASCRIPT FOR BEGINNERS: IF, THEN & ELSE ........................................ 160

PROGRAMMING YOUR LIFE WITH IF-THEN DECISIONS ............................................ 160


JAVASCRIPT SYNTAX FOR IF-THEN DECISIONS ...................................................... 161
TRUE AND FALSE WITH JAVASCRIPT LOGIC .......................................................... 162
JAVASCRIPT IF EXAMPLE ................................................................................... 163
GET TO KNOW SOME MORE COMPARISON OPERATORS ............................................ 165
SAFETY NETS WITH IF THEN ELSE ...................................................................... 168
NO, I DIDN'T FORGET THAT QUESTION ................................................................. 169
TESTING FOR INEQUALITY .................................................................................. 170
CLOSING OUT WITH IF THEN ELSE ....................................................................... 171

JAVASCRIPT LOOPS: AN INTRODUCTION TO THE JAVASCRIPT FOR LOOP173

HOW LOOPS ARE USED IN PROGRAMMING ............................................................ 174


DIFFERENT KINDS OF PROGRAMMING LOOPS ........................................................ 178
HOW TO WRITE A FOR LOOP IN JAVASCRIPT ......................................................... 182
INFINITE LOOPS AND OTHER LOOPY PITFALLS ....................................................... 192
JAVASCRIPT FOR LOOP TERMINATION ................................................................ 195

PROBLEM SOLVING SKILLS: 5 STRATEGIES FOR ANY PROGRAMMER ...... 197

PROBLEM SOLVING SKILL 1: MAKE IT SMALLER .................................................... 197


PROBLEM SOLVING SKILL 2: THE 3 X 3 METHOD ................................................... 199
PROBLEM SOLVING SKILL 3: KNOW YOUR SOLUTIONS. ......................................... 200
PROBLEM SOLVING SKILL 4: BREAK TABOOS ........................................................ 201
PROBLEM SOLVING SKILL 5: KNOW YOUR PROBLEMS ........................................... 204
CONCLUSION ................................................................................................... 205
Copyright © 2017 Luke Fabish iv
INTRODUCTION TO JAVASCRIPT ARRAYS .................................................. 207

SO WHAT’S AN ARRAY? ...................................................................................... 207


GETTING ITEMS OUT OF AN ARRAY (AND PUTTING THEM IN TOO!) ............................ 211
MAKING A SIMPLE SLIDESHOW WITH JAVASCRIPT ................................................ 215
SUMMARY ........................................................................................................224

PRACTICE CHALLENGE #1 ............................................................................ 225

THE ABOUT PAGE – HTML AND CSS PRACTICE .................................................... 225

PRACTICE CHALLENGE #2 ...........................................................................229

CONST BOOKFINISHED = TRUE; // THE END. ................................................. 233

PS: WANT TO STAY IN TOUCH? ........................................................................... 233

APPENDIX A: HOW TO EDIT TEXT ON A MAC .............................................. 235

SO THIS IS WHAT I’LL COVER AS WE TALK ABOUT TEXT ON MAC OS X. .................... 238
AND WHAT DO YOU GET OUT OF THIS?................................................................. 238
TEXT EDITING ON MAC – TEXTEDIT ................................................................... 238
TEXTWRANGLER. THE SMALL, SIMPLE, TEXT EDITOR FOR MAC. ...........................242
VIM ON THE MAC – GET READY FOR AN ADVENTURE! ............................................ 245

APPENDIX B: BOOKS TO MAKE YOU A BETTER DEVELOPER .................... 250

TAKE CONTROL OF YOUR LEARNING .................................................................... 252


HOW TO GET THE MOST OUT OF A BOOK ............................................................... 253
BOOKS THAT’LL MAKE YOU A BETTER PROGRAMMER ............................................. 255

APPENDIX C – PRACTICE CHALLENGE ANSWERS ......................................262

PRACTICE CHALLENGE #1 ..................................................................................262


PRACTICE CHALLENGE #2................................................................................. 264

Copyright © 2017 Luke Fabish v


Hello, and Welcome

First of all, I want to thank and congratulate you for downloading The Absolute
Beginners Guide to Web Programming.

This e-book contains all the information you need to start creating dynamic web
pages using HTML, CSS and the programming language JavaScript (don't worry if
you don't know what those are – you will by the end of the book).

The e-book also includes practice exercises for you to put your new knowledge into
action.

And your new knowledge is going to be important because the World Wide Web is
quickly becoming the only communication channel that matters. The web is where
we consume news, share our lives and present ourselves to prospective employers
and clients.

This is your opportunity to learn how to take control of the web and make it do what
you want.

What this e-book will cover


After reading this e-book, you'll have learnt everything you need to know to build a
web page with a customised appearance and dynamic content.

Specifically, we'll go over HTML, which is used to define the structure of a web page.
Then we'll learn about CSS and how it's used to define the way a web page looks.

Finally, we'll go over the fundamentals of programming, by learning the basics of the
programming language JavaScript, which is used to add dynamic content (things you
can interact with) to a web page.

Copyright © 2017 Luke Fabish 1


We'll also go into detail on how to think like a programmer.

Who this e-book is for


But before going any further, we should make sure this e-book is for you.

First, this e-book is for beginners. And when I say beginners, I mean absolute
beginners.

It doesn't matter if you're taking your first steps to becoming a professional


developer, broadening your existing skillset or just learning web programming as a
hobby – this book takes nothing for granted. This includes where to find special keys
like '<' and '>' on your keyboard.

This is useful for those starting out, but it may be frustrating for readers with some
experience.

Secondly, we're going to stick to the fundamentals. That means that we won't learn
about the latest framework for CSS or JavaScript. The aim of the book is to give you
enough foundational knowledge to go out and start creating web pages, and then
apply that knowledge when learning more advanced topics.

Finally, this e-book is for people who are prepared to learn. Just reading the e-book
won't get you anywhere. Please do the exercises and answer questions included at the
end of each section. It's only by applying new knowledge that you'll get to own it.

Having said that, it's time to get started. We'll begin with the most fundamental
component of a web page: HTML.

Copyright © 2017 Luke Fabish 2


Copyright © 2017 Luke Fabish 3
HTML FOR ABSOLUTE
BEGINNERS

This is where we’ll be starting at the very beginning to explain how HTML works,
what it’s for and how you can start using it right now.

I hope you're excited because I can't wait to get started!

What we’re here for (is this for you?)


So, like I said, this is a guide for absolute beginners. If you already know what HTML
is, please jump straight to our explanation of HTML tags, or even to the HTML Tags
for Page Structure section.

If you’re here for the latest on HTML5, I’m afraid this is not the book for you – we’ll
be covering only the most fundamental (but crucial!) tags we need to get started
making HTML web pages (but watch this space – we’ll be producing an advanced
HTML guide in the near future!).

Otherwise, this is the section for you – you don’t know anything about HTML yet,
but you can’t wait to get started making your own web pages and building
up the knowledge you need to take control of your own awesome web site.

How we’ll proceed


So there’s a lot of detail in HTML and how the web works.

In this chapter we’re going to start at a very high level and work down to the level of
detail you need to start building web pages.

Copyright © 2017 Luke Fabish 4


If you’re worried because we’re not covering something you’ve heard about – don’t
worry! It’s something we’ll either get to in this e-book, or another e-book in this
series.

If I’ve left something out, it’s because that thing isn't necessary for you to get started.

What we’ll cover


As I mentioned already, we’re going to be looking at the fundamental HTML we need
to get started making web pages.

We’ll start with looking at what HTML is and how it works, to make sure you have
some context for the rest of the chapter.

After that, we’ll go into how we can use HTML to structure web pages, web page
content and the appearance of our content.

What we won’t cover


To keep the amount you have to take on at a sensible volume, we won’t be looking at
responsive or interactive features (like those included in HTML5) or forms.

We’ll get to those in later chapters.

Additionally, CSS and JavaScript have been kept back for later chapters as well.

What you’ll be able to do by the end of this chapter


Well, you wouldn’t want to show up, read a whole chapter and then not have
anything to show for it, right?

I’ll be including a few little tests and exercises (not compulsory, but highly
recommended!) to make sure that by the time you get to the end you can:

• Explain what HTML is


• Know what HTML is used for
• Build a simple web page.

Let’s get started!

Copyright © 2017 Luke Fabish 5


HTML Background
Let’s find out what HTML’s all about before we get into actually using it.

How it started

Waaaay back in 1989, a guy called Tim Berners-Lee came up with the idea of HTML
as a way of linking documents together across the Internet.

Yes, the Internet actually existed back then, but it was all text, and there was no
WWW.

As Berners-Lee published his ideas in the early 90’s, the Internet started to adopt
HTML more widely.

He showed off a prototype in ’92, then early web browsers like Mosaic and Netscape
implemented Berners-Lee’s ideas and the World Wide Web was born!

Since then, HTML has been moving through different standardized versions – we’re
up to version 5 now, written as HTML5.

Copyright © 2017 Luke Fabish 6


Figure 1: HTML documents linked together. The lines between documents could link files in different offices of a
building, or link documents on different continents.

What HTML means

HTML stands for HyperText Markup Language.

That’s hyper as in super – think hyper speed on Star Trek, or hyperactive after your
kids have too much sugar.

Markup Language is a way of adding extra information to plain text so that a


computer program knows what to do with it, like displaying a heading in large, bold
text.

HTML gives us a way of adding structure and


meaning to a document, so a computer program

Copyright © 2017 Luke Fabish 7


(like your browser) can take some text and change
its appearance, or add functionality to it.

What problem does HTML solve?

HTML was created to link together academic documents that were


spread all over the world.

Berners-Lee wanted to make life easier for academics to share information over the
internet. So he created a way of structuring information in a document and adding
hyperlinks to it to connect them across a network.

Hyperlinks (usually represented with an underline and a highlight colour) are what
we click in a web page to go to a new web page.

When we talk about the World Wide Web,


hyperlinks are the strands that link the web
together.

How HTML and the World Wide Web work

Since you’re going to start taking control of the web, we should find out what
happens when you load an HTML web page in your Internet browser (like Chrome,
Firefox, Safari or Internet Explorer).

Note: this is one of the sections where we gloss over a lot of detail to gain a quick
understanding!

First, we type the name of the web site we want in an Internet browser. Or, we might
click on a bookmark we saved earlier.

So, what happens then?

Copyright © 2017 Luke Fabish 8


Your Internet browser looks at the address (lukefabish.com, let’s say) and goes to the
server hosting that web page and says, in effect “Please may I have the front page for
lukefabish.com?”

(A server is a large, powerful computer whose job is to send data to other


computers).

So the server says “Sure, here it is” and sends the web page across the Internet to
your computer, and what it sends is HTML.

“Thanks,” says your browser, and interprets and displays the HTML page on your
screen so you see the web page you asked for.

Copyright © 2017 Luke Fabish 9


Key takeaways

We’ve covered a lot without even getting down to the nuts and bolts of HTML! But
the important things to remember are:

• This is for absolute beginners


• HTML defines the structure and appearance of a web page
• It was invented to link documents across the Internet

Copyright © 2017 Luke Fabish 10


HTML Tags
Tags are the building blocks of HTML, and they're used to enclose something to give
it some meaning.

What does that mean?

Let’s take a look at an example. We’ll invent a new tag called example. It’s not a part
of HTML, so don’t try to use it!

Here’s some text we want to treat as an example:

<example>This is text that’s had a fake mark-up tag called 'example'


applied to it.</example>

We’ve enclosed the above text with ‘example’ tags. Why would we do that? Maybe
because in a fictional version of HTML ‘example’ text should be formatted
differently.

The main point is, we’ve indicated to a browser that the text “This is text that’s had a
fake markup tag called 'example' applied to it” is an example.

Tag anatomy

We saw in the tag example above, that to enclose the text we used the tag name
twice:

<example>…</example>

There are a few things to notice here. We’ve used the tag name twice, which is normal
for all tags (except a couple we'll talk about later).

Each time we use the tag, it’s surrounded by what we call ‘angle brackets’, but are
actually the ‘greater-than’ and the ‘less-than’ symbols. Here they are on a standard,
English-language keyboard:

Copyright © 2017 Luke Fabish 11


Figure 2: Angle bracket and shift keys on an English language keyboard.

To type an angle bracket you’ll need to hold the ’shift’ key while you press the angle
bracket keys.

Finally, you’ll see that the second tag (or the closing tag, the first is the opening tag)
starts with a forward slash (it’s right next to your ‘shift’ key on the right-hand side of
the keyboard’).

<example>…</example>

This tells your browser that you’re finishing the tag.

Why do tags need these weird characters?

Yeah, why does HTML make us use these weird characters anyway?

It’s a good question, and the answer is that it’s for the benefit of the browser you use
for the Web.

The browser, of course, isn’t as smart as you are, and what this means is that when
we use an HTML tag like ‘head’ or ‘strong’, we show the browser it has a special
meaning by putting angle brackets around it.

Otherwise the browser would get confused when we wrote a document about
someone’s ‘strong’ arms or hard ‘head’. So we write it like this instead:
Copyright © 2017 Luke Fabish 12
<head>…</head>

<strong>…</strong>

This brings us to an important point.

HTML serves two masters

One of them is you, and the other is the browser.

Once again, when we talk about a browser, we’re talking about an application like
Chrome, Firefox, Safari, or Microsoft’s Internet Explorer and Edge applications.

HTML is a series of codes we use to give instructions to the browser, so it’s designed
to be interpreted by a machine.

But it uses normal English words or abbreviations, so it’s for you too.

Computers don’t need regular words, and it would be more efficient (from the
computer’s point of view) to use a string of 1’s and 0’s.

But we humans aren't very good at interpreting binary strings that look like this:
‘100010011’.

So HTML represents a middle ground.

But now that you're learning to be a web developer I encourage you to always think
of things from the point of view from the browser.

As we move further into learning actual HTML, imagine how a browser would
interpret the tags. This will help you when things don’t work the way you expect
them too!

Tag attributes

Finally, we need to talk about tag attributes.

An attribute is an extra piece of information we attach to a tag. Going back to our


example tag, we could add an attribute like this:

Copyright © 2017 Luke Fabish 13


<example ofwhat="html">…</example>

In this case, we’ve added an imaginary attribute called ‘ofwhat’ to the example tag.

We can’t just make up attributes for HTML tags, but I’ve used a pretend one in this
case to demonstrate:

The parts of an attribute: it has a name (‘ofwhat’), and a value (‘html’)

How it’s defined: name="value"

And that it adds extra information to a tag (the example is for HTML).

Copyright © 2017 Luke Fabish 14


Key takeaways

After all that, what we need to keep in mind about tags is:

• They’re the building blocks of HTML.


• They’re defined using angle brackets (<, >).
• There are usually two of them.
• The first is the opening tag, the second is the closing tag.
• The closing tag starts with a forward-slash (/).
• We can add extra information to them with attributes.

Copyright © 2017 Luke Fabish 15


HTML Tags for Page Structure
Finally we get to look at some HTML!

We’ve been saying all along that HTML is used to define a web page's structure, so
here it is:

Copyright © 2017 Luke Fabish 16


Figure 3: Structure of a web page, defined by HTML tags

You can see that it uses a series of tags I haven’t mentioned yet: html, head, title, and
body. Let’s look at them now to see how they’re used.

The !DOCTYPE tag

So sorry to do this to you, but the first tag to appear in an HTML file…isn’t even an
HTML tag!

<!DOCTYPE html>

No, it’s the !DOCTYPE tag, and it’s the first thing to appear in an HTML document.

It's a heads-up for the browser to tell it: "get ready for an HTML document!"

None of the rules I’ve laid out so far here apply to the !DOCTYPE tag – it doesn’t
have a closing tag, and it’s attribute isn’t defined in the name="value" style.

As I said, that’s because it’s not actually an HTML tag. But it does need to appear at
the start of an HTML file.

Let’s talk about a real HTML tag.

The <html> tag

And what could be more HTML-ish than an <html> tag?

The html tag defines an entire document, so the two html tags (opening and closing
tags) surround a document's contents.

The closing html tag is also a signal to the browser – the document’s finished now,
you can get on with rendering it (i.e. displaying the document's contents in your
browser window).

The <html> tag can have a few attributes, but there’s only one we really need to pay
attention to at this stage: the ‘lang’ attribute.

The ‘lang’ attribute tells our browser what the predominant language of the web page
is.
Copyright © 2017 Luke Fabish 17
This is an accessibility feature for people who use screen-readers to experience the
World Wide Web.

If our page is in English, our opening <html> tag would appear as follows:

<html lang="en">

You can find a list of HTML lang language definition codes here.

The <head> tag

The <head> tag is a place to put information about your document and to refer to
other resources the document uses.

It’s not usual to give the <head> tag an attribute, and it’ll be used only once in your
document.

As shown in Figure 3, it’s expected that the <head> tag will have at least one other
tag in it, the title tag.

We’ll talk about the <title> tag next.

The <title> tag

Take a look at the text in the tab at the top of this Google search for bunny rabbits:

Copyright © 2017 Luke Fabish 18


Figure 4: Example of the <title> tag's content appearing in a browser tag.

It says 'Bunny rabbits - Google Search' and it’s the job of the <title> tag to define that
text.

In this case, the title tag would look like this:

<title>Bunny rabbits – Google Search</title>

The <body> tag

The body tag is where you finally get to put your content – whatever appears in here
is what we’ll see in a browser when we look at your web page:

<body>

[The rest of your page content]

</body>

Once again, there aren’t any attributes we’d use for the <body> tag at this stage, it’s
just important to remember it encloses the entirety of the content that’ll appear in a
web page, and it’s only used once in an HTML document.

Copyright © 2017 Luke Fabish 19


Exercise using HTML page structure tags

Now that we’ve covered the basics of how a web page is structured, let’s do a little
exercise.

You know how I said earlier that when we request a web page, we get it from a server
– well the server can be your own computer!

So if you’re up for it, you’re going to make a little web page, save it to your computer,
and look at it in your browser.

Here’s how:

Open a simple text editor (not a word processor like Microsoft Word, or Apple
Pages):

On Windows: use the Notepad application (press your Windows key, and type
‘Notepad’, then press Enter).

On an Apple computer: you can use the ’TextEdit’ application (it’s in your
Applications folder). Before you type anything into TextEdit, you need to tell it to
use plain text – go to the Format menu and select Make Plain Text.

For once life seems much simpler on a Windows computer!

See Appendix A to learn more about editing text on an Apple Mac computer.

Now that you've got your text editor open, enter the following into a new file:

<!DOCTYPE html>
<html lang=“en-US”>
<head>
<title>This is my web page exercise</title>
</head>
<body>
Hello, and welcome to my web page.
</body>
</html>

(That’s not quite valid HTML, but we’ll fix that in the next section).

Copyright © 2017 Luke Fabish 20


Save the file as ‘example.html’ (make sure you use that ‘.html’ extension on the end
of the file).

Now, in your browser, open the file by pressing ctrl-O (on Windows) or command-O
(on Mac), navigate to where you saved your text file, open it, and you should see the
following:

Figure 5: Example of a super-simple web page.

Copyright © 2017 Luke Fabish 21


Key takeaways
• We’ve seen that we can use the !DOCTYPE, html, head, title and body tags to
define the structure, as well as some fundamental information about a web
page, like its title and what language it uses.
• We can also create a web page on our computer and view it in our browser

In the next section we’ll start putting some proper content into our web page.

HTML Tags for Content Structure


Now we get to work on some actual content for our web page.

We’ve looked at the fundamental outline of a HTML document – the <html>,


<head> and <body> tags.

Now we’ll look at the tags we can use inside the <body> section to structure our web
page content.

HTML tags that assign meaning and structure to content

The tags we’re about to look at tell our browser how we want content to be structured
and laid out.

(We don’t have much control over the finer points of appearance in HTML – that’s
CSS’s job. We’ll look at how HTML can change the appearance of content in the next
section.)

<p>

That’s P for Paragraph. We use the <p> tag to house written content.

A browser will put a small amount of space between <p> tags to give some definition
to our paragraphs, like when you press Return or Enter in a word processor program.

When you made your example web page and displayed it in your browser, I told you
the HTML wasn’t quite valid.

Copyright © 2017 Luke Fabish 22


That’s because content like text should always appear in another tag, not just on its
own in the <body>. Otherwise, the browser doesn’t know how to display it.

(Notice the browser displayed it anyway – browsers are very tolerant of poor HTML)

It could appear in an HTML document like this:

<body>
<p>
Even though this is example text, notice how we’re using
indentation here.
Which is to say that the p tag is a couple of spaces in from the
body tag,
and this text is a couple spaces in from the p tag.
</p>

<p>
We use indentation in this way to make the document easier to
read for humans.
The browser doesn’t care about indentation at all.
</p>
</body>

Note – since we’re only dealing with tags that appear inside the <body> tag, for
clarity I won’t include the <html>, <head> and <title> tags in examples.

<div>

Short for division, as in section or area, not the mathematical division!

It’s really just a section of a web page to hold some other content. We use the <div>
tag to break up sections of a document, and as containers for different kinds of
content.

We could use it like this:

<body>
<div>
<p>This content has no point to make.</p>
<p>Nor does this.</p>
</div>
</body>

That may not seem very useful to you, until we talk about the <span> tag, and how it
and <div> differ.

Copyright © 2017 Luke Fabish 23


<span>

A <span> is also another holder of content. For example:

<body>
<span>
Text doesn’t have to appear inside a p tag!
</span>
</body>

So why have two tags, <div> and <span>, for holding content?

Because one of them is classed as being a ‘block’ tag, and the other as ‘inline’. We'll
talk about that next:

A brief interlude – Inline vs. Block

So all tags that appear within the <body> of an HTML document can be classed as
either inline or block.

What does that mean?

It means that when displayed one after the other, block tags stack up on top of each
other.

Inline tags are displayed next to each other (hence ‘in-line’).

Copyright © 2017 Luke Fabish 24


Figure 6: An illustration of the difference between block and inline HTML tags.

Additionally, inline tags can only contain other inline tags, but block tags can
contain block and inline tags.

Copyright © 2017 Luke Fabish 25


Figure 7: Illustration of nesting block and inline HTML tags.

Now, if you do put block tags inside inline tags, the browser police won’t show up at
your door.

What will happen though, is that you can’t predict how a browser will display it.
They’ll all guess, but they guess differently and unreliably!
Copyright © 2017 Luke Fabish 26
From now on, I’ll indicate whether a tag is block or inline, and you’ll know what I
mean.

<a>

The <a> tag is inline, and is used to put a link in a web page. Once upon a time the ‘a’
stood for ‘anchor’ – a way of marking (or anchoring) a place in a document.

As of HTML5, it’s only used for defining links to a web page.

Sometimes, the changing nature of HTML standards leads to tags having a name that
doesn’t make much sense!

Until now, we haven’t really discussed attributes for our HTML tags. The <a> tag
isn’t much use unless we use the ‘href’ attribute. ‘href’ stands for ‘hypertext reference’
and is the address we want our link to take us if we click it.

For example this HTML:

<body>
<div>
<a href="http://www.google.com">Do a google search.</a>
</div>
</body>

Would appear as follows:

Figure 8: Example of the <a> tag in action.

Notice the text between the opening and closing tags: it's the text we click to go to
the linked page.

Copyright © 2017 Luke Fabish 27


Also notice that the link href includes the protocol http:// as well as the web page
www.google.com.

The link would probably still work if we left off the protocol portion of it, but it’s best
not to let the browser guess our intentions. If we’re more specific, our results will be
more certain.

(And what’s a protocol? It’s an agreed method of exchanging information. By having


an agreed protocol in place, computers all over the world can exchange information
in a predictable way.)

<h1>, <h2>, <h3>, <h4>, <h5> & <h6>

What’s with all the h’s? These tags represent different levels of headings in a web
page, and they’re all block tags.

When you make a web page, you probably want a big bold title at the top – that’d be
<h1>. Each section would start with an <h2>, and sub-headings would have <h3>
and so-on.

For example:

<body>
<h1>Why Dogs Are Better Than Cats</h1>

<div>Introductory text making the dogs v cats case</div>


<h2>The Smell Factor</h2>
<div>I just like the way dogs smell, etc</div>

<h2>Cat food is gross</h2>


<div>It smells funny, and so on</div>

<h3>The cat food caveat</h3>


<div>Unless it's dried food, but the vet says...</div>

<h2>Conclusion</h2>
<div>Argument summation...</div>

</body>

Copyright © 2017 Luke Fabish 28


Figure 9: Demonstration of different 'h' tags. For the record, I love both dogs AND cats. Got any spare??

<img>

Finally, a tag with a name that makes sense!

The <img> tag is used to display images. It’s officially an inline element, but it’s also
a little blocky.

I’ll explain why in a moment, but I also have to point out something else odd about it
– the <img> tag doesn’t have opening and closing tags. It only appears once per
image. If that sounds weird, check out the examples below!

The <img> tag has two ‘required’ attributes. One is src, which tells the browser
where to find the image to be displayed. The other is alt, meaning ‘alternative text’.

Copyright © 2017 Luke Fabish 29


This is the text to display if the browser, for some reason, can’t display the image.
Most browsers will still display an image if it doesn’t have a value for alt, but it's
always better to use it.

So here’s our example:

<body>
<img

src=https://upload.wikimedia.org/wikipedia/commons/2/2e/Margaret_Ham
ilton.gif
alt="The amazing Margaret Hamilton with her Apollo code
printout." />
</body>

Note the single appearance of ‘img’ – it ends like this: “/>” and has a lot of attribute
information. Here’s how it will appear in our browser:

Copyright © 2017 Luke Fabish 30


Figure 10: Example of the img tag in use. Note the image seems to be quite big!

(No, that’s not Amy from the Big Bang Theory, it’s Margaret Hamilton, responsible
for the on-board flight software for the Apollo space program at NASA. She’s
awesome.)

Now, I said earlier in this section that the inline <img> is also a little blocky. That’s
because it supports two attributes normally only associated with block elements:
height and width.

I think it’s great that we can change the height and width of an image on a web page,
but it begs the question – how do we measure height and width on a screen?

Copyright © 2017 Luke Fabish 31


"Lots of ways" is the answer, but we’ll stick to two that’ll get you the furthest fastest:
percentage, and pixels.

First, let’s look at percentage. If we wanted to show the above image at a tenth of its
original size, we’d set width and height to 10%, like this:

<body>

<img

src=https://upload.wikimedia.org/wikipedia/commons/2/2e/Margaret_Ham
ilton.gif
alt="The amazing Margaret Hamilton with her Apollo code
printout."
width="10%" height="10%"/>

</body>

And here’s how it looks:

Figure 11: Width and Height applied to the img tag.

And now pixels – funny name, let’s find out what they are.

A pixel is the smallest space on your computer screen that can be lit up. You can
imagine your screen as a tightly packed grid of teeny tiny light bulbs that can be lit in
different colours.

When we light them up in the right pattern, we get a picture on the screen.
Copyright © 2017 Luke Fabish 32
So a pixel is like a tiny light bulb, and it takes up space on your screen. We can then
measure anything on a web page (not just images) in pixels.

The original photo of Margaret Hamilton is 2294 pixels wide and 2896 pixels tall. We
can specify the original dimension like this (‘px’ is short for ‘pixels’):

<body>
<img

src=https://upload.wikimedia.org/wikipedia/commons/2/2e/Margaret_Ham
ilton.gif
alt="The amazing Margaret Hamilton with her Apollo code
printout."
width="2294px" height="2896px"/>

</body>

And if we changed the width attribute to 100px (100 pixels) and the height to 500px
(500 pixels):

<body>
<img

src="https://upload.wikimedia.org/wikipedia/commons/2/2e/Margaret_Ha
milton.gif"
alt="The amazing Margaret Hamilton with her Apollo code
printout."
width="100px" height="500px"/>
</body>

We’d get this:

Copyright © 2017 Luke Fabish 33


Figure 12: An img tag with mis-matching height and width attributes

Uh, she looks kind of squashy, doesn’t she?

That’s because we kept the image height the same, but narrowed the width. If for
some reason, we insist the image be 300px wide but scale (to ‘scale’ an image is to
alter its size) without distortion, we can just put in the width dimension and set the
height to 'auto'. The browser will work out the correct height for us – isn’t that nice?

<body>
<img

Copyright © 2017 Luke Fabish 34


src="https://upload.wikimedia.org/wikipedia/commons/2/2e/Margaret_Ha
milton.gif"
alt="The amazing Margaret Hamilton with her Apollo code
printout."
width="300px" height="auto" />
</body>

Figure 13: An img tag using heigth="auto"

<ul>, <ol>, <li>

These tags are all about lists, and we use them to make either a bullet-point list, or a
numbered list. We’ll check out some examples below.

<ol> is short for ‘ordered list’, meaning a numbered list.

We use the <ol> opening and closing tags to contain an entire list, and the <li> (list
item) tag to define individual items in the list, like this:
Copyright © 2017 Luke Fabish 35
<body>
<p>My shopping list (I always buy things in the correct
order):</p>
<ol>
<li>Eggs</li>
<li>Milk</li>
<li>Dog food</li>
</ol>
</body>

Figure 14: Example of an ordered list using the <ol> and <li> tags.

Note that we’re using opening a closing tags for <li>. You’ll see lots of examples
where only the opening tag is used. As usual, if you do that the browser will
understand your intention well-enough and give you a nice list, but there’s no
guarantee it’ll work in the future. So close your <li> tags!

<ul> is short for ‘unordered list’, which is a fancy way of saying a list with bullet
points instead of numbers, and we use it in the same way as <ol>

<body>
<p>My shopping list (I buy stuff any old how): </p>
<ul>
<li>Eggs</li>
<li>Milk</li>
<li>Dog food</li>
</ul>
</body>

Copyright © 2017 Luke Fabish 36


Figure 15: An unordered list using the <ul> and <li> tags.

Finally, <ul>, <ol> and <li> are all block tags.

Practice using HTML content structure tags

Wow, there’s a lot of information in this section. I think it’s time to put what you’ve
learnt to use!

Open the same file (example.html) you used last time in your text editor.

Delete “Hello, and welcome to my web page.” from it.

Add the following:

• An <h1> title: “3 Reasons Why I Am Swooping on HTML Like An Eagle Upon


Its Prey”
• The following image:
https://upload.wikimedia.org/wikipedia/commons/thumb/2/2e/WB_Sea_E
agle_Pounce.jpg/640px-WB_Sea_Eagle_Pounce.jpg (don’t worry about
setting width or height unless you really want to)
• A numbered list with the following list items: “It didn’t see me coming”,
“HTML is delicious”, “Enclosed in my talon-like mind, HTML shall not
escape”
• An <h2> title: “HTML Reflections”
• A paragraph, enclosed by opening and closing <p> tags that briefly describes
your experience of learning HTML so far.
Copyright © 2017 Luke Fabish 37
• And put all of the above inside a <div>, using opening and closing tags.
• Save your example.html file.
• Open it in your browser (remember, ctrl-O on Windows, command-O on Mac)

Figure 16: Sample HTML exercise output (Creative Commons Eagle image By Mdk572 [CC BY-SA 3.0, via
Wikimedia Commons])

Key takeaways

Your talon-like mind not-withstanding, I know this is an awful lot of information. I


think the key things to remember are that HTML gives us tags to:

• Define titles and headings


• Enclose text in paragraphs
• Create lists

Copyright © 2017 Luke Fabish 38


• Display images
• And group content together as a block, or inline.

If you forget which does what, you can always come back to this section to check
again.

HTML Tags for Style and Appearance


All the tags we’ve discussed previously have added meaning to the content they
enclose – they tell the browser they represent a certain kind of content – titles,
images, text etc., or how that content should be arranged on a web page.

The following tags are mostly for changing the appearance of text in the browser.
Let’s take a look at them now.

<em>

<em> is used to add emphasis. That emphasis almost always translates into italic
text.

<em> is an inline style tag, because we may want to have several sections of italic
text in a paragraph, and not have them stacking up on top of each other.

An example:

<body>
<p>
Allow me to <em> emphasize my point.</em>
</p>
</body>

Figure 17: Example use of the <em> tag.

Copyright © 2017 Luke Fabish 39


Not much to it, hey?

<strong>

Like <em>, <strong> is an inline tag. In this case, it will make text appear in bold.

A quick example:

<body>
<p>
This time, I shall make my point with <strong>strength</strong>.
</p>
</body>

Figure 18: Example use of the <strong> tag.

Exercise using HTML tags for style and appearance

Well that didn’t take long did it? Let’s test out our new tags in your example.html file.

So open example.html in your text editor and:

• Use <em> to add emphasis to the phrases “Swooping on HTML Like An Eagle
Upon Its Prey”, “It didn’t see me coming”, “talon-like mind”.
• Use <strong> to strengthen “delicious”
• Save your example.html
• Open it in your browser (remember, ctrl-O on Windows, command-O on Mac)


Copyright © 2017 Luke Fabish 40
Key takeaways

Once again, even if you don’t remember the details, I think our main points this time
around are:

• We can emphasize text, usually with italics, by using <em>.


• We can strengthen text with bold-face by using <strong>.

Copyright © 2017 Luke Fabish 41


HTML Recap, and next steps
Now we truly have covered an awful lot of information, but it’s a decent grounding in
HTML fundamentals.

It’s telling how much of fundamental HTML is devoted to structure and meaning,
compared to styling. I think that tells us very clearly what the priorities of HTML are:
adding semantic meaning to web page content.

Text styling? Not so much.

If you’d like to know more about changing the appearance of a web page, rejoice!
That's what the next chapter covers.

Ok, what have we covered so far?


• What HTML is.
• How HTML works.
• Why HTML was invented.
• What a tag is.
• HTML tags for page structure.
• HTML tags for content structure.
• HTML tags for text styling.

In addition to that, you’ve also learnt:

• How to create an HTML page in a text editor.


• And how to display a text HTML file in your browser.

Finally, you’ve combined all of the above to build a simple, but correct web page by
hand.

Let’s meet again for more HTML


I mentioned the next chapter will teach you about applying styling to web pages: this
is where we'll start using CSS.

Copyright © 2017 Luke Fabish 42


In later chapters we’ll cover in-depth information on HTML that will build on the
information covered in this chapter.

Copyright © 2017 Luke Fabish 43


Copyright © 2017 Luke Fabish 44
CSS FOR ABSOLUTE
BEGINNERS

Want to know how to make a web page look good?

This is where you find out.

Previously, we covered HTML for beginners pretty thoroughly and learned that
HTML is used to provide meaning and structure to a web page.

That’s great, but the web page we produced looks like it was made in 1995, and it’s
time we fixed that.

So today in our CSS for beginners' chapter we’re going learn how to use CSS to
change the appearance of a web page.

Let’s get started!

Who is this CSS Guide is for?


As with our mega HTML guide for beginners, we’ll start from the very beginning and
take nothing for granted. So I’m assuming you have zero, or next to zero knowledge
of CSS.

I do assume you know some HTML now – if you don’t, once you’ve checked out our
HTML chapter you’ll be more than ready to get started on CSS.

CSS in one chapter? You’re crazy!


Yeah, that’s a big call, right?

Copyright © 2017 Luke Fabish 45


CSS is big, I mean really big. I count something like 180 different properties we can
use in CSS.

But you’ll only need a tiny fraction of those most of the time.

So we’ll be concentrating on the small part of CSS that’ll give you the most bang for
your web buck.

What we’ll cover in this chapter


Having said that, I’d better be pretty clear about what you’re going to get if you read
this chapter.

We’ll cover:

• How to apply CSS to a web page.


• How CSS selectors work.
• The CSS we can use to change the appearance of text, change foreground and
background colors; and,
• How we can use CSS for a simple page layout.

I know there’s some jargon in that list you might not be familiar with yet, but you
will be by the end of the chapter!

What you’ll be able to do by the end of this chapter


So, if you put in the effort to work though this chapter and do the exercises you’ll be
able to:

• Change the font, size, style and colour of text in a web page.
• Change the background colour in a web page.
• Control the fundamental layout of a web page
• Accurately and selectively apply CSS styles to distinct parts of a web page.

In short – turn a drab piece of HTML into a nicely styled web page.

So, what is CSS anyway?

Copyright © 2017 Luke Fabish 46


I’ve been talking about CSS all this time without being very specific about what it is,
and it’s time to fix that.

There are three main technologies used to make web pages – HTML, CSS and
JavaScript.

As I mentioned in the introduction, HTML is for defining the meaning and structure
a web page’s different parts. This is referred to as a web page’s semantics.

JavaScript adds interactivity to a web page – you do something, and the JavaScript
does something back!

And finally, CSS is used to change the appearance of a web page. We can use CSS to
selectively apply rules to how a browser should render different parts of a web page.

Once again, it’ll be tremendously helpful for you to


consider things from the browser’s perspective.

You’ll see that, similar to HTML, CSS is a system of


encoding that serves both humans and computer
programs.

You should always try to consider how a browser


will interpret your CSS – it’ll make your CSS
better!

Now I’ve typed ‘CSS’ a bunch of times already, but haven’t said what it actually
stands for – we’ll it’s Cascading Style Sheets.

Helpful, right? Now you can see why I took so long to get around to spelling it out –
because it doesn’t really tell us very much.

First, what are style sheets?

Once upon a time they were a list of rules that typographers used to ensure a
consistent look and feel for newspapers, magazines and other printed matter.
Copyright © 2017 Luke Fabish 47
One typographer or designer could hand a style sheet to someone else, and they’d
produce work that’d fit right in with the rest of the publication.

So, the modern cascading style sheets for HTML are used to apply styles consistently
on a web page.

You give the style sheet to the web browser, and then the browser knows how the
page should look.

We’ll get to the ‘cascading’ bit later in this chapter.

Key takeaways:

• CSS stands for ‘Cascading Style Sheets’


• Style sheets are used to define a consistent look and feel.
• CSS is used to define the ‘look’ of a web page.

How does CSS work?


There are two important parts of CSS:

What we want to style, and

How we want to style it.

When put these two together, they comprise a CSS style rule. A browser will apply
CSS rules to change the appearance of a web page.

These are the components of a CSS rule:

selector {
property: value;
}

And an actual CSS rule may look like this:

p {
font-size: 14pt;
}

Let’s take a look at CSS selectors, properties, and values.

Copyright © 2017 Luke Fabish 48


CSS Selectors

I said previously CSS has two parts: what to style, and how to style it.

CSS selectors are the what part of the equation.

Above, I described a CSS rule like this:

selector {
property: value;
}

The selector is used to identify part of an HTML web page, and there are three ways
to do that.

The first and simplest, is to name an HTML tag:

p {
property: value;
}

You remember the <p> for paragraph tag, right?

The CSS rule above would apply to all <p> tags in the web page. If we wanted to
apply it to all <div> tags, we’d have written this instead:

div {
property: value;
}

But what if we didn’t want our style to apply to all <p> tags, just some of them?

Then we’d use our second type of CSS selector: a ‘class’.

A class is an attribute that can be applied to any HTML element. We’d use it like this:

<p class="diary-date">...</p>

Our CSS could then look like this:

.diary-date {
font-style: italic;
}

Copyright © 2017 Luke Fabish 49


Note the ‘.’ at the beginning of ‘diary-date’. We use that so the browser knows we’re
talking about a class, and not some weird HTML tag called ‘diary-date’ that the
browsers never heard of!

Now, any tag with a class of ‘diary-date’ will have the style ‘font-style: italic;’ applied
to it. I’m sure you can guess what that does!

Our last kind of selector is for ‘id’ type selectors. This is another attribute we can
apply to any HTML tag:

<div id="main-content">...</div>

But how is ‘id’ different to ‘class’?

While we can use a class in a web page as often as we like (e.g. we could have lots of
‘diary-date’ tags on a page), an ‘id’ should appear only once on a web page.

A CSS rule for our ‘main-content’ div might look like this:

#main-content {
background-color: FloralWhite;
}

This time we used a ‘#’ in front of our selector.

That tells the browser it should look for an HTML tag with an id of ‘main-content’,
and make its background color ‘FloralWhite’ (Oh yes, ‘FloralWhite’ is a color! See
here for a full list of pre-defined colors we can use in CSS).

Key takeaways

• CSS is comprised of Selectors, Properties and Values


• CSS Selectors can identify a tag in a web page by: tag type, a tag’s class, or a
tag’s id.

Ok, so it’s time for us to get our hands dirty and start writing some HTML and CSS.
We’ll do that in the next section.

Copyright © 2017 Luke Fabish 50


CSS Properties and Values
Before we go any further, we have a little exercise:

Open a plain text file (remember, see Appendix A if you need some help with that)
and save the following as diary.html

<!DOCTYPE html>
<html lang="en">
<head>
<title>Dear Diary</title>
</head>
<body>
<h1>Dear Diary</h1>
<p>September 1st</p>
<p>Oh diary, you won't believe what happened to me today...</p>
</body>
</html>

So how does this look at the moment? Try opening it in your browser it’s pretty plain:

Figure 19: HTML with no CSS.

So let’s explore CSS style properties and values with some examples.

First, add this inside the <head> tags, after the <title> tag (the style tags tell the
browser to get ready for some CSS rules):

<style type="text/css">

Copyright © 2017 Luke Fabish 51


h1 {
font-size: 48pt;
}

</style>

Not too sure about the characters; : { and }?

Fans of punctuation will know; and : but the rest of us can find them below. You’ll
need the shift key for the colon:

Figure 20: Where to find colon (:) and semi-colon (;) on a keyboard.

The ‘curly braces’ { and } are rarely used outside math and programming. We can
find them here, and you’ll need to hold down the shift key while you type them:

Copyright © 2017 Luke Fabish 52


Figure 21: Where to find the curly braces { and } on a keyboard.

Now, once you’ve typed in the style, re-load the page in your browser.

Ok, so that’s not much more exciting, but we’ll use it to explore CSS properties and
values.

Let’s take another look at our CSS style rule:

h1 {
font-size: 48pt;
Copyright © 2017 Luke Fabish 53
}

So we already know that the selector ‘h1’ means that the rule will be applied to
(“selects”) all <h1> tags in the document.

Our curly braces – { and } – group together all the CSS properties and values that
will be applied to the selector (h1 in this case).

What about the property and value? Let’s take another look at how we formulate a
style:

property: value;

‘Property’ is the name of an attribute that affects how things look on a web page, the
font size in this case.

‘Value’ alters the property to do what we want it to!

In this case, the value of our style rule looks like this:

font-size: 48pt;

So we want to the font size to be ‘48pt’. I’ll explain the ‘pt’ in a moment, but first note
the use of ‘:’ and ‘;’.

We use the colon ‘:’ character to end the name of the CSS property – that tells the
browser that the name of the property has finished, and the browser can check if it
knows that property or not.

The semi-colon character (;) is used to tell the browser that we’ve finished the value
part of the CSS style. That means the browser can get on with applying the value to
the property.

Copyright © 2017 Luke Fabish 54


Key takeaways:

• Style properties for a selector are grouped together with { and }


• Property names end with a colon, ‘:’
• Property values end with a semi-colon, ‘;’

I think it’s time to dig into the nitty-gritty of some CSS style properties, and we’ll
begin with our font-size property.

Copyright © 2017 Luke Fabish 55


CSS font-size
As you saw earlier, we set the font size of our <h1> tag to 48pt:

font-size: 48pt;

What’s a ‘pt’?

Once upon a time, your word processor (like Microsoft Word) would have given you
a list of font sizes with ‘pt’ next to them. They don’t any more, they just look like this:

Figure 22: Font sizes in MS Word - we don't get a 'pt' any more!

The pt stands for ‘point’, and is a way of measuring the size of text. Many of the
conventions used in CSS hark back to the days when type was set with moveable
type, like this:

Copyright © 2017 Luke Fabish 56


Figure 23:By Daniel Ullrich, CC BY-SA 3.0

These chunks of metal were measured in ‘points’. A font can also be measured by
‘em’ (the width of a capital ‘M’) or pixels.

Sound confusing? Don’t worry, stick with ‘pt’ for now since it corresponds nicely to
word processors.

Copyright © 2017 Luke Fabish 57


Key takeaways:

• The font-size property is used to set a font’s size (surprise!)


• There are many ways to measure a font’s size: point, ems, pixels.
• Pick one and stick to it; I recommend point (pt) to start with.

Copyright © 2017 Luke Fabish 58


CSS font-family
So now that we can change the size of a font, how about changing the actual font
itself? That’s where font-family comes in, and we’ll use it like this:

h1 {
font-size: 48pt;
font-family: 'Myriad Pro', Helvetica, Arial, sans-serif;
}

Update your h1 CSS rule in diary.html to include the font-family as above, and reload
it in your browser. You should get something like this:

Figure 24: Example of font-family rule with CSS.

This property looks quite different to our first example, so let’s take a closer look:

font-family: 'Myriad Pro', Helvetica, Arial, sans-serif;

As name of this property, ‘font-family’ might hint, this property takes a series of
values, separated by commas (,). Why is that?

You may know some of these fonts (Helvetica, Arial etc) from your word processor:

Copyright © 2017 Luke Fabish 59


Figure 25: Examples of fonts in a word processor.

But why do we provide a list? That’s because not all computers have the fonts we
want on them. For example, your computer may not have the ‘Myriad Pro’ font
installed on it.

If it doesn’t, the browser will go to the next font in the list, ‘Helvetica’, and see if it
has that.

It’ll continue going through your font-family list until it finds one it recognises, or it
gets to a default like ‘serif’, or ‘sans-serif’.

‘serif’ is your computer’s default font with ‘serifs’ (highlighted in red):

Figure 26: Serifs example

‘Sans-serif’ (literally ‘without-serif’) is your computer’s default font without serifs:

Copyright © 2017 Luke Fabish 60


Figure 27: Sans-serif example

This business of serif and sans serif fonts is another pointer to CSS’s typographic
origins.

So, when we set our font-family value, we’re giving the browser a list of our preferred
fonts, from most preferred through to least preferred.

Finally, why does Myriad Pro have single-quotes around it?

font-family: 'Myriad Pro', Helvetica, Arial, sans-serif;

That’s because the font name has two words, ‘Myriad’ and ‘Pro’. We put quotes
around the whole thing – ‘Myriad Pro’ – so that the browser doesn’t think we want a
font called ‘Myriad’.

The browser really needs our help at times!

This goes for any font name, or any other value that’s more than one word: we’ll
need to surround it in quotes for the browser to recognise it properly. Single quotes
are best.

Wondering which fonts you can use, and what their names are? There’s a list of web-
safe fonts right here.

Copyright © 2017 Luke Fabish 61


Key Takeaways:

• The font-family property changes the type of font the browser will use.
• We give the font-family a list of fonts, in order of our preference.
• The list of fonts should end with either ‘serif’ or ‘sans-serif’, which are default
fonts used by the browser.
• Fonts with more than one word in their name, e.g. ‘Myriad Pro’ or ‘Times New
Roman’ should be surrounded by single quotes.

Now that we’ve looked at changing font size and type, let’s see what else we can do
with our fonts.

Copyright © 2017 Luke Fabish 62


CSS font-style
The font-style property is reassuringly simple after all that font-family business.

It only has three possible values: normal, italic, and oblique.

And there’s often no difference between italic and oblique! Some fonts have an
oblique version that’s a little darker and heavier than the italic version, but plenty
don’t.

Let’s try it out. After the h1 rule in diary.html, make a new CSS rule, starting on a
new line:

.diary-date {
font-style: italic;
}

Note the ‘.’ Preceding the selector. As I mentioned earlier, this means we’re looking
for a class called ‘diary-date’.

So let’s add one! Update the first <p> tag in diary.html to appear as follows:

<p class="diary-date">September 1st</p>

Reload diary.html in your browser. You should see something like:

Copyright © 2017 Luke Fabish 63


Figure 28: Example of the font-style CSS property.

You may be thinking at this point – why do we need this rule to make some text
italic? We have the <em> tag for that.

Well, there are a couple reasons. Firstly, the browser is free to interpret the <em> tag
as it wishes, and by convention they’ll use italics for emphasis. But there’s no
guarantee they always will.

Second, imagine we used the <em> tag to surround all our dates, like so:

<p><em>September 1st</em></p>

What if we changed our mind? If we had 20 dates on the page, we’d have 20 changes
to make.

But – if all our date paragraphs have a “diary-date” class, we can change them all at
once by editing the rule for diary-date. Ok, that’s pretty cool!

CSS Margin (Introducing the Box Model)


We’ve been talking about CSS styles so far as if we’re just applying them to lumps of
text. But that’s not what we’re doing!

Copyright © 2017 Luke Fabish 64


CSS considers all HTML elements to be rectangular boxes.

(An element is part of an HTML web page represented by an HTML tag. I’ll be
referring to elements a lot from now on. Don’t worry, remember they’re just tags
like <p>, <h1> and <div> that have graduated from a text file to a browser web
page).

So, CSS sees everything on a web page as a box. And all these boxes have three
properties: padding, border and margin:

These are the properties we can use to separate one thing on an HTML page from the
other, either with a line (the border), or with blank (aka ‘white’) space represented by
the padding and margin.

In an effort to be helpful, most browsers have default values for these, to stop things
bunching up against each other.

For example, if we remove all the borders, padding etc from our sample diary.html,
it’d look like this:

Copyright © 2017 Luke Fabish 65


Figure 29: CSS example with no margins, padding or border.

It’s readable, but not very nice.

Let’s use the margin property to our advantage. Here’s our box model again, this
time with some values in there for padding, border and margin:

So while it’s most intuitive to use numbers with margins, we can let the browser help
us instead, and put our content in the middle of the page.

Copyright © 2017 Luke Fabish 66


First, please wrap up everything in diary.html inside a brand new <div>, like this:

<div>
<h1>Dear Diary</h1>
<p class="diary-date">September 1st</p>
<p>Oh diary, you won't believe what happened to me today...</p>
</div>

Now we’ve put everything we had so far into a brand new box. And let’s give that box
an id:

<div id="main-content">
<h1>Dear Diary</h1>
<p class="diary-date">September 1st</p>
<p>Oh diary, you won't believe what happened to me today...</p>
</div>

You can re-display that in your browser if you like, but it won’t look any different – that new
<div> is just an invisible box right now.

But let’s add a new CSS rule. Put it under the .diary-date rule in your <style> section:

#main-content {
margin-left: auto;
margin-right: auto;
width: 600px;
}

Left? Right? Auto? What?

Let’s look at left & right first. Since it’s a box we’re dealing with, it has four sides: top,
right, bottom and left. If we’d just used

margin: auto;

Then our new rule would automatically apply to all four sides, but we just want it to
be applied to left and right. There are further ‘shorthand’ techniques we can use, but
we won’t bother with them yet.

And auto? Auto means: “Hey browser, please just set the margin to the available
remaining space.”

When we give our rule a width (600px) and left and right margins set to auto, our
content jumps into the middle of the page:

Copyright © 2017 Luke Fabish 67


So the browser says to itself (as it were), “Ok, I’ve got this 600 pixel-wide div here,
and I need to make the left and right margins equal to the remaining space. Hmm,
my screen’s 1200 pixels wide, that means I should put 300 pixels space on the left,
and 300 pixels space on the right. Done!”

So with equal amounts of space on the left and right, our content moves to the
middle.

Let’s talk about these Cascading Style Sheets

So I said I’d get to the cascading bit later, and here we are.

Once again, let’s demonstrate this with an example. Please add a new rule to your
CSS styles in diary.html, this time at the top, just above your h1 rule:

body {
font-family: Georgia, Palatino, serif;
font-size: 18pt;
}

Copyright © 2017 Luke Fabish 68


We’re applying a rule to the <body> tag! The <body> tag encloses everything in our
document. Hmmm.

We’re familiar with font-size already, and font-family too, except this time we’re
using Serif style fonts.

Let’s see what effect that has:

Figure 30: CSS cascading styles in effect.

So what happened there? We changed the font styles in the <body> tag, and it
affected everything except the <h1> tag.

This is because we can look at a web page like a hierarchy. Changes we make to the
top of the hierarchy cascade down to the bottom of the hierarchy. Let’s take a look at
that:

Copyright © 2017 Luke Fabish 69


Ok, since <html> contains everything else, it’s at the top. Then on the left is our
<head>, and right is the <body>, which we’ve assigned a new style to.

Then comes our “main-content” <div>, which then contains all our other elements.

So the change to the font styles <body> flowed down to nearly everything else.

Why did <h1> miss out? Because it has it’s own font styles. And this is how CSS
works.

It’ll apply styling rules generally until it


encounters a more specific rule, and then that
more specific rule will be applied.

But wait! We have a specific rule for our ‘diary-date’, why did its font change too?

Copyright © 2017 Luke Fabish 70


Because the ‘diary-date’ rule only affects the font-style, not the font-family or font-
size. Because the h1 rule addresses font-family and font-size specifically, the change
at the body level doesn’t affect it.

So this is great, right?

If we want to change the font in the entire document, we only need to change it in
one place. And if there are some parts of the document we want to always have a
different font, we can give them a more specific rule.

This is one of the reasons the whole web industry went crazy about CSS.

I’ve only talked about a ‘web page’ so far.

CSS really comes into its own for web sites that may have hundreds of pages. If we
store our CSS separately to our web pages (we’ll do this later in this chapter) we can
make one change in our CSS and change the style of the entire site at once. That’s
powerful stuff.

Ok! Back to our CSS properties.

CSS text-align
We can use text-align to choose whether our text lines up on the left, right or centre
of our document.

Valid values for text align are left, right and center. Note the spelling of ‘center’ with
the ‘er’ at the end, not ‘re’.

I don’t know about you, but when I make a journal entry, I put my dates on the right-
hand side. So let’s update the rule for our diary-date class as follows:

.diary-date {
font-style: italic;
text-align: right;
}

And reload the page in your browser:

Copyright © 2017 Luke Fabish 71


Figure 31: Examples of CSS text-align.

And you can see the affect that’s had on our date.

CSS background-color
So, enough with the text and fonts already.

One of the things we frequently want to do with a web page is change its colour.

Here, we’ll talk about changing the background colour, which is the colour behind
the text.

To call attention to our diary entry I think we’ll change the background colour of our
diary entry a little.

We’ll use the background-color property to do this. Once again, note the spelling
here: that’s color. CSS would not win an international spelling bee.

So, update the main-content CSS rule as follows:

#main-content{
margin-left: auto;
margin-right: auto;
width: 600px;
background-color: FloralWhite;
}
Copyright © 2017 Luke Fabish 72
Which looks like this:

Figure 32: CSS background-color property example.

Well, that OK, but there’s a couple things to fix. That background finishes right at
the edge of the text, which doesn’t look very nice.

Also, I don’t think the white page looks very good against our ‘FloralWhite’ page
colour.

We’ll fix those now.

Back to the Box Model: CSS borders and padding


I’m sure you remember this:

Copyright © 2017 Luke Fabish 73


This time we’ll adjust the padding:

#main-content{
margin-left: auto;
margin-right: auto;
width: 600px;
background-color: FloralWhite;
padding: 20px;
}

We’ve added 20 pixels of padding to all sides of our box. We could have set padding-
top, padding-right etc., but padding can be set on all four sides at once with just
‘padding’:

Copyright © 2017 Luke Fabish 74


Figure 33: CSS padding example.

Well that’s nicer. But I do want it to stand out some more. How about a border?

#main-content{
margin-left: auto;
margin-right: auto;
width: 600px;
background-color: FloralWhite;
padding: 20px;
border-style: dashed;
border-width: 4px;
border-color: BlanchedAlmond;
}

Note, that we’ve added border-style, border-width and border-color at the end
there. There are a lot of border properties, but these are the most useful for now.

It comes out like this:

Copyright © 2017 Luke Fabish 75


Figure 34: CSS border property.

The border-color is as its name suggests – it sets the colour of the border. The
border-width is the thickness of the border. I’ve set it to 4 pixels here.

Border-style is a bit different. You can see we’ve gone for a dashed border. Other
options include solid, dotted, double, inset, groove and even hidden (when we want
the border to be invisible, but take up space).

CSS color
Finally, color.

When CSS says ‘color’ on its own like that, it really means text color.

Fortunately the same array of colors is available to us for text color as for background
and border colors. Let’s add some color first to our text:

body {
font-family: Georgia, Palatino, serif;
font-size: 18pt;
color: darkred;
}

And then something different for our header:


Copyright © 2017 Luke Fabish 76
h1 {
font-size: 48pt;
font-family: 'Myriad Pro', Helvetica, Arial, sans-serif;
color: orange;
}

Let’s see how that looks:

Figure 35: CSS color example.

Get the CSS out of the HTML


I mentioned earlier in the chapter that one of the benefits of CSS is that we can
control a whole web site with one CSS rule.

To do that, the CSS needs to be stored outside of the HTML file.

We’ll do that now.

First, open a new text file in your text editor. Copy everything between the <style>
tags in diary.html into your new file. This is how it should look, in its entirety:

body {
font-family: Georgia, Palatino, serif;
font-size: 18pt;
color: darkred;
}

Copyright © 2017 Luke Fabish 77


h1 {
font-size: 48pt;
font-family: 'Myriad Pro', Helvetica, Arial, sans-serif;
color: orange;
}

.diary-date {
font-style: italic;
text-align: right;
}

#main-content{
margin-left: auto;
margin-right: auto;
width: 600px;
background-color: FloralWhite;
padding: 20px;
border-style: dashed;
border-width: 4px;
border-color: BlanchedAlmond;
}

Save the new file as diary.css

Now, in diary.html replace your <style> tags and everything between them with this:

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

So diary.html looks like this now:

<!DOCTYPE html>
<html lang="en">
<head>
<title>Dear Diary</title>
<link rel="stylesheet" type="text/css" href="diary.css">
</head>
<body>
<div id="main-content">
<h1>Dear Diary</h1>
<p class="diary-date">September 1st</p>
<p>Oh diary, you won't believe what happened to me today...</p>
</div>
</body>
</html>

Ok, so what does our <link> tag tell the browser?

First, there’s a link we want it to follow, and that it’s going to be a stylesheet
(rel=“stylesheet”). That stylesheet will contain CSS text (type=“text/css”), and that

Copyright © 2017 Luke Fabish 78


the HyperText reference is “diary.css” (href=“diary.css”), which is where to find the
CSS file.

Really, because the <link> tag uses an href, our CSS file could be anywhere on the
Internet, but we’re going to keep ours right next to our diary.html file.

And if our website had lots of pages, they could all include that same <link> tag, and
be controlled by one CSS file.

What have we achieved with our CSS?


Well, we’ve gone from this:

Figure 36: HTML with no CSS.

To this:

Copyright © 2017 Luke Fabish 79


Figure 37: HTML styled with CSS.

While hardly a triumph of typographic design, it definitely improves upon the


original.

Copyright © 2017 Luke Fabish 80


On your CSS journey you’ve covered a lot for a beginner. You’ve learnt so far:

• What CSS is, and what its purpose is, and where it comes from.
• The benefits of using CSS.
• The CSS box model.
• How styles cascade in CSS.
• How to control font styles, types, size and text alignment.
• How to lay out a page using CSS and a <div>
• How to change the colors on a page with CSS.
• How to use elements, classes and divs to select what your CSS rules affect on a
web page.
• And how – like a pro – to store your CSS in a separate location so you can use
it across an entire website.

But there’s so much more! Like HTML, CSS has adapted and evolved through the
years to meet more complex needs. The web keeps changing, and CSS changes with
it.

Summary
Like I said, we’ve covered an awful lot so far.

If you came into this chapter know nothing about CSS, you’ve grown your knowledge
so much since in such a short time. You deserve a rest!

Copyright © 2017 Luke Fabish 81


HTML FORMS:
BEGINNERS GUIDE TO
BUILDING HTML FORMS
AND INTERACTING WITH
THE WEB

What does this picture have to do with HTML forms?

We’ll get to that.

In the previous chapters we’ve had a pretty close look at HTML, and CSS too. It’s
time to expand our knowledge further by learning about HTML forms.

Because forms are what we use to get things done on the web.

And whether you know it or not, you use HTML forms all the time.

Don’t believe me?

Copyright © 2017 Luke Fabish 82


Every time you log in anywhere on the web, post to Facebook or comment on a
webpage, you’re using some kind of form.

So, if you’re learning HTML (or any other web technology) it’s vital to understand
HTML forms, their elements, and how to use them properly.

I’ve got a great project to work on in this chapter while we learn what HTML forms
are, understand how they work and get some practice building one.

Goals
Of course you don’t want to read this chapter and come away with nothing, right?

So this is what you’re going to learn:

• What HTML forms are


• What HTML forms are comprised of
• How HTML forms and web servers work together, and
• How to build an HTML form

What are HTML forms?


Like I said, we use forms on the web all the time.

Any time you type information into a webpage, you’re probably using an HTML
form.

Like a paper form, on HTML forms you can enter different kinds of information to
answer questions.

These questions might just be asking your name. Or a banking website might ask if
you’re currently a customer or not. Maybe a dating site would ask you to list your
interests (‘check all that apply’).

HTML forms have different kinds of controls to answer these kinds of questions.

By control, I mean part of a web page you can interact with, like a button, text field or
check-box
Copyright © 2017 Luke Fabish 83
Figure 38: Example form, the Facebook login.

When we write an HTML form, we group these controls together on a page, along
with a button to click to ‘submit’ the form.

Once we do that, the form will normally be sent off to a server. The server will check
the form to make sure it doesn’t have crazy information in it (e.g. you said your age
is ‘Frank’).

Then the server will send back a response to either say all’s well, or it may send back
an error message saying that you should fill in your form properly.

And this is how it goes:

Copyright © 2017 Luke Fabish 84


Figure 39: Example of sending a form, and receiving a response.

Copyright © 2017 Luke Fabish 85


How to build HTML forms
Let’s find out what we use to build a form in HTML

Form Elements

Once upon a time, a loooong time ago, all forms were wrapped up in form tags, like
this:

<form some attributes >


parts of the form, fields etc
</form>

But since the invention of AJAX that’s no longer 100% true. AJAX is used like a form,
but it updates just one tiny part of a web page.

Anyway, <form> elements are still used a lot. <form> can take a number of different
attributes, but we’ll concentrate on the most important, and most used attributes:
action, and method.

The action is what we want to do, and method is how we want to send data to the
action.

Let’s take a closer look at HTML form action


Like I said, action is what we want to happen when we submit the form.

It’s usually an address that identifies a server, and the location of some code on the
server that’ll know what to do with our form.

Remember the ‘Sign Up’ form example we used above?

I just showed a picture of a server there to keep things simple. But when we send
something to a server, we address it to the server with an URL.

URL stands for ‘Uniform Resource Locator’. Sounds like something we’d use to find a
police officer, right?

No! That’s ‘uniform’ as in ‘regular’ or ‘un-varying’.

Copyright © 2017 Luke Fabish 86


The resource it’s talking about is something on a server. That something could be a
picture, a music file, a web page – anything!

In our case it’s going to be a piece of program code that’ll do something with our
form.

You can think of a URL like an address you write on an envelope.

And this is an example of what an URL looks like:

https://facebook.com/login

Look familiar? This is a simple breakdown:

• https: – This is the protocol (an agreement on how to exchange information).


• // – Separates the protocol and the next bit…
• facebook.com – this is the server, or host. This is the computer1 that stores
the resource we want.
• /login – This is the path to our resource. Resources reside at the end of the
path.

So that’s our action. What about method?

HTML Form’s Method Attribute


The method is how we want to send our form information to a server.

We can use two different values for method: GET, and POST.

There are some important differences between GET and POST, but I’ll only go into
the most important one right now:

1 Only on the most simple sites will a domain like example.com resolve directly to a
server. For large, complex sites like Facebook's, facebook.com will lead to a cascade
of network devices that eventually resolve to a server, somewhere.

Copyright © 2017 Luke Fabish 87


When we use GET, our form information is added
to the URL. If we go back to our example of an
URL being like an address on an envelope, that’d
be like writing your letter on the outside of
the envelope!

Using GET on our imaginary Facebook example URL, our login request might look
like this:

https://facebook.com/login?username=luke&password=chicken+dance

What this would mean is that I’m trying to log into Facebook with a username ‘luke’
and a password of ‘chicken dance’.

When we use POST, form information isn’t sent on the URL; it’s packaged up with
the URL on the outside of it, so your browser can send it off.

This makes POST sound more secure than GET, and it is – but not by much!

So, when should we use them? Their names are a good hint.

We use GET when we’re searching for something, or retrieving data from a server.

We use POST when we want a server to do something besides sending us information


(like creating an account, logging into an account, sending an email and so on).

Finally then, a form element with action and method attributes would look like this if
we continue with our fake Facebook example:

<form action="http://facebook.com/login" method="POST">

That’s enough with the form element for now.

Let's find out how we actually collect information with an HTML form.

Copyright © 2017 Luke Fabish 88


Input types
HTML forms have a variety of controls we can use to collect user information.

The most common one is the ‘input’ tag, which is the workhorse of HTML forms.
Here’s an example:

<input type="text" name="username">

In this example, we can see two attributes: type and name.

The type attribute

Type indicates what kind of control our ‘input’ will be.

<input> is a really odd tag, because the value we give its type attribute will change
the input’s appearance completely! Here are some examples:

<input type="text" name="username"> Username <br>


<input type="radio" name="gender"> Gender <br>
<input type="checkbox" name="gender"> Gender <br>
<input type="submit" name="signup" value="Sign Up">

And this is how it looks:

Figure 40: Example of different form input types.

Odd, right? One tag, <input>, doing all that work!

Copyright © 2017 Luke Fabish 89


And those are just a few of them. HTML5 introduced a lot more. We won’t be using
them today, but they add a lot to HTML forms and you should check them out when
you’re ready.

The name attribute

The name attribute is what we use to identify something within a form.

Why would we do that?

Let’s look at the signup form again. We collected three pieces of information: Email,
Name and Password.

If we just sent three pieces of information off to a server (“me@lukefabish.com”,


“Luke Fabish”, “chicken dance”) we’d have trouble.

While you might guess that my name isn’t ‘chicken dance’, the server
wouldn’t be so sure.

So we need to identify each piece of information, e.g.: email="me@lukefabish.com",


name="Luke Fabish", password="chicken dance".

We’d use our <input> elements to do that like this:

<input type="text" name="email">


<input type="text" name="name">
<input type="text" name="password">

And hey-presto! The data in each input is paired with a name to identify it. You’ll run
into this idea over and over again in computing, often called key-value pairing,
where our name is the key, and the input element’s data is the value.

So that’s how we use the <input> element to collect a simple text value.

Let’s see what else we can do with it.

Copyright © 2017 Luke Fabish 90


Input Element Radio Buttons (there can be only one!)

Back in the day, a long long time ago, car radios had big fat mechanical buttons on
them. Only one button could be pushed in at a time. If you pressed another button,
the button that was in popped back out again.

The main point here is that they allow only one choice.

So HTML forms have these too.

Once again we put the <input> element to work to get some radio buttons, like this:

<input type="radio" name="flavor" value="chocolate"> Chocolate <br>


<input type="radio" name="flavor" value="vanilla"> Vanilla <br>
<input type="radio" name="flavor" value="strawberry"> Strawberry
<br>

Which looks like this:

Copyright © 2017 Luke Fabish 91


Figure 41: Example of form input radio buttons in use. I've put some extra text (Chocolate, Vanilla, Strawberry)
to tell which is which. There's a much better way of doing this, which is coming up later.

On this form, we’re restricting the choices to chocolate, vanilla and strawberry.

You’ll notice that all of the inputs have the same name. That’s so the browser
understands that those radio inputs belong together.

If chocolate is selected and we click vanilla, chocolate is automatically deselected.


The browser knows to do this because the chocolate and vanilla <input> elements
have the same name, ‘flavor’.

If we change the above example so that the strawberry <input> element’s name is
‘fruit’ instead of ‘flavor’, you’ll notice we can select more than one of them:

Figure 42: If form radio buttons have different names, we can select more than one of them.

When we submit the form, the name (or key) ‘flavor’ will only appear once, and it’ll
be assigned whichever choice we made, chocolate, vanilla or strawberry.

Copyright © 2017 Luke Fabish 92


HTML Checkboxes: Getting greedy with multi-select

Let’s return to our flavor example. While it’s great being able to restrict choice on a
for to one item, maybe we want more than that!

That’s where checkboxes come in. They’re an opportunity to present a number of


choices to the user, and the user can select as many as they want. Once again, it’s our
old friend <input> at work here:

<input type="checkbox" name="flavor" value="chocolate"> Chocolate


<br>
<input type="checkbox" name="flavor" value="vanilla"> Vanilla <br>
<input type="checkbox" name="flavor" value="strawberry"> Strawberry
<br>

Which looks like this:

Copyright © 2017 Luke Fabish 93


Figure 43: Example of form input checkboxes.

So now we can choose as many flavors as we want!

This time, when the form is submitted to a server, name will appear for each value
we checked: flavor=Chocolate, flavor=Vanilla, etc.

HTML Select: When there are just too many


options

Sometimes on a form we have more options than screen-space. Especially now so


much web traffic comes from mobile devices.

Did you know, for instance, that Ben & Jerry’s have offered 74 different ice cream
flavors? That’d be a lot of radio buttons!

So we use the <select> and <option> elements instead. They go together like this:

<select name="flavor">
<option>Banana Split</option>
<option>Bonnaroo Buzz</option>
<option>Brownie Batter</opion>
[etc]
</select>

Here’s an example, featuring 74 glorious flavors (sourced here):

Copyright © 2017 Luke Fabish 94


Figure 44: Form <select> input while closed.

Figure 45: Form <select> input while open.

When we submit this form, ‘flavor’ will be assigned one value only, just like our radio
button example.

We can make a <select> element give us multiple values, just like a group of
checkboxes.

I don’t think this is a great idea, because most browsers will display the <select> as a
giant list of options, taking up lots of screen space.

Copyright © 2017 Luke Fabish 95


If you do want to do that, the <select> element has an attribute called ‘multiple’
which breaks all the rules we’ve seen so far, because we don’t give it a value; it just
sits there on its own (I’m not a fan):

<select name="flavor" multiple >


<option>Banana Split</option>
<option>Bonnaroo Buzz</option>
<option>Brownie Batter</opion>
[etc]
</select>

Taking action with HTML Form Submit


Now that we’ve seen all these HTML form elements for gathering input from a user,
we need a way to send it all off to a server.

Once again, our <input> element puts on another disguise and does the job for us.
This is how we use it:

<input type="submit" name="signup" value="Sign Up">

Which looks like this:

Figure 46: Example of a submit input.

When we click a ‘submit’ <input> element, the browser knows that it’s time to pack
up all the values in the form and send them off to the URL in the form’s ‘action’
attribute.

Copyright © 2017 Luke Fabish 96


Enough chit-chat – it’s time to put it all together!

Example of how to build an HTML


form
So, enough with our ice cream forms. We’re got something much more serious to
work with.

This picture of a dog being vacuumed, for example.

This is an animated GIF from the lovely people at GIPHY (you can't tell it's animated
because you're reading this in a book!). Anyway, GIPHY hosts thousands upon
thousands of amusing animated GIF images.

They also provide an API to their GIFs, which is to say, we can send a form to their
server, and they’ll send us a GIF.

Super! We’ll use the part of their API that returns random GIFs that match a tag.

For example, if we send the ‘random’ API a request with tag=”cat”, we’ll get back
random GIFs that feature cats.

Let’s take a look at that now.

Actually, I’ll give you the information you need, and you take a look at it.

Copyright © 2017 Luke Fabish 97


Please open a text editor, create a basic HTML skeleton page and put a form in it. To
start with, we’ll have:

• The form action=http://api.giphy.com/v1/gifs/random


• The form method=”GET”
• One input with type=”text” and name=”tag”
• One input with type=”submit”, name=”submit” and value=”Get GIF”
• And the following:

<input type="hidden" name="api_key" value="dc6zaTOxFJmzC">


<input type="hidden" name="fmt" value="html">

Now the last part isn’t really fair – I’ve introduced a whole new <input> type:
hidden!

Well, like it says, hidden <input> elements are on the form but hidden from the user.

Why would we do this?

Because sometimes we need to send information to


a server that the user has no way of knowing. But
we know it, so we put it in the form where the user
can’t see it, using <input> elements with
type=”hidden”.

In this case, our hidden inputs are sending some information that GIPHY needs.

One is the format we want our image to come back in (“html”), and the other is an
API key.

An API key is a value that’s supposed to identify the person using the API. It doesn’t
count in this case, because GIPHY’s API is in beta testing, and everyone uses the
same key.

So now you know all that, please have a try at making your form for GIPHY and
loading it in a browser.

Copyright © 2017 Luke Fabish 98


Once you’ve done that, type something in your ‘tag’ input (I recommend “puppies”),
click the submit button, and see what you get!

Ok! Here’s my version of the HTML page and form:

<!DOCTYPE html>
<html lang="en">
<head>
<title>Time for some mad GIFs from GIPHY</title>
</head>
<body>
<form action="http://api.giphy.com/v1/gifs/random" method="POST"
target="_blank" >
<input type="hidden" name="api_key" value="dc6zaTOxFJmzC">
<input type="hidden" name="fmt" value="html">
<label for="tag">Tag</label><input type="text" name="tag"
value="">
<input type="submit" name="submit" value="Get GIF!">
</form>
</body>
</html>

And this is what it looks like:

Figure 47: Gloriously unstyled HTML <form> example.

Because I’m just completely unfair, I’ve included a couple of things that you don’t
know about yet. But you get to learn about them now.

One is the ‘target’ attribute for the form. When we set it to “_blank”, that means we
want the result of the submitted form to be shown in a new page.

Try it!

Now your form won’t be replaced by GIPHY’s response to your request.

Copyright © 2017 Luke Fabish 99


The other new item here is the <label> element. It allows us to attach some
explanatory text (i.e. a label) to a form’s <input> element. We use it like this:

<label for="name of input element">The label text</label>

We use the ‘for’ attribute so that the browser knows which labels and <input>
elements go together, and can arrange them nicely on the page.

Expanding our example HTML Form


You may be interested to know that GIPHY’s GIFs have ‘suitability’ ratings, like PG,
R, G etc. We’ve been querying their API for everything so far, so I hope you haven’t
seen anything too naughty.

Let’s add some controls to our form to let us choose the naughty level of the GIFs we
search for.

So please add five radio buttons to the form. They should all have name=”rating”,
and each should have its value set to one of the following: “y”, “g”, “pg”, “pg-13”, “r”.

Put some text followed by a <br> after each radio <input> that explains each option
(that’d be “Young”, “General”, “Parental Guidance”, “Parental Guidance for 13 years
and older” and “Restricted”).

Give it a try! Then read on for my solution.

(I’m sure you’re doing that right now…)

Ok! Here are the <input> elements I added to my form:

<input type="radio" name="rating" value="y" checked > Young <br>


<input type="radio" name="rating" value="g"> General <br>
<input type="radio" name="rating" value="pg"> Parental Guidance <br>
<input type="radio" name="rating" value="pg-13"> Parenatl Guidance
for 13 years and older <br>
<input type="radio" name="rating" value="r"> Restricted <br>

And in my browser:

Copyright © 2017 Luke Fabish 100


Figure 48: Expanding the GIPHY example with radio buttons.

And you might notice I got you again! Yes, I added the ‘checked’ attribute (again,
without a value) to the ‘Young’ radio button.

Adding ‘checked’ to a radio button or checkbox <input> element selects it by default.

We do this to help the user out, and to make sure we don’t submit inputs without
values to a server.

Try adding the ‘checked’ attribute to one of your radio inputs!

A final submission on <forms>


So that about wraps it up for HTML forms.

We’ve covered a lot today and I think it’s enough for one session!

Here’s what you’ve learnt today:

• What HTML forms are


• How HTML forms work with a server
• The <form> element and its most important attributes
• The <input> element, and how to use it as a
o Text field
o Radio button
o Checkbox
o Submit button

Copyright © 2017 Luke Fabish 101


• The <select> element, and how to use it to select among a large number of
options
• How to build an HTML form
• How to send queries to a real, live server on the Internet.

The next chapter is a lot less practical than the first chapters, but you'll need to get
your thinking cap on for it! It's a preliminary chapter for beginning programming
with JavaScript, and will prepare you for some of the challenges in later chapters.

Copyright © 2017 Luke Fabish 102


Copyright © 2017 Luke Fabish 103
COMPUTATIONAL
THINKING: HOW TO
THINK LIKE A
PROGRAMMER AND FIND
GREAT SOLUTIONS TO
TOUGH PROBLEMS

Let me ask you a question:

What does a programmer do all day?

Stare at a monitor and type? Attend meetings? (Ha!).

Seriously, mostly what they do is think, which is why they’re considered knowledge
workers.

Sounds cushy right?

Sitting around thinking all day. It’s sure better than cleaning fish or hauling ice (I recommend
neither), but it’s no walk in the park.

Programmers are held accountable for the quality of their thinking and
the decisions they make based upon it.

Poor thinking means poor code. Poor code means software bugs, projects running
over time and over budget, and everyone working late to fix bad software.
Copyright © 2017 Luke Fabish 104
You may be thinking at this point – well bigger brains mean better software, right? If
there’s more IQ to pour into a problem we’re going to get a better solution.

While having a few brain cells definitely helps, the IQ advantage goes out
the window when we’re stressed, sleep-deprived, angry, in love (!) or
generally just being human.

What saves us from ourselves? Tools and techniques that allow us to reduce complex,
overwhelming problems to small, achievable tasks.

These techniques comprise computational thinking.

Computational thinking doesn’t mean thinking like a computer – just the opposite!
It’s where you use your ability to think like a human to solve problems with a
computer.

In this chapter I’ll give you a framework for thinking about problems that you can
use to develop great solutions.

What we'll cover on computational thinking


Here’s what we’ll look at and practice today:

• Decomposition – how to break complex problems down into simple ones.


• Algorithms – how to make a recipe for solving a problem, every time.
• Checking for blind-spots (examining assumptions)
• And bundling everything up into abstractions

Sound weird? Don’t worry, it won’t by the end of the chapter.

What you’ll be able to do by the end of this chapter


By the end of this chapter you’ll have the tools to:

• Know how to understand a problem from the top to the bottom


• Build solutions that work every time.
• Make your solutions easy to understand.

Sound too good to be true? I didn’t say it was going to be easy!


Copyright © 2017 Luke Fabish 105
But first, you’ll have to meet your new robot!

Get started with computational thinking – train the UrkelBot!

Figure 49: Allow me to apologize if the reference is before your time.

Congratulations! You’re the proud new owner of a brand new UrkelBot5000. Just
like you always wanted.

He’s a domestic robot, and besides bursting into your kitchen at odd times and
making whiny noises, he’ll understand and DO anything you tell him – anything at
all!

The only problem is, he can’t really think for himself.

So before you can enjoy your new domestic helper, you’ll have to train him.

Let’s start with a nice hot cup of tea.

How to make tea


This is actually a very controversial question – people from the UK, India and Japan
will have very different ideas about it. Never mind the rest of us.

But we’ll keep things simple for UrkelBot.

Copyright © 2017 Luke Fabish 106


We’re going to ask him to make tea by adding a tea bag to a cup of freshly boiled
water (from an electric kettle).

So before we go any further, please write down the steps for making a cup of tea
(make sure you don’t leave anything out!)

Breaking the tea problem down (Decomposition)


So, instead of me trying to read your mind and guess how you make tea, I’ll give you
the list I made sitting in an early programming class:

1. Boil water in kettle


2. Put teabag in cup
3. Put boiled water in cup.

Huzzah! A nice hot cup of tea.


And I can give this tea recipe to just about anyone, and they’ll hand me back a hot
cup of tea. Excellent.

That works with humans because we have a similar frame of reference. We’re all
more or less familiar with cups, tea and kettles.

UrkelBot however, is a machine, and doesn’t share that frame of reference. So we


really need to spell things out for him.

This is where we start decomposing our problem – i.e. break it down into smaller
problems.

As you can see, young Luke has already done this somewhat. Our ‘make tea’ problem
has been turned into three problems. But is this enough? Let’s consider the first step:

“Boil water in kettle” is fine for you and me, but UrkelBot? He’s not too sure where
this water is coming from, nor how to make it ‘boil’.

So maybe we can break this problem into:

1. Fill kettle from tap


2. Push button on kettle to boil water.

So that’s a little better, but did UrkelBot just splash water over the top of a closed
kettle? Did he produce any water at all?
Copyright © 2017 Luke Fabish 107
So “Fill kettle from tap” needs to be spelled out too:

1. Grasp kettle by outer handle.


2. Push button on the top of the handle to open the lid on top of
the kettle.
3. Place open top of kettle beneath cold-water tap.
4. Open cold-water faucet (I’ll leave the choice between turning
the faucet anti-clockwise vs raising the lever up to you and
your kitchen).
5. Close the cold-water faucet when the water level in the kettle
reaches the MAX indicator on the kettle.
6. Close the lid on the kettle.

And UrkelBot might have a bit more luck filling the kettle with those instructions.

Too bad we’re only one third of the way to a cup of tea.

This isn’t just for UrkelBot, of course. We as programmers need to go through this
process to solve complex problems.

Decomposition is a tool for managing problems that exceed our brain’s


capacity to understand all at once. It’s a vital part of being a programmer –
much more than learning the ins and out of the latest JavaScript framework.

If you went through this process already and produced a nice, take-nothing-for-
granted list of instructions for making tea – then congratulations! You’re a natural at
decomposition!

Otherwise, now might be a good time to re-examine your steps for making tea, and
expand them to the point where UrkelBot can do no wrong.

Copyright © 2017 Luke Fabish 108


Key Takeaways:

• Decomposition is breaking large complex problems into small simple ones


• It reduces the amount of complexity we need deal with at any one time
• It’s a fundamental process for dealing with complexity

Copyright © 2017 Luke Fabish 109


Hidden Assumptions

A program is only as good as the assumptions it was built upon, and the same goes
when we teach tea-making to UrkelBot.

The thing about this exercise is that we’re making tea.

I’ve made an assumption (an explicit one) that you drink tea, and not coffee, or some
other hot beverage. This isn’t really a reasonable assumption (I prefer coffee, myself),
but at least it’s been stated.

Hidden assumptions are trickier. These are things that are so obvious that we don’t
even think about them.

I’ve been talking all this time about putting teabags into a cup, but do we actually
have any tea in the house? Does the cup need washing? Is the kettle plugged in (and
the electricity bill paid)? Was the kettle full already? And so on.

If you were actually standing in a kitchen these things might have jumped out to you
as obvious.

But since we’re dealing with an imaginary kitchen they may be a little more difficult
to anticipate.

Copyright © 2017 Luke Fabish 110


That might not seem fair, but that’s the situation we’re dealing with when
we’re programming – imagining data, files, network connections and so
on. Many things you’ll never see in the flesh.

So we need a tool to help us uncover these assumptions.

One thing I like to do is list all the states of the things I’m dealing with, for instance:

Kettle:

• Lid closed? Yes/No


• Plugged in? Yes/No
• Full? Yes/No
• Turned on? Yes/No

And so on. This helps make our imaginary kettle a little more concrete.

Examining each of its states can highlight problems in our solutions.

Again, it’s a way of decreasing the amount of complexity our brain must deal with in
a single moment. (You might see a pattern forming here).

So try it yourself. List the states of the Tea, and the Faucet, and then compare them
to the steps you’ve developed so far.

Copyright © 2017 Luke Fabish 111


Key Takeaways

• Hidden assumptions get us because they’re so obvious we don’t think about


them.
• They can be a big source of problems in code.
• Assumptions are ok if we state them
• Listing properties and states of the things you’re dealing with can expose
hidden assumptions

Copyright © 2017 Luke Fabish 112


Turn it into a recipe (let's make an algorithm)
You’ll hear a lot about algorithms in the programming world. College courses have
multiple semesters devoted to them and there are hundreds of books on algorithms.

But we can define an algorithm simply as a series of steps that lead to a solution.

We started working on an algorithm for making tea during our problem


decomposition.

You’ll notice that our definition of algorithm doesn’t say ‘maybe leads to a solution’
or ‘sometimes leads to a solution.’ An algorithm is no good if it doesn’t get us to a
solution.

Luckily, we fleshed our first steps for UrkelBot’s tea making out by examining
assumptions. When we incorporate those into our tea recipe, it gets a little more
robust.

But now it’s time to express the tea recipe as an algorithm a little more formally.

First, we need to know that an algorithm is made up of three types of things:

• execution, or sequence (i.e. do something, and then do something else)


• decision, or branching (“If the kettle isn’t full…”, “if there is tea…”)
• repetition, or iteration (“Is the kettle boiled? No, wait. Is the kettle boiled? No,
wait…”)

We’ll apply these to our ‘Fill the kettle’ algorithm, and incorporate extra steps to deal
with some assumptions identified earlier.

Since we already have a series of steps to execute, we’ll move on to decision:

1. If the water in the kettle reaches the MAX indicator; Then


a. Finish here (there’s nothing to do!)

2. Grasp kettle by outer handle.

3. If the kettle lid is closed; Then


a. Push button on the top of the handle to open the lid on top
of the kettle.

4. Place open top of kettle beneath cold-water tap.


Copyright © 2017 Luke Fabish 113
5. If the cold-water faucet isn’t open; Then

a. Open cold-water faucet.

6. Close the cold-water faucet when the water level in the kettle
reaches the MAX indicator on the kettle.

7. Close the lid on the kettle.

This is also called branching, because the code branches into different paths.

The If…Then construct is an extremely common way of implementing decisions in


programming languages. If you’ve done even a little programming before you’re
bound to have run into them.

You’ll notice that they allow us to skip steps that don’t need to be performed, and
avoid making mistakes.

What’s more, this is the kind of instruction UrkelBot understands: If this, then that…
And our tea recipe is looking a little more like a program.

Because that’s what a program is – an algorithm encoded in a form a machine can


understand.

Let’s move on to repetition, more formally known as iteration. Less formally known
as looping.

Why looping? Because sometimes in an algorithm we need to loop back to an earlier


part of the algorithm and repeat some steps.

Let’s add it to the kettle-filling algorithm:

1. If the water in the kettle reaches the MAX indicator; Then


a. Finish here (there’s nothing to do!)

2. Grasp kettle by outer handle.

3. If the kettle lid is closed; Then


a. Push button on the top of the handle to open the lid on top of
the kettle.

4. Place open top of kettle beneath cold-water tap.

5. If the cold-water faucet isn’t open; Then


a. Open cold-water faucet.
Copyright © 2017 Luke Fabish 114
6. Has the water reached the MAX indicator on the kettle?
a. No?
i. Wait 1 second
ii. Go to step 6
b. Yes?
i. Continue to step 7

7. Close the cold-water faucet.

8. Close the lid on the kettle.

Now we repeatedly wait until the kettle is full. Once again, repeating code like this is
often referred to as ‘iteration’ or ‘looping’.

The appearance of ‘Go to’ may give some people the shivers here, because ‘Go to’
commands (called ‘goto’) were once abused terribly in early programming. Goto was
synonymous with messy, undisciplined code.

But don’t worry! All programming languages (and programmers) use ‘go to’ style
statements all the time, it’s just that they’re dressed up with a different name that
forces us to use them properly. These are ‘looping’ constructs, often called ‘for’ or
‘while’. We’ll look at using them in a later chapter.

Finally, we should ask ourselves “is this a good algorithm?” Is it going to give us a full
kettle every time? I think if we state some outstanding assumptions (‘water is
available’, ‘kettle lid works reliably’, ‘the faucet works’) then we’ve got a good
algorithm.

Over to you – try applying these constructs (execution, decision and repetition) to
the rest of your tea-making instructions, and see what you come up with!

Copyright © 2017 Luke Fabish 115


Key Takeaways

• An Algorithm is a series of steps that lead to a predictable outcome


• Algorithms are comprised of sequences, decisions and repetition
• A sequence is one or more steps executed one after the other
• We make decisions using the If..Then construct
• Looping is implemented with constructs like ‘For’ and ‘While’, but they behave
similarly to the ‘go to’ example above

Copyright © 2017 Luke Fabish 116


Abstractions
Let’s take another look at our kettle-filling algorithm:

1. If the water in the kettle reaches the MAX indicator; Then


a. Finish here (there’s nothing to do!)

2. Grasp kettle by outer handle.

3. If the kettle lid is closed; Then


a. Push button on the top of the handle to open the lid on top of
the kettle.

4. Place open top of kettle beneath cold-water tap.

5. If the cold-water faucet isn’t open; Then


a. Open cold-water faucet.

6. Has the water reached the MAX indicator on the kettle?


a. No?
i. Wait 1 second
ii. Go to step 6
b. Yes?
i. Continue to step 7

7. Close the cold-water faucet.

8. Close the lid on the kettle.

It’s getting fairly involved now, and it’s only about one sixth of our overall tea-
making instructions!

So to save us the trouble of dealing with all this detail in the future, we can put a label
on it, and know that the label represents a well thought-out algorithm. What should
we call it then?

Fill kettle from tap.

What? Back here again? This is our step from our first effort at decomposition!

Here’s the difference:

Before, ‘Fill kettle from tap’ was useless to UrkelBot. But now ‘Fill kettle from tap’
contains everything UrkelBot needs to know to fill the kettle.

But we could have just given UrkelBot the original list, right? Machines don’t care if
instructions are wrapped up in nice labels.
Copyright © 2017 Luke Fabish 117
As I said before, it makes life easier for us.

Having worked out all the detail, we can happily forget it and use our abstraction,
confident that now, and in the future, we can tell UrkelBot to ‘Fill kettle from tap’,
and he can go and look at our detailed instructions.

And here’s another benefit – we can generalise the abstraction, and the
underlying algorithm to give us something like:

Fill from tap (thing)

So that we expand UrkelBot’s abilities to

Fill from tap (kettle)

Fill from tap (pot)

Fill from tap (cup)

And so on. Our abstraction not only saves us from thinking work, it expands our (and
UrkelBot’s) abilities, so that we multiply the value of the work we did
developing the original algorithm.

Over to you – see what abstractions you can come up with from the algorithms you
developed in the previous section. How could you generalise and expand them in the
future?

Copyright © 2017 Luke Fabish 118


Key Takeaways

• Abstractions are a way of dealing with complexity.


• They act as a label for complex details.
• They save us from dealing with complex details over and over again.
• We can generalise them to apply them to new situations and make them more
useful.

Copyright © 2017 Luke Fabish 119


And let's replace UrkelBot
So now we’ve have a good look at the fundamental practices for understanding
problems and developing solutions:

• Decomposing problems
• Developing algorithms
• Analysing assumptions
• Using abstractions

While I can’t give you an actual UrkelBot (how I wish I could!), I’m sure you realise
by now he’s standing in for your computer.

And of course these are the practices you’ll use to develop programs for your
computer.

Hang tight – we're about to start applying some of these principles in the next
chapter – Introduction to JavaScript.

Copyright © 2017 Luke Fabish 120


Copyright © 2017 Luke Fabish 121
JAVASCRIPT
PROGRAMMING FOR
ABSOLUTE BEGINNERS

Ok, are you ready to start programming in JavaScript?

That’s what we’re going to do today.

JavaScript, as I’m sure you’re aware, is one of the most-used programming languages
today.

And it’s still growing in popularity!

Every day there are new JavaScript frameworks and libraries being released.

So there’s never been a better time to start learning.

Because everyone has to start somewhere, we’ll keep things simple. We’ll practice
some basic programming concepts using JavasScript, and learn how JavaScript,
HTML and your browser all work together.

Let’s get started!

Goals
Here’s what you’re going to learn today:

• How we can use HTML to trigger some JavaScript


• How to write JavaScript inside an HTML web page
• How to define a simple JavaScript function

Copyright © 2017 Luke Fabish 122


• To use JavaScript to make changes to a web page
• How to use abstraction
• How to use and define variables

Phew! That’s plenty!

How to use this chapter


This chapter builds on previous chapters in the e-book. If you’re not at least a little
familiar with HTML and Computational Thinking, I suggest you catch up with the
previous chapters:

• HTML FOR ABSOLUTE BEGINNERS


• COMPUTATIONAL THINKING: HOW TO THINK LIKE A PROGRAMMER
AND FIND GREAT SOLUTIONS TO TOUGH PROBLEMS

Remember UrkelBot from the Computational Thinking chapter?

Figure 50: UrkelBot - he's baaaaack!

We put him in a kitchen to make a cup of tea.

In the kitchen, he didn’t really know how to use a kettle or turn on a tap.

Now you’ve swapped places with UrkelBot.

Copyright © 2017 Luke Fabish 123


If you haven’t programmed before, then JavaScript is going to feel like
that kitchen did to UrkelBot.

You’re going to be presented with tools that don’t at first make any sense. Don’t
worry!

The goal today isn’t to understand everything about JavaScript. The goal here is to
practice some fundamental programming ideas, and see JavaScript working in a
browser.

You’ll learn some introductory JavaScript syntax, which you can build on for future
learning.

So go through the chapter one section at a time.

Each section has a core learning goal (that I’ll spell out at the beginning) that I hope
the section will convey successfully. Anything else presented along the way is a
bonus, but not vital for this chapter.

Copyright © 2017 Luke Fabish 124


Key Takeaways:

• This chapter assumes a very basic understanding of HTML and programming


concepts
• The primary goal is to practice some fundamental programming concepts in
JavaScript
• The secondary goal is getting a little familiarity with JavaScript syntax.

Copyright © 2017 Luke Fabish 125


How programming languages work
Learning goal: Gain a high-level understanding of how a program is
turned into something a
computer understands and
acts upon.

Programming is often called


‘coding’, because we as
programmers encode our
instructions in a format that can be
understood by a computer.

Of course we can’t say Computer!


Count all the records in the invoice
file! But we might say something
like:

for each invoice record


add one to the count

That’s the first step in encoding our


instruction for a computer.

Lucky for us, the rest is taken care


of by other computer programs, but
it goes something like Figure 51

In this image, you can see that our


source file (where we type our
programming code) is encoded into
a series of formats that are
increasingly more computer
friendly.

Finally, it reaches a stage where it’s


in a format that corresponds to the

Figure 51: High-level overview of Copyright © 2017


how source code Luke
turns into a Fabish 126
computer program.
instructions used internally by a computer.

The computer’s then free to orchestrate activity amongst its parts to carry out the
instructions that were in your source file.

There are a couple things to note here:

• Once upon a time, long ago, people programmed computers using that lowest
level of programming code (1s and 0s).
• The different levels of code can be viewed as levels of abstraction.
• The highest level is the one we deal with when we type code into a source file.
• These abstractions save us time and effort by avoiding complex detail.

Copyright © 2017 Luke Fabish 127


Key Takeaways

• Our programming code must be turned into ‘machine’ code before a computer
can use it.
• We have programs called interpreters, compilers and linkers to turn our code
into something a computer can use
• The programming code we use today is an abstraction that hides complex
detail. This saves us time, effort and reduces the opportunity to make
mistakes.

Copyright © 2017 Luke Fabish 128


How JavaScript works in your browser
Learning goal: Gain a high-level understanding
of the differences between running JavaScript
and other code.

We’ve seen how programming code is turned into


something a computer understands, and then how a
computer uses that code.

JavaScript is a little different, because it uses a browser


to execute all its instructions. Actually, JavaScript is
executed by a JavaScript Engine, which is part of the
browser.

The JavaScript Engine compiles the JavaScript and


executes it, which in turn controls the browser.

Key Takeaways

• JavaScript is compiled like other programming


languages
• The difference is that the resulting machine code
is executed within the browser.

Figure 52: How JavaScript is


Copyright © 2017 Luke Fabish 129
executed by a browser.
How JavaScript, HTML and the browser work together
Learning goal: Understand how JavaScript can affect HTML, and how
that affects the browser.

Now that we’ve seen how JavaScript code is executed in a browser, let’s take a closer
look at how that works in our HTML.

As we saw earlier, an HTML page is structured like this:

Copyright © 2017 Luke Fabish 130


Figure 53: HTML page structure.

We can use <script> tags to add code to the HTML. We normally put <script> tags in
the <head> section of a page, but more often these days we put it at the very end of
the page.

Copyright © 2017 Luke Fabish 131


This is to stop very large pieces of JavaScript making a page load slowly.

For simplicity, we’ll put our code at the top of the page, since it’s going to be small
anyway.

Our page is going to look kind of like this:

Figure 54: HTML page structure including <script> tags.

But how does JavaScript do anything? It’s just sitting there in the page, right?
Copyright © 2017 Luke Fabish 132
Well, there are lots of ways of running JavaScript in a page, but the most common,
and what we’ll be focusing on today, is events.

Every time you do something on a web page, like click a button, or type in
a text box, you trigger an event.

When an event occurs, it’s packed up in a parcel of information:

• What the event was (a click? A keypress?)


• Information about the event (what was clicked? What key was pressed?)

The browser uses this information to react to the user’s actions.

Did the user click a submit button? The browser had better check what form the
button belongs to, and submit the form.

Did the user type in an <input>? The browser had better update the input to show
what the user typed.

The great thing is, we can catch these events in our HTML, and then pass them to
our JavaScript.

So, imagine we have a <button> element2 that’s not part of a form. We can tell the
browser that we want to know when our <button> is clicked like this:

<button onclick="our-javascript-goes-here">

So now when our <button> is clicked the browser executes whatever our-javascript-
goes-here may be.

And the beautiful thing is that our JavaScript can then go and change what the user
sees on the page, creating a cycle of interaction.

2 The <button> element is just like <input type="submit"> or <input


type="button">, except that it has a closing tag and we can put content inside it like
text, or images.

Copyright © 2017 Luke Fabish 133


Key Takeaways

• JavaScript can appear in HTML pages between <script> tags


• We can execute JavaScript by linking it to events.
• Events can be triggered by a user doing something in the browser.
• JavaScript can update the browser display, so the user knows their action had
an effect!

Copyright © 2017 Luke Fabish 134


Let’s try some JavaScript in a sample page
Learning goal: Execute JavaScript for the first time; learn the syntax for
calling a JavaScript function.

Ok! It’s time to try some JavaScript! We’ll start super-simple and work our way up to
something more interesting.

To begin with, open up a text editor, and enter and save the following (js-intro.html):

<!DOCTYPE html>
<html lang="en">
<head>
<title>JavaScript Introduction</title>
</head>
<body>
<h1>HTML, meet JavaScript</h1>
<button onclick="alert('Why, hello there.')">Say Hi</button>
</body>
</html>

Open it in your browser, and you should see something like:

Figure 55: A button with JavaScript attached to it.

Copyright © 2017 Luke Fabish 135


And if you click the button:

Figure 56: Clicking a button with JavaScript attached to it. Don't check 'Prevent this page from creating
additional dialogues'! If you do, our examples won't work for a while!

So let’s take a look at what’s going on:

<button onclick="alert('Why, hello there.')">Say Hi</button>

The most interesting part is this:

onclick="alert('Why, hello there.')"

There’s a few things to notice here:

The HTML attribute onclick (it’s not JavaScript!) is used to say we want to execute
some code when our button is clicked.

All events in HTML are specified in the form onevent. E.g. onchange, onkeypress,
and so on.

As usual with a tag attribute value, we’ve enclosed it in double-quotes


("):"alert(‘Why, hello there.’)"

Copyright © 2017 Luke Fabish 136


The actual JavaScript is this:

alert(‘Why, hello there.’)

Notice that we’re using a string here – 'Why, hello there.' – which we’ve enclosed in
single quotes ('). We have to use single quotes here because the whole thing’s
wrapped in double-quotes (").

The browser isn’t smart enough to understand that: "alert("Why, hello there.")" isn’t
three separate things:

1. alert(
2. Why, hello there.
3. )

When we say string in programming, we mean a piece of text, usually enclosed in


quotes. For example: “A”, “this is a string”, ‘this is also a string’.

Let’s take a closer look at our JavaScript code:


alert('Why, hello there.')

Remember when I said you’d be like UrkelBot navigating an unfamiliar kitchen?


Well this is your first mystery appliance. Every kitchen has them, right? A cupboard
full of appliances that on first glance doesn’t really make sense?

Copyright © 2017 Luke Fabish 137


Figure 57: An appliance that makes no sense at all! Sadly, you'll encounter a few programming tools like this.

JavaScript has built-in tools (like alert) that we can use. They’re unfamiliar at first,
but you’ll get to be more familiar with them as you use them.

So alert is a JavaScript function. A function is a series of commands bundled up


together with a name on them.

As we discovered, alert creates a little window on our screen with text in it. When we
give a function a value to use like that, that value is called a parameter. Functions are
executed (or called) like this:

functionName(parameter)

If a function had two parameters, we’d call it like this (note the comma between
parameters):

functionName(parameter1, parameter2)

And if it had no parameters:

functionName()
Copyright © 2017 Luke Fabish 138
In JavaScript, a function always has brackets “(” and “)” at the end, even if it has no
parameters.

So looking at our JavaScript example then:

alert('Why, hello there.')

We can say we’re calling the function alert with the parameter ‘Why, hello there.’

These rules for writing JavaScript (and other languages) are called
syntax.

The syntax of a programming language simplifies natural language commands


(“Please open a small window and display ‘Why, hello there.’ in it.”) so that
computers can understand them.

Let’s try another example:

Try changing the parameter in our alert function to ‘This is my first


JavaScript programming exercise.’

Copyright © 2017 Luke Fabish 139


Key Takeaways

• We can attach JavaScript to events in HTML


• We do this using onevent. We used onclick in our example.
• JavaScript has functions
• Functions are commands grouped together with a name.
• We can pass one or more values to a function. These values are called
parameters.
• Functions are always used with “(” and “)” at the end of the function name.
• Parameters are always separated by a comma (,).

Copyright © 2017 Luke Fabish 140


Time to roll your own JavaScript
Learning goal: Define your own JavaScript function; execute it with an
HTML event.

So now we’ve used JavaScript’s alert function, let’s try making our own. Update your
example HTML file so that it looks like this:

<!DOCTYPE html>
<html lang="en">
<head>
<title>JavaScript Introduction</title>
<script type="text/javascript">

function showAlert(alertMsg){
alert(alertMsg);
}

</script>
</head>
<body>
<h1>HTML, meet JavaScript</h1>
<button onclick="showAlert('Why, hello there.')">Say Hi</button>
</body>
</html>

Note – we’ve added some <script> tags, a function definition inside them, and we’ve
updated our <button>'s ‘onclick’ attribute.

If you reload that file in your browser, you should get exactly the same behaviour!
Never mind – we’re covering some important concepts here and we’ll start
expanding our JavaScript capabilities soon.

Let’s take a look at our changes.

First, we have our <script> tag:

<script type="text/javascript">

Copyright © 2017 Luke Fabish 141


You can see we’re using a type attribute with a value of “text/javascript”.3

Next:

function showAlert(alertMsg){
alert(alertMsg);
}

What’s happening here? We’ve made our own function!

In the last section I said that a function is some commands grouped together with a
name.

In this case there’s only one command, JavaScript’s alert function, which we saw in
the previous section.

And to make our function and give it a name, we have this:

function showAlert ( alertMsg )

We use the word function to tell JavaScript we’re making a new function. Then we
give it a name. For names like this it’s best to stick to normal alphabetic letters (A-Z,
a-z). Also, we can’t use spaces or hyphens (-) in function names either.

Notice that the function name is in the form verbNoun, where show is the verb, and
Alert is the noun. This helps us know what a function does. It shows an alert.

We could call the function xyz(abc) and it would work exactly the same – but we
wouldn’t know what it does!

Anyway, you’ll notice that the showAlert has (alertMsg) on the end of it.

In the last section we saw a parameter being passed to alert like this:

alert('Why, hello there.')

3 The type attribute isn't strictly necessary any more, since the default value for a
<script> tag's type attribute is "text/javascript". I've included it because there are
many examples of both styles on the web.

Copyright © 2017 Luke Fabish 142


‘Why, hello there.’ is the parameter. So we give a function a parameter. But how does
it receive it?

It receives it with a named parameter. The actual definition of the alert function
starts like this:

function alert(message)

So ‘Why, hello there.’ goes in, and it comes out as message. In this case, message is
like a container for ‘Why, hello there.’

For our new function, showAlert, we’ve given it a container for messages called
alertMsg.

There are two more important things to cover with our new function. Let’s look at the
function again:

function showAlert(alertMsg){
alert(alertMsg);
}

The first of these is that alert(alertMsg) has a semi-colon (;) on the end of it. Semi-
colons at the end of a line in a JavaScript function are optional, but I believe it’s best
to use them.

The second, is that there are curly braces “{” and “}” around the body of the function.
This is how a function’s commands are grouped together.

Finally, let’s see how we use our new function:

<button onclick="showAlert('Why, hello there.')">

As you can see we’ve just exchanged alert for our own showAlert. Because we
package ‘Why, hello there.’ up in a parameter called alertMsg, we’re free to pass it
along to the call to alert in our own function.

What we’ve just covered here is the syntax for declaring a function. We could define
any function in the same way:

function nameOfFunction(parameter1, parameter2,...){


command1;
command2;

Copyright © 2017 Luke Fabish 143


etc
}

Copyright © 2017 Luke Fabish 144


Key Takeaways

• We can make our own JavaScript commands, called functions.


• Functions can have parameters, which are containers for the values we give
functions.
• A function doesn’t have to have parameters!
• We can call our functions the same way we call JavaScript commands like
alert.
• You can name a function however you want, but descriptive names are best.
• Parameters should also have descriptive names.
• Descriptive names help us as programmers remember what our code does (it’s
surprisingly easy to forget!)

Copyright © 2017 Luke Fabish 145


Use JavaScript to write a message on our page
Learning goal: Learn how to declare a variable; see how we get data from
an HTML page; see how we write data to an HTML page.

In the previous section we replaced JavaScript’s alert function with one of our own.

But I’m sure you’ve noticed that most websites don’t communicate with you by
opening little windows with messages in them!

It’s much better to change the actual web page. And that’s what we’ll do now:

<!DOCTYPE html>
<html lang="en">
<head>
<title>JavaScript Introduction</title>
<script type="text/javascript">

function updateMessage(){
var msg;
msg = document.getElementById('msgInput').value;
document.getElementById('message').innerHTML = msg;
}

</script>
</head>
<body>
<h1>HTML, meet JavaScript</h1>
<div>Get typing:</div>
<input id="msgInput" type="text" onkeyup="updateMessage()">
<h2 id="message"></h2>
</body>
</html>

There are some big changes here! Maybe make a new file (e.g. ‘js-intro-2.html’) and
type the new code into it. Then open it in your browser. What do you think it will do?
Try typing into the text input and see what happens!

Copyright © 2017 Luke Fabish 146


Now that you’ve done that, let’s look at our new code.

This time, we’ll start with the HTML:

<h1>HTML, meet JavaScript</h1>


<div>Get typing:</div>
<input id="msgInput" type="text" onkeyup="updateMessage()">
<h2 id="message"></h2>

So our <h1> is the same.

Then we’ve got a <div> with Get typing: in it. Nothing special there.

Next is a text input:

<input id="msgInput" type="text" onkeyup="updateMessage()">

Ok! Now we’ve got something new. Let’s check it out.

If you’ve read the earlier chapters on HTML and Forms, you’ll already know about
text inputs. You can see this one’s got an id of msgInput. You’ll see why that’s
important soon.

The really interesting thing about this input is that it’s using a different event:
onkeyup.

Copyright © 2017 Luke Fabish 147


We’ve assigned updateMessage() to it. This means that when we type into that text
input and our finger lifts off a key, updateMessage() will be executed.

Finally in the HTML we have:

<h2 id="message"></h2>

Hmmm. An empty <h2> with an id set to message. You’ll see how we use this <h2>
and id value in a moment.

Time to check out our JavaScript:

<script type="text/javascript">

function updateMessage(){
var msg;
msg = document.getElementById('msgInput').value;
document.getElementById('message').innerHTML = msg
}

</script>

So the <script> tag is the same as before.

But we have a new function: updateMessage(). This is the function we assigned to


that text input’s onkeyup event.

What’s it doing? You can see the curly-braces “{” and “}” grouping together three
commands. And they’re pretty funky commands.

At a high level:

• The first command makes a container (variable) called msg.


• The next command gets whatever is in our text input and stores it in msg.
• The last command puts the contents of msg inside our <h2> tags.

Let’s take a closer look. Here’s the first line:

var msg;

This creates a variable called msg. var is short for variable.

What’s a variable?
Copyright © 2017 Luke Fabish 148
Like the parameter I described earlier, a variable is a container we can temporarily
store something in, like a number (1, 2, 50.23 etc.), or a string (“A”, ‘B’, “Here’s
lookin’ at you, kid.”).

When we put a value into a variable like that, we can pass the variable
around and re-use it over and over. That way you only have to type
“Here’s lookin’ at you, kid” once. Thank goodness for that.

Once again, I’ve ended the variable declaration with a semicolon (;).

So now we have a variable called msg. What’s next?

msg = document.getElementById('msgInput').value;

Whenever you see something = somethingElse, it means that something is some kind
of variable, and we’re putting the value of somethingElse into it.

The somethingElse could be a literal value, like a number or string, or it could be


another variable.

Hey, let’s try that right now! Change your updateMessage() function to read as
follows:

function updateMessage(){
var msg;
msg = "Here's lookin' at you, kid.";
document.getElementById('message').innerHTML = msg;
}

Reload it in your browser, and try typing in that input field again. You should see
something like:

Copyright © 2017 Luke Fabish 149


Figure 58: Re-assigning a variable.

So we’re assigning a value to our variable msg.

It’s not a requirement for our purposes today to understand more than
that.

The rest of this section deals with the nitty-gritty of how we refer to elements (HTML
tags displayed in a browser) in JavaScript. We refer to them in this way so we can get
data from them, or put data into them.

So it’s entirely expected for the next part not to make sense – but only
because it’s unfamiliar to you. It’s not complicated, just weird.

Anyway, let’s change the function back again:

function updateMessage(){
var msg;
msg = document.getElementById('msgInput').value;
document.getElementById('message').innerHTML = msg;
}

What are we assigning to msg here?

msg = document.getElementById('msgInput').value;

You know how I said that variables are like containers we put values in?

Copyright © 2017 Luke Fabish 150


Well those containers can hold more containers, and so on down. Just like the
Russian dolls.

Here’s what each part of document.getElementById(‘msgInput’).value; means:

• document: this is a reference to our HTML document js-intro-2.html. Yes!


JavaScript lets us play directly with the HTML document inside the browser.
• .getElementById: a function that belongs to document (containers can have
functions in them too). The parameter we give it (msgInput) is the id of our
HTML <input> (check the HTML again to see for yourself).
• So getElementById(‘msgInput’) is like a container for our HTML <input>.
• .value: This is the text you typed into the <input>.
• When we want to refer to a variable inside another variable (container inside
another container), we put dots between their names:
• outerContainer.innerContainer
• Container isn’t the correct word, but it’s a good way to think about these
things for now.

Phew. That’s the fundamental JavaScript machinery for getting an HTML element
(tag) from a page in the browser and doing something with it.

Finally, the last line of the function:

document.getElementById('message').innerHTML = msg;

We already know that document.getElementById is a function that gives us a


container for an HTML element.

This time we’re asking for an element with an id of ‘message’.

Quick! Check the HTML to see which tag that will be…

Ok, I hope you checked and saw that it’s the <h2> tag. This time though, we’re using
assignment (=) to put a value into our element’s innerHTML. innerHTML is
whatever is in between an element’s tags.

Remember when we assigned “Here’s lookin’ at you, kid.” to msg earlier, and then
assigned msg to document.getElementById(‘message’).innerHTML = msg;
Copyright © 2017 Luke Fabish 151
That was just like typing <h2 id="message"> Here's lookin' at you, kid. </h2> directly into
our HTML file.

Only now, msg has been assigned the value of whatever is in our <input> field.

Once we assign msg to the <h2>'s innerHTML, the <h2> will contain whatever the
<input> tag contains.

Golly.

Copyright © 2017 Luke Fabish 152


Key Takeaways:

• Variables are like a temporary container for storing something


• Variables let us pass values around with a label (like msg) without having to
refer to the actual contents of the variable
• Variables are declared like this: var variableName;
• We can use getElementById(id) to get a reference to an HTML element
• Remember an HTML element is a tag from an HTML file that’s been rendered
– displayed – in a browser.
• getElementById(id).value is what’s inside an <input> field. It’ll be nothing if
id isn’t an <input> field.
• getElementById(id).innerHTML = value put’s whatever is in value inside the
HTML tags of id.

Copyright © 2017 Luke Fabish 153


A simple abstraction with JavaScript
Learning goal: See how an abstraction can be used to hide complexity,
and isolate costly changes

You know, I really don’t like document.getElementById().

It’s long, ugly-looking and I usually mis-type it.

So let’s replace it with something nicer in our code:

<!DOCTYPE html>
<html lang="en">
<head>
<title>JavaScript Introduction</title>
<script type="text/javascript">

function updateMessage(){
var msg;
msg = getInput();
writeMessage(msg);
}

function getInput() {
return document.getElementById('msgInput').value;
}

function writeMessage(theMessage){
document.getElementById('message').innerHTML = theMessage;
}

</script>

</head>
<body>
<h1>HTML, meet JavaScript</h1>
<div>Get typing:</div>
<input id="msgInput" onkeyup="updateMessage()">
<h2 id="message"></h2>
</body>
</html>

This time only the JavaScript has changed. Update your file and reload it in your
browser. Everything should work just like it did before.

Our JavaScript has two new functions, and the updateMessage function uses them:

function updateMessage(){
var msg;
msg = getInput();
Copyright © 2017 Luke Fabish 154
writeMessage(msg);
}

function getInput() {
return document.getElementById('msgInput').value;
}

function writeMessage(theMessage){
document.getElementById('message').innerHTML = theMessage;

So updateMessage looks a lot more straightforward now. It declares msg, assigns


getInput() to it and then uses writeMessage(msg). That, I think, is more intuitive
than our previous version of updateMessage().

In fact, we’ve introduced a very simple abstraction. Which is to say invent a name
with meaning (getInput) to replace something that has no obvious meaning on its
own (document.getElementById…).

Let’s look at these new functions:

function getInput() {
return document.getElementById('msgInput').value;
}

This is the first time we’ve seen return in a function. We can explain the use of return
as follows:

alert("Hello Dolly");

Is exactly the same as:

function sayHello(){
return "Hello Dolly";
}

alert(sayHello())

It’s like saying that sayHello() is the same as “Hello Dolly”.

So in our updated code we’re saying that getInput() is the same as


document.getElementById(‘msgInput’).value.

The next function:

function writeMessage(theMessage){
Copyright © 2017 Luke Fabish 155
document.getElementById('message').innerHTML = theMessage;
}

takes a parameter theMessage and assigns it to the innerHTML of our <h2> tag, just
like we did before.

There’s not much advantage of using functions like these if we’re only going to use
them once.

But imagine if in our code we had to read from our <input> and write to our <h2> over
and over again.

By making functions with sensible names we make our code more readable and hide
complexity, which makes it more understandable.

We also avoid typing long, complicated pieces of code over and over
again. This reduces the opportunity for making mistakes.

Additionally, imagine if we did use these functions many, maybe hundreds of times.
And then we had to change where we get the input value from.

If we used document.getElementById(‘msgInput’).value everywhere in our code,


we’d have to make hundreds of changes.

If we replaced document.getElementById(‘msgInput’).value with a function, then we


only have to make the change in one place, inside the function. Our code can keep
calling that function getInput(), and benefit from the change.

Copyright © 2017 Luke Fabish 156


Key Takeaways:

• We can replace complex code with well-named functions


• This make our code more readable and understandable
• It saves us from coding errors
• It hides complexity
• It can save us from extra work in the future
• Assigning a meaningful name to a complex operation is an example of
abstraction.

Copyright © 2017 Luke Fabish 157


Enough already!
That’s a lot.

I mean an absolute ton.

And like I said before, don’t worry if you’re not feeling super-solid of some of the
more technical parts of what we’ve covered today.

If you’d like to feel more comfortable with these concepts – try playing with the code:
introduce new elements and new events. See what happens!

To recap, today we’ve covered:

• How HTML and JavaScript work together with events.


• How put JavaScript in an HTML web page
• How to write simple JavaScript functions
• How to use and define variables
• To we can change a web page with JavaScript
• How to use abstraction

I hope it’s been useful for you!

If you remember the Computational Thinking chapter, where we covered three


aspects of programming:

• Sequence
• Decision
• Iteration

We've just covered Sequence in this chapter. In the next chapter we'll be learning
about Decision.

Copyright © 2017 Luke Fabish 158


Copyright © 2017 Luke Fabish 159
JAVASCRIPT FOR
BEGINNERS: IF, THEN &
ELSE

Ready to get started on learning more fundamental JavaScript?

We covered some JavaScript basics in the previous chapter, and you should be
familiar with that before continuing. If you’re not, go check it out. I’ll be waiting right
here for you.

So now you’re totally familiar with executing JavaScript when a user types into or
clicks an element on a web page. You can make new functions with parameters, and
can use variables.

Let’s move on to the second major component of any programming language:


making decisions.

Programming your life with if-then decisions


We make decisions all day, every day, right?

If the weather’s nice, I’m going running.

If that $#@! lift doesn’t come after one more minute, then I’m taking
the stairs.

Decisions in programming are different, because we have to tell a computer how to


make a decision, and then what to do afterwards.

We give our decisions (and actions) to people all the time:


Copyright © 2017 Luke Fabish 160
If you don’t tidy your room, you’re not going to that sleepover!

If Jerry calls, tell him I’ll call him back after my meeting.

You might notice these decision and action pairs have


a common format:

if < a condition of some kind > then < some


consequence >

Most programming languages call these if-then


constructs, even though there’s not often a ‘then’!

There’s even an Internet service that does this for you,


called ‘IFTTT’: If This Then That. For instance, if your
fitness wearable (e.g. Fitbit) records a bad night’s
sleep, IFTTT puts a reminder in your calendar to go to
bed early the next night! Or more simply:

If I don’t sleep well, then remind me to sleep early the following night.

So that’s great, but we want to put those decisions into our programs.

Let’s start exploring JavaScript’s syntax for making decisions.

JavaScript syntax for if-then decisions


First thing to know is, JavaScript doesn’t use ‘then’, but some languages do. The
‘then’ part of the decision is implied.

This is how it looks:

if ( some condition ) {
do something
}

The parts that say ‘some condition’ and ‘do something’ aren’t actual JavaScript! We’ll
fill in those bits soon.

Copyright © 2017 Luke Fabish 161


The important thing to realise is that ‘some condition’ corresponds to the ‘Jerry
calls’, ‘clean your room’ portions of those earlier examples.

So we could re-write one of the earlier rules like this:

if( "Jerry calls" ) {


"Tell him I'll call back after my meeting."
}

Remember that we use { and } to group JavaScript commands together.

But this raises a question – how do we tell if a condition, like ‘Jerry calls’ – has
happened? What we really ask is how do we know it’s true.

So we can re-write the if statement like this:

if ( some condition is true ) {


do something
}

True and False with JavaScript logic


Now, we have to find a way to decide if something is true or not. Luckily, we don’t
need a polygraph machine for that.

Comparison operators

JavaScript has some special tools called ‘operators’. Some of them do simple math
for us, for example:

var sum = 4 + 5;

Here, we’re using the addition operator (+) to add two numbers together. If we give +
two numbers, it’ll add them together and return the result. In this case we use
assignment (=) to put the result in the sum variable.

What would you say sum is equal to (i.e. the same as)? I’d say 9 (hey, I didn’t even
use a calculator).

Copyright © 2017 Luke Fabish 162


But how do we ask the same question in JavaScript? We use the ‘equality’ (or equal-
to) operator, which looks like this: ===4

Like + , === takes two values. It checks the values to see if they’re the same. If they’re
the same, === returns True. Otherwise it returns False.

So if we want to check our sum is correct, we could do this:

var sum = 4 + 5;

if (sum === 9) {
alert("The sum is correct.");
}

In this case, === checks sum and 9, sees that they’re the same, and returns True. Our
if gets a True value between its parentheses () and lets us execute alert.

What if the code looked like this:

var sum = 4 + 5;

if (sum === 10) {


alert("The sum is correct.");
}

Would we see an alert?

No way!

The if statement would get False from sum === 10 and wouldn’t let alert be
executed.

Let’s try that out for real.

JavaScript If example
We should check out a working example to get an idea of how this works.

Here’s an HTML file to start with:

4 Most languages use ==, which exists in JavaScript as well and does nearly the same
job as ===. For complicated reasons, it's much better to use ===.

Copyright © 2017 Luke Fabish 163


<!DOCTYPE html>
<html lang="en">
<head>
<title>JavaScript IF Example</title>
<script type="text/javascript">

var sum = 4+5;

if( sum === 9 ) {


alert ("Sum is 9");
}

if( sum === 10 ) {


alert("Sum is 10"); // No it's not!
}

</script>
</head>
<body>
<h1>JavaScript IF example</h1>
</body>
</html>

Pop that into a text editor and save it as (for example) js-if-1.html. Then load js-if-
1.html in your favorite browser.

You should see a pop-up when you load the page – what does it say??

(Remember, when we put JavaScript in <script> tags that’s not inside a function,
that JavaScript will execute as soon as the page loads.)

What's next?

Just to get things rolling, how about you try changing the value of sum so that the
message “The sum is 10” is displayed in an alert.

Remember; make that message display by changing the value of sum,


NOT by changing the message in the first alert!

So how did that go? I did it by changing

var sum = 4+5;

to

var sum = 5+5;

Copyright © 2017 Luke Fabish 164


You could have just done this:

var sum = 10;

Or, much more inappropriately:

if( sum === 9 ) {


alert("Sum is 10"); // No it's not!
}

The point is, this is a way of manipulating the values in the if statement’s condition
so that the condition becomes true.

But here’s a question – what if we wanted both alerts to display: “Sum is 9” and “Sum
is 10”

Get to know some more comparison operators


So we met === before, which we can use to tell if two values are the same. But there
are other tests we can do as well.

What if we want to see if something is less than something else?

Like, is it bed time yet?

Let’s try some new code:

<!DOCTYPE html>
<html lang="en">
<head>
<title>JS Decisions</title>
<script type="text/javascript">

var oclock = 7;
var bedtime = 8;

if( oclock < bedtime ) {


alert ("Ok, just a *little* more TV...");
}

</script>
</head>
<body>
<h1>JavaScript If example number 2</h1>
</body>
</html>

Copyright © 2017 Luke Fabish 165


Hmmm, so what’s this < symbol? It’s
another logical operator like === , but we
use it to see if something is less than
something else. In this case we checked
to see if oclock, which is 7, is less than
bedtime, which is 8.

You may have met < in your math class. I


always used to remember it means ‘less
than’ because the < looks like a wonky
capital L.

Of course our < has a friend: > for greater than. And it works much the same way.
Let’s update our code:

<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript">

var oclock = 9;
var bedtime = 8;

if( oclock < bedtime ) {


alert ("Ok, just a *little* more TV...");
}

if( oclock > bedtime ) {


alert ("Ok, time for bed!!");
}

</script>
</head>
<body>
<h1>JavaScript If example number 3</h1>
</body>
</html>

So now we can see > in action!

But that’s not really what we want is it? We don’t want to wait until 9 o’clock, a whole
hour past bedtime. Even if we were taking minutes into account, wouldn’t it be better
to take action right on 8, rather than 8:01?

Copyright © 2017 Luke Fabish 166


To do this, we could do something like:

if( oclock < bedtime ) {


alert ("Ok, just a *little* more TV...");
}

if( oclock === bedtime ) {


alert ("Ok, time for bed!!");
}

if( oclock > bedtime ) {


alert ("Hey, it's waaaaaay past bedtime!!");
}

But less code is usually better, so let’s see what we can do about this.

Introducing the “or equal to” operators. Both < and > come with an ‘equal to’ variant.
Most programming languages express them like this:

<= : Less than OR equal to

>= : Greater than OR equal to

So let’s try out a shiny new greater than or equal to operator in our code. Update
your code and try it out in your browser:

<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript">

var oclock = 8;
var bedtime = 8;

if( oclock < bedtime ) {


alert ("Ok, just a *little* more TV...");
}

if( oclock >= bedtime ) {


alert ("Ok, time for bed!!");
}

</script>
</head>
<body>
<h1>JavaScript If example number 4</h1>
</body>
</html>

Copyright © 2017 Luke Fabish 167


But we can achieve the same result with even simpler code! Let’s see how.

Safety Nets with If Then Else


Let’s go back to an earlier example:

If the weather’s nice, I’m going running.

But if the weather isn’t nice – are you just going to stand in the rain like a zombie?

No! You’ll go inside and do something else, like read a book or binge-watch Game of
Thrones. Or something.

Anyway, when we make decisions in everyday life there’s often an implicit part of the
decision that gets left out: What happens when the criteria for the decision isn’t met.

In plain old English, we’d say ‘Otherwise…’, but most programming languages use
else.

So we started with the following to describe decision making in code:

if < a condition of some kind > then < some consequence >

Now we can add else to it:

if < a condition of some kind > then < some consequence >

else < some other consequence >

For example:

If the weather’s nice, I’m going running.

Else, I’ll stay in and watch G.O.T. until a favorite character is killed off.

So, what about our code? Let’s try this:

<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript">
Copyright © 2017 Luke Fabish 168
var oclock = 8;
var bedtime = 8;

if( oclock < bedtime ) {


alert ("Ok, just a *little* more TV...");
} else {
alert ("Ok, time for bed!!");
}

</script>
</head>
<body>
<h1>JavaScript If example number 5</h1>
</body>
</html>

You can see that else follows immediately after the if’s final }.

The else, like if, is followed by { and } with commands in between them. Once again,
we use them to group together the commands we want to execute when our else case
is true.

No, I didn't forget that question


Earlier, we were looking at this code:

<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript">
var sum = 4+5;

if( sum === 9 ) {


alert ("Sum is 9");
}

if( sum === 10 ) {


alert("Sum is 10"); // No it's not!
}
</script>
</head>
<body>
<h1>JavaScript IF example</h1>
</body>
</html>

And I asked – what if we wanted both alerts to display: “Sum is 9” and “Sum is 10”?

Copyright © 2017 Luke Fabish 169


Well, let me say right now that’s not a good question – how could Sum be both 9 and
10 at the same time?

How about checking if sum is more than 9 or 10? Now that we know about the >
operator, we’d do it like this:

var sum = 11;

if( sum > 9 ) {


alert ("Sum is more than 9");
}

if( sum > 10 ) {


alert("Sum is more than 10");
}

That might seem like a silly example – why do two tests? Couldn’t we just check if it’s
greater than 10, and then we know that it’s greater than 9 too!

These kinds of ‘threshold’ checks come up fairly often. One example is payroll:

• Did the employee work up to or more than 40 hours? Great, they get their
regular pay.
• Did they work more than 50 hours? Hmm, those extra hours get time-and-a-
half.
• More than 60 hours?? Time to call the employee’s manager!

We see similar examples for calculating taxes, sales bonuses and business KPIs as
well. So it’s not so crazy after all!

Testing for inequality


Sometimes, we just don't want to know when something === something. We want
the opposite!

Take this example:

var result = 0;

// Note: this function returns 0 on success, otherwise it returns one of


// 500 error codes that describe what kind of error occurred.
result = trickyOperationThatMayFail();

Copyright © 2017 Luke Fabish 170


Are we going to write 500 test cases to see if there was an error of any kind? I don't
think I want to do that; it'd be pretty boring, easy to get wrong, and hard to maintain.

We just want one simple check we can use to see if there was an error, and then keep
going.

You may be thinking, hey, let's just use < to check if the error code is less than 1
(therefore 0). But there's nothing stopping those error codes being less than
0! Before we get on to combining < and > to corral 0, there's a better option:

The opposite of === is !==

You can use !== just like ===, except that it means not equal. For instance:

var result = 0;

// Note: this function returns 0 on success, otherwise it returns one of


// 500 error codes that describe what kind of error occurred.
result = trickyOperationThatMayFail();

if (result !== 0) {
// The people who make tricky operations that return 500 different error
// codes are obligated to provide code that interprets them!
reportTrickyOperationError(result);
}

// We continue processing...

Closing out with If Then Else


So I hope you’ve found this chapter useful, and that you’ve had some practice using
if-then-else in your browser.

These kinds of constructs are fundamental to programming and the skills you’ve
learned today translate across nearly 100% of programming languages!

Now that we've dealt with decision making in JavaScript, it's time to move onto
Iteration.

Copyright © 2017 Luke Fabish 171


Copyright © 2017 Luke Fabish 172
JAVASCRIPT LOOPS: AN
INTRODUCTION TO THE
JAVASCRIPT FOR LOOP

Next we’re going to be checking out


JavaScript loops, particularly the simple
and ubiquitous JavaScript for loop.

First of all – do you remember what


loops are all about?

If not, you should also check out the


chapter on Computational Thinking
where we discuss repetition and
iteration.

For a quick recap – loops are simply a


tool for doing the same thing over and over again.

Why would you want to do that? Isn’t doing something once enough?

Well, probably the most common use of loops is to display a list of things: like every
time you open a spreadsheet.

Every spreadsheet you ever opened is a giant list of lists, and when you open it,
there’s a busy little loop taking each item from a list, and writing it to your screen,
and then moving to the next item.

Copyright © 2017 Luke Fabish 173


So, we’ll take a look at loops so you can learn how to make repetitive programming
tasks simple.

Here’s what we’ll cover:

• How loops are used in programming


• Different kinds of programming loops
• For loops in JavaScript
• The dangers of infinite loops

Let’s get started!

How loops are used in programming


One of the great saving graces of computers is that they don’t mind doing the same
thing over and over again, no matter how boring.

In fact, this is where their true power lies.

Want to multiply 109,420 and 308,155? Under the computer’s hood (if you will),
there’s no multiplication machine that’ll give you the product in one go.

Instead, the computer is going to add 109,420 with 109,420 and store the sum,
218,840.

Then add 109,420 to 218,840, and store the sum of that: 328,260.

And then do that 308,153 more times until it finally calculates the product
(33,718,320,100 in case you were wondering).

And that’s not even a very big calculation.

But as programmers, math like that is taken care of for us (unless you’re building a
new chipset from the ground up, in which case: good luck to you!).

But we still need to use loops in everyday programming.

A typical example is when we’re presented with an un-sorted list. Which is to say, the
things in the list are in no particular order.

Copyright © 2017 Luke Fabish 174


If we want to know if something’s in the list we need to check through the list one
element at a time. Like this:

List: apples, oranges, pears, bananas

Question: do we have grapefruit in the list? (You already know that’s not true, but the
computer doesn’t).

One approach is to check each item in the list consecutively, and see if it’s a
grapefruit:

List item 1: apples

Is apples equal to grapefruit?

No. Look at the next item.

List item 2: oranges

Is oranges equal to grapefruit?

No. Look at the next item.

List item 3: pears

Is pears equal to grapefruit?

No. Look at the next item.

List item 4: bananas

Is bananas equal to grapefruit?

No. Look at the next item.

There are no more items. And there are no grapefruit in the list.

Dang. No grapefruit. Anyway, if you’ve completed the other chapters you might have
an idea about how you’d turn that into a working program.

But what if the list had 2000 kinds of fruit in it? (Hey – there’s 1200 kinds of banana
alone!) Would you type out 2000 tests to see if one of them was grapefruit? I don’t
think so.

Instead we could do something like:

list: apples, oranges, pears, bananas, etc

Copyright © 2017 Luke Fabish 175


for each thing in list
is thing equal to grapefruit?
yes? stop looking.
no? go back to the 'for each' bit and keep looking.

In this case thing would be a variable. The first time the above executed, thing would
be “apples”. The second time it executed, thing would be “oranges”.

And so on, until the list was exhausted (in the sense we’ve checked all of it) or until
we find our grapefruit.

So, we still do our check each time, it’s just that we do it repeatedly.

And what’s the benefit of that?

Our code will work the same with a list of one item, or ten million items.

We only need to type out our checking code once. This saves time and reduces errors.

Copyright © 2017 Luke Fabish 176


Key Takeaways:

• Computers use loops extensively to implement fundamental functionality.


• We as programmers use loops as well.
• Loops are used to do the same thing over and over again.
• Using a loop saves us time and reduces errors.

Copyright © 2017 Luke Fabish 177


Different kinds of programming loops
In the previous example, I used the word ‘for’:

for each thing in list....

It’s a good word to use in a loop example, because for loops are the most common
and useful loops in programming languages.

Because we’ll be spending most of our time with the for loop, I won’t go into much
detail about it here, other than to say it’s useful when we know exactly how many
times we’re going to loop.

While loops

Another common loop construct is the while loop, which looks something like:

while something is true


do stuff

While loops are useful when we don’t know how many times we’ll loop, or if we want
to loop ‘forever’.

When wouldn’t we know how many times we’re looping?

Often when reading data from a file, or from a network connection. In these cases we
often can’t tell ahead of time how much data we’ll receive, so we’ll just keep going
round and round until we reach the end of the data:

while not end-of-file


read a little more from the file

(End-of-file is often abbreviated to EOF, so it’s common to see while not


inputFile.EOF….)

The other example I mentioned is looping ‘forever’.

Clearly, we don’t expect our computer program to see out the end of all eternity.
Forever in this case means that there’s no clear end for the loop.

Copyright © 2017 Luke Fabish 178


These are called ‘infinite loops’ and we’ll see why we have to guard against them
soon. But they’re often useful too. Here’s an example

while true
respond to user input

So true is always True, right?

That means this loop will go forever, and keep on responding to user input. It’s very
common to see these kinds of loops in the heart of graphically-based applications
(like web browsers). They just keep going around and around, waiting for you to click
or type, and then responding when you do.

How does it ever stop? Usually because the program receives a special signal (like
quitting or exiting the program) that makes it jump to a predefined section of code to
make sure it cleans up after itself (like deleting temporary files, finishing any output
it was doing, and so on). This kind of signalling is waaaaay outside the scope of
today’s chapter.

And finally, a not so common loop.

Do While loops

Sometimes these are called ‘Do Until’ loops. Here’s how it goes:

do
things
while something is true

This is kind of an upside-down while loop, right?

The big deal here is that our test is at the end of the loop, rather than the start.

This means that our things is guaranteed to execute at least once. With a regular
while loop, our things may never execute if our while loop’s truth test fails from the
beginning.

When would we use a do..while loop?

A classic example is evaluating user input as they type. In old-school command-line


programs, a user would be presented with a text-based menu and pick an option
Copyright © 2017 Luke Fabish 179
from it. We only want them to choose a valid option from the menu, and would have
done it like this:

print text-menu

do
get menu option
while menu option isn't valid

So if the menu looked like this:

(R)ead new messages

(V)iew old messages

(C)ompose new message

(Q)uit

The loop would continue until the user typed R, V, C or Q.

The do..while type construct isn’t so common because we can usually structure our
code so we can just use a while loop instead.

Ok, now it’s time to write some actual loops in JavaScript, but first:

Copyright © 2017 Luke Fabish 180


Key Takeaways:

• Programming languages share similar loop constructs


• The most common are for, while and .while
• For loops are often used when we know how many times to loop.
• While loops are useful when we don’t know how many times to loop.
• While loops are less common, but useful when we want our loop code to
execute at least one.

Copyright © 2017 Luke Fabish 181


How to write a for loop in JavaScript
The earlier example I used was in the form: for each thing in list…

This is an easier form to understand intuitively, but it presents a few traps in


JavaScript. Instead, we’ll look at a form that’s a little less intuitive upfront, but will
serve you better over time.

First, we need some HTML we can use to play with JavaScript:

<!DOCTYPE html>
<html lang="en">
<head>
<title>JavaScript For Loops</title>

<script type="text/javascript">
// Our loopy code is going to go here.
</script>

</head>
<body>
<h1>Fun with JavaScript <em>For</em> Loops</h1>
</body>
</html>

That’s an almost-empty piece of HTML. The only thing in the HTML body is an <h1>
tag.

Even though it doesn’t do anything yet, please type it into a text editor, save it and
then open it in your browser. You should see this:

Figure 59: Preparing for JavaScript for loops

Now, replace:
Copyright © 2017 Luke Fabish 182
// Our loopy code is going to go here

With:

var count;

for (count = 0; count < 5; count = count + 1){


alert("Hello");
}

Before we get into what it’s doing, save the file and open it in your browser. You
should see something like this:

Figure 60: An annoying loop exampe!

Remember, please don’t check that ‘Prevent this page from creating additional
dialogs’ checkbox if you see it – we need our dialogs!

Let’s take a look at our new code:

var count;

for (count = 0; count < 5; count = count + 1){


alert("Hello");
}

Copyright © 2017 Luke Fabish 183


The first line declares a variable called count. The next line is where it starts getting
interesting:

for (count = 0; count < 5; count = count + 1){

We can view this line like this:

for (initialize; decide to continue; advance){

Initialize means that we start at some initial state, or condition. In this case, we want
to make sure our count starts at 0.

Yes, we start at zero.

In the programming world, whenever we say we’re going to do something ten times,
we start at zero and count until 9. I know it’s weird, but you’ll have to get used to it :).

Once you start working with arrays, you’ll see why this is important!

Decide to continue is a test that comes out to True or False (like in the previous
chapter). This is how we decide to keep looping or not. In our example we used count
< 5 as the condition. So each time we loop, we check count, see if it’s less than 5, and
continue looping if it is.

Advance is where we do something that changes the circumstances of the loop. In


our first example, we used count = count + 1. What does this do? It adds 1 to count
each time we loop.

Now, how do these bits go together? In what order does our computer execute them?

We’ve got an initialization, a decision about whether to continue or not, and


something that advances the state of our loop. And of course we have the body of the
loop, in this case alert(“Hello”).

It goes a little like this:

Initialization
Decide to continue
Loop body
Advance

Copyright © 2017 Luke Fabish 184


So even though we use the for(…) construct to write the loop, this is how the
computer executes our code (in pretend pseudo-code, not JavaScript):

count = 0
Is count < 5 ?
alert "Hello world"
count = count + 1
go to line 2

Here’s our loop once again for comparison:

for (count = 0; count < 5; count = count + 1){


alert("Hello");
}

So why use the for construct at all? It’s less straight-forward than just doing
everything in order like our pseudo-code example. This is true, but it has the
following benefits:

We can understand everything about our loop from looking at one line of code. If the
loop body was 200 lines long, we’d have to search back and forth through the code to
know what’s going on.

It avoids the use of the pesky goto. Goto is synonymous with bad code, because
undisciplined programmers used it poorly in the past.

Because this is an exercise in learning about loops, and not just reading about them,
here’s a little exercise.

Please write down (anywhere you like), what the values of count will be each time the
loop executes.

Ok, done that?

Let’s update the code to check our answer. Please change your loop code to match
this (only one line, the loop body’s alert, has changed):

for (count = 0; count < 5; count = count + 1){


alert(count);
}

Now when our loop executes, we get something like this:

Copyright © 2017 Luke Fabish 185


Figure 61: Checking the value of our for loop counter.

Great. But using alerts for output is kind of annoying, right?

Let’s do something a little different. Our code changes quite a lot here, but I hope it’s
not unrecognizable. Please type this into a new file, save it with a new name, and
open the file in your browser:

<!DOCTYPE html>
<html lang="en">
<head>
<title>JavaScript For Loops</title>
<script type="text/javascript">

function loopExercise(){
var count;
var outputDiv = document.getElementById("for-loop-output");

for (count = 0; count < 5; count = count + 1){


outputDiv.insertAdjacentHTML("beforeBegin", "<br>Loop: " +
count);
}
}
</script>
</head>

Copyright © 2017 Luke Fabish 186


<body>
<h1>Fun with JavaScript <em>For</em> Loops</h1>
<a href="#" onclick="loopExercise()">Get loopin'</a>
<div id="for-loop-output"></div>
</body>
</html>

You should see something like this:

Figure 62: JavaScript loop output in HTML.

What’s changed? Let’s take a look.

First, our HTML has two new lines:

<a href="#" onclick="loopExercise()">Get loopin'</a>


<div id="for-loop-output"></div>

If you’ll recall, our <a> tags are called anchor tags, and are used for HTML links. If
you’ve read the previous chapters, the only thing that’ll be unfamiliar to you from
this:

<a href="#" onclick="loopExercise()">Get loopin'</a>

Is href=”#”. Here’s the thing about this link. We don’t want it to go to another HTML
page, but we do want it to look like a link. # is the one thing we can use that won’t
confuse your browser when you click on it.

Copyright © 2017 Luke Fabish 187


If we don’t set href at all, or give it an empty string, the browser won’t display it with
an underline, and your cursor won’t change into a little pointing hand when you
hover over the link.

So we want href=”#” in there. And of course, we want something to happen when we


click the link. That’s where onclick=”loopExercise()” comes in.

Also, we have an empty div element with an id set to for-loop-output:

<div id="for-loop-output"></div>

How is that used? To find out we’ll need to check out loopExercise(), which is part of
our JavaScript changes. Let’s take a look at those:

<script type="text/javascript">

function loopExercise(){
var count;
var outputDiv = document.getElementById("for-loop-output");

for (count = 0; count < 5; count = count + 1){


outputDiv.insertAdjacentHTML("beforeBegin", "<br>Loop: " +
count);
}
}

</script>

That’s all of our JavaScript. What’s different?

Well, we’ve wrapped it all up in a function called loopExercise(). That’s one less
mystery.

Besides count, we declare a new variable outputDiv, and use


document.getElementById(“for-loop-output”) to give it a value.

Remember, document.getElementById is a way to take something from our HTML,


and give it to our JavaScript to play with.

So now we have a variable outputDiv that refers to our empty div for-loop-output.

Here’s how we use it:

for (count = 0; count < 5; count = count + 1){


outputDiv.insertAdjacentHTML("beforeBegin", "<br>Loop: " + count);
Copyright © 2017 Luke Fabish 188
}

So the actual for loop construct hasn’t changed. We’re still using count in exactly the
same way.

But what are we doing to outputDiv?

outputDiv.insertAdjacentHTML("beforeBegin", "<br>Loop: " + count)

First, any time we use document.getElementById to get an HTML element, the


element comes with a bunch of functions attached to it. One of them is
insertAdjacentHTML.

Note that understanding everything about insertAdjacentHTML is not necessary for


learning about for loops in JavaScript. If it doesn’t make sense to you, don’t worry
about it.

Anyway, insertAdjacentHTML: As we saw from running our code, clicking Get


loopin’ made our loop execute and insertAdjacentHTML clearly put a bunch of stuff
on the page.

As you can see from our example, insertAdjacentHTML takes two arguments. We’ll
look at the second one first:

"<br>Loop: " + count

Because we’re inserting HTML directly into the web page, we can use <br>, which
tells the browser to start a new line, like pressing Return or Enter on your computer
keyboard.

Then we have the word “Loop: ” which you saw printed out in the browser in the
example. Finally, we stick count on to the end of it.

So our first loop prints “<br>Loop: ” + “0”, and the last loop prints “<br>Loop: ” +
“4” (Remember, with numbers, + adds them together. With strings, it sticks them
together. When we use + with a number and a string, JavaScript turns our number
into a string).

Whew!

Copyright © 2017 Luke Fabish 189


After all that, what’s the first argument for insertAdjacentHTML? It’s “beforeBegin”.
Remember that we’ve got a reference to a div HTML element? “beforeBegin” tells
insertAdjacentHTML to put our string (“<br> Loop” etc) just before the <div>
element.

Copyright © 2017 Luke Fabish 190


Key Takeaways:

• For loop statements have three parts: initialization, a conditional check to see
if the loop should continue, and something that advances the loop.
• The loop has a body, which is one or more statements that are executed while
the loop’s ‘continue’ condition is true.

Copyright © 2017 Luke Fabish 191


Infinite loops and other loopy pitfalls

Figure 63: You should stay out of infinite loops – but if you find yourself in one, you’ll learn a lot!

I mentioned infinite loops earlier in the chapter. This is where we’ll see how they
work and what else we should watch out for.

Let’s look at our for loop again:

for (count = 0; count < 5; count = count + 1){


outputDiv.insertAdjacentHTML("beforeBegin", "<br>Loop: " + count)
}

We know that count starts at 0, has one added to it for each execution of the loop,
and that the loop will only execute while count is less than 5. But what if we changed
the for statement to look like this:

for (count = 0; count < 5; count = count - 1)

It’s a tiny change. If you didn’t spot it, I changed the + to a -, so now instead of
adding to count on each iteration of the loop, we subtract from it.

What do you think will happen if you run that code? Well, it depends on your
browser. Firefox gave me this:

Copyright © 2017 Luke Fabish 192


And Chrome:

So clearly, that loop just runs and runs and runs and doesn’t stop until the browser
decides it’s had enough. We’re lucky we have browsers that take care of that for us.

Copyright © 2017 Luke Fabish 193


Some other programming environments make it very difficult to break out of an
infinite loop.

To avoid infinite loops, we need to check each part of our for statement very
carefully: the initialization, the check to continue, and the loop advancement.

Here’s something else to watch out for:

for (count = 0; count < 5; count = count + 1){


count = count – 1;
}

Uh oh, what’s going to happen here? Once again, our loop is never going to stop
because count is always going to be less than 5.

Actually, when we have a for loop that uses a variable like count to control the loop’s
iterations, it’s considered bad practice to change that variable inside the loop.

If we start changing the variables that control a for loop it becomes difficult to
predict the behaviour of the loop. If you need to skip an iteration of a loop, or jump
out of a loop early, do some googling for for loop continue and for loop break
statements.

Copyright © 2017 Luke Fabish 194


Key Takeaways

• Infinite loops may be useful sometimes, but they’re usually a mistake!


• They can be caused by setting up a for loop’s initialization, loop-condition or
advancement incorrectly.
• An infinite loop may be caused by changing the variable that controls the loop
inside the loop’s body.
• It’s bad practice to change the variable controlling a for loops execution.
• If you want to skip an iteration of a loop, or leave a loop early, try using the
continue and break

JavaScript For Loop Termination


So today you’ve learned how about the different kinds of loop available to us, you’ve
had a practice at writing some for loops (including how they work under the hood),
and the dangers of infinite loops and how to avoid them.

Coming up next, we'll take a break from JavaScript for a little while, and look at some
approaches to solving problems.

Copyright © 2017 Luke Fabish 195


Copyright © 2017 Luke Fabish 196
PROBLEM SOLVING
SKILLS: 5 STRATEGIES
FOR ANY PROGRAMMER

So I thought I’d spend a little time on a favourite topic of mine – problem solving.

As a programmer, solving problems is what you'll do when you get down to work.
The more problem solving skills and strategies you have, the better we’ll be.

The problem might be “how can I tell if this string contains a valid e-mail address”,
or “what’s the best way to process more transactions per second to solve this
latency problem our customers keep complaining about?”

They’re different classes of problem, but what I’ve found over the years is that I can
improve the quality of my solutions by applying some tactics to my problem solving,
and not just waiting for something to pop into my head.

So I’m going to cover a few of my favorites right here.

Problem solving skill 1: Make it smaller


This is the most fundamental approach to problem solving, and it should be the very
first thing we do.

Back in the day, it was called ‘decomposition’ which sounds kind of nasty.

But this is good! This is the process of breaking a problem into lots of tiny sub-
problems until we end up with a list of trivial problems that are easy to solve.

Let’s clarify with an example.

Copyright © 2017 Luke Fabish 197


We’ll imagine – for the sake of fun – that you’re going to build your very own
personal home accounting system: it’s going to produce a ledger report, graph
income and outgoings over time, and help you prepare your tax return.

That sounds like a lot! But let’s start breaking this down into smaller problems.

First smaller problem – the application will need to get its data from somewhere,
and an export from your bank is the perfect place to start.

One of the options your bank will probably provide is a CSV export of your
transactions. CSV stands for Comma Separated Values, and part of your CSV file
might look like this:

2016-08-02, 10:23:30, "-10.45", "7-11 BROADWAY 22034","+2241.34"

Meaning – on August 2nd 2016, 10:23AM you spend $10.45 at the 7-11 on Broadway,
leaving $2241.34 in your account.

So we’ll break our problem – getting the data – down some more:

• We need to open the CSV file


• Read each record in the file
• Break each record into individual fields
• Load the fields into a database record
• Close the CSV file

Breaking a problem down into small, discrete problems that can be solved one at a
time is how to build an entire application.

But what if you don’t know what the right solution is?

Copyright © 2017 Luke Fabish 198


Problem solving skill 2: The 3 x 3 method

Often we treat solutions to problems the same way we treat lost house keys – as soon
as we find them, we stop looking!

But problem solving is different to lost keys – we might not come up with the best
solution first off.

Actually, the first solution we come up with is often the most obvious – nothing
wrong with that – but once the obvious solution is out of the way, we can start
thinking of new and different things.

Often these turn out to be better solutions than the first thing that occurred to us.

So one actionable step you can take when you sit down to solve a problem is not
to stop until you come up with three different solutions.

This can be surprisingly hard to do – the resistance to keep on working on a problem


after you’ve solved it is powerful.

But if you do, you’ll encounter unexpected problem solving creativity.

Copyright © 2017 Luke Fabish 199


But this is the 3×3 method, right?

So your second actionable step can be thinking up three things that could go
wrong with each of your three solutions.

Boy, now doesn’t that sound like fun?

I think one of the hardest things in the world is to sit down and think really hard
about what might be wrong with our wonderful ideas.

But it’s worth it!

Once you do that, you’ll not only have thought through each of the solutions
thoroughly, you might realise that some of the problems you thought up can be
solved by combining your solutions into super-solutions, more robust and creative
than your first idea!

Problem solving skill 3: Know your solutions.


“There’s nothing new under the sun, boy.”

So I was told by an old analyst at my first job, squinting at me between his grey,
bushy eyebrows.

I didn’t believe it then, and I don’t now (even though my eyebrows are getting just a
little grey now).

But he did have a point.

A lot of the problems we come across in day-to-day programming life are tricky – we
wouldn’t be paid to solve them otherwise – but they’ve come up in the past and have
been solved.

And those solutions have been improved and improved until we’ve got something as
close as possible to a perfect solution for that problem.

And then some people started documenting those solutions.

Copyright © 2017 Luke Fabish 200


Some of you will be saying to yourself at this point – “hmm, sounds like design patterns…”
and you’d be right.

A couple years after the Gang of Four published their Design Patterns book (a
compendium of standard solutions to tricky problems) Design Pattern Mania took
over the industry for a while.

After the inevitable backlash design patterns lost a lot of their shine.

But I think they’re still a great tool to bring to problem solving – if we use them
judiciously.

By that I mean recognising that they’re designed for complicated problems and it’s
pointless to use them for everyday problems.

Normally, we’d only turn to a design pattern when our regular solutions come up
short.

If you want a good grounding in design patters, I heartily recommend the Head First
Design Patterns book (see the chapter on books I recommend to be a better
programmer).

It’s seriously one of the best books I’ve encountered for getting up to speed quickly
on a subject (and it was put together by the incredible Kathy Sierra, one of the
superstars of developer education).

Problem solving skill 4: Break taboos


So I totally acknowledge this is about to get weird. I’m sorry about that, but stick with
me.

I have a hypothetical problem for you.

Bad news: you’re locked in a cement cell with eight


other people.

Copyright © 2017 Luke Fabish 201


There’s a lead pipe set in the concrete floor, six
inches of the pipe is below floor level and six inches
of it is above floor level. There’s a ping pong ball at
the bottom of the pipe, and the pipe is slightly
wider than the ball.

The cell guard won’t let you and your eight friends
out until you give him the undamaged pingpong
ball.

You have a hammer, a chopstick and a shoelace to


help you retrieve the pingpong ball.

What are you gonna do? A solution is below, but spend some time coming up with
your own before you read it.

Copyright © 2017 Luke Fabish 202


Common solutions include: splitting the chopstick in two and attempting to
tweezer the ball out. Others involve mounting a frontal assault on the concrete floor
with the hammer to excavate the pipe from the floor.

How about another solution? (This is where it gets weird).

There’s you plus eight other people in that room. Sooner or later someone’s going to
have to pee. And you know, once one person goes, everybody will want to go.

And where will they do that?

How about the pipe? Once everyone starts peeing in the pipe, that ball’s going to float
on out, undamaged.

Gross, sure.

But the thing is, very few people discover that solution (if you’re one of them – well
done! I didn’t get it).

Why don’t many people think of it? It’s elegant, doesn’t require any of the tools you
were given (I mean “misdirected with”) and happily gets everyone out of the place
before it really gets stinky.

The reason most people don’t find that solution is that it involves a taboo – namely a
bunch of people using their pee constructively.

I found something interesting happened once I had cleared that taboo – I thought of
lots of new solutions to the problem that involved breaking other taboos.

But that’s not the kind of taboo we deal with in our professional lives (or I hope not!).
But there are other kinds of taboos:

“We don’t use Perl here.”

“You must always/never use foreign-key constraints.”

“Javascript is evil/our saviour.”

There are lots in the programming world. The question is, once we break the taboo,
what new solutions do we start to see?
Copyright © 2017 Luke Fabish 203
Problem solving skill 5: Know your problems
Finally, our last problem solving tactic isn’t about solving problems so much, as
recognising them.

Sometimes when I was presented with a problem I just had to dive in and fix it
straight away. Usually because it was my code that was causing the problem and I
was just plain embarrassed.

But sometimes it can be hard to separate a problem from a symptom.

A symptom, for example, was when, as a junior developer, my code one day started
showing out of date data to a customer. This was a big deal – the data was used by
our customer to make important business decisions, and if they lost confidence in the
data, they’d lose confidence in us.

I was getting the customer data from a cache used by our application. We used a
cache because it was expensive and slow to query the data. It looked like the cache
was out of date and had to be refreshed.

“Just refresh the cache before you fetch the data.


Why do I have to explain this to you?”

That was my boss, who was terrified we were going to lose some valuable business.

I hung up the phone and that’s what I did. Clearly, we had to make sure that
particular report had the most up-to-date information in it. Always.

Then a funny thing happened.

Other areas of the application started occasionally showing out of date data too.
‘Refresh the cache’ became a mantra and our cache quickly became useless as the
application spent all its time querying and re-querying the database.

Our technical lead, who’d designed the caching system in the first place, put a stop to
this and investigated what was going on in the cache.

Copyright © 2017 Luke Fabish 204


It turned out that the code that triggered automatic cache updates had a subtle, time
zone related bug in it.

Once that was fixed, we put an end to forced cache refreshes, and everybody was
happy.

So I think we have two actionable steps –

• Have the gumption to respect your own decisions and analysis when someone
senior is yelling at you.
• Think hard about how the problem you’ve seen occurred, and whether you’re
fixing it, or just putting a band-aid over it.

Conclusion
The main point here is that there are lots of ways to approach a problem, and that
circumstances will determine which you choose.

I think the most important thing to take away from this is that you should trust your
ability to understand problems and come up with creative, effective solutions.

Happy problem-solving!

Coming up next – we dive back into JavaScript and to look at arrays.

Copyright © 2017 Luke Fabish 205


Copyright © 2017 Luke Fabish 206


INTRODUCTION TO
JAVASCRIPT ARRAYS

I hope you’re well and ready to learn a fun concept that’s fundamental to
programming.

Today we’re going to check out arrays and build a slideshow project to practice using
them in JavaScript.

We’ve already looked at HTML, CSS, JavaScript basics, decision making in


JavaScript and JavaScript loops.

Now we’ll use a bit of everything while we explore arrays.

By the end of this chapter you’ll:

• Know what an array is.


• Know how to create arrays.
• Be able to retrieve single data items from an array.
• Access all items in an array.
• Know how array indexing works.
• Be able to use arrays in JavaScript.

So what’s an array?
First, let’s talk about what it’s not.

In JavaScript, we know how to make a new variable to store a string. We’d declare it
like this:

var myName = "Luke";

Copyright © 2017 Luke Fabish 207


And a number like this:

var myAge = 21; // Yeah right!

A variable that represent one, and only one value like those above, is called a scalar
variable (that terminology isn’t super important right now).

What if we want to store a bunch of names? Shall we have a bunch of scalar


variables? Like this:

var myName = "Luke";


var hisName = "Harry";
var herName = "Betty";
var yourName = "McGoodlookin";

Well, that’s one solution, but it’s pretty inflexible. What if we need to store more
names? We’d have to add a new variable for every new name. And when it comes to
using them, that’d be even more work.

What if we put all our names in a container, and get them out one at a time? That’s
an array.

In JavaScript, we could declare our list of names like this:

var nameList = ["Luke", "Harry", "Betty", "McGoodlookin"];

A note on notation – nearly all programming languages that use arrays use the
square brackets [ and ] for array notation. JavaScript is no exception, and when
you see [ and ], remember you’ll be dealing with something inside an array.

Great! Now we’ve got ‘nameList’ which is kind of like a shopping bag – you’re
holding one thing in your hand, but it lets you carry four things at once.

Copyright © 2017 Luke Fabish 208


Now we’ve got our array of names called nameList. That’s great, but how do we get
them back out again?

Copyright © 2017 Luke Fabish 209


Key Takeaways

• Arrays are used for storing multiple values


• We reference values inside arrays using the [ and ] characters.

Copyright © 2017 Luke Fabish 210


Getting items out of an array (and putting them in too!)
When we start pulling things out of arrays, we need to start talking about indexes and
elements.

This is some terminology worth learning.

Element – something that’s stored in an array. So we could say that ‘McGoodlookin’


is an element of the array nameList.

Index – the position of an element inside an array, and they always start at 0
(zero)2. It takes a while to get used to counting from 0, but you’ll get the hang of it.

Let’s revisit our array with index positions noted in a JavaScript comment:

var nameList = ["Luke", "Harry", "Betty", "McGoodlookin"];


// Index: 0 1 2 3

If we want the first element, we’d refer to it like this:

nameList[0]; // Yeah, the first element is 0.

So this would show an alert with ‘Luke’ in it:

alert(nameList[0]);

And this would show an alert with the last element (‘McGoodlookin’) in it:

alert(nameList[3]);

And what if we wanted to change an element? Let’s give my name a more


sophisticated spelling:

nameList[0] = 'Luc'; // So chic!


alert(nameList[0]); // Displays 'Luc';

Instead of talking about all this, let’s put it in a file and run it:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>JavaScript Arrays</title>
<script>

var nameList = ["Luke", "Harry", "Betty", "McGoodlookin"];


Copyright © 2017 Luke Fabish 211
alert(nameList[0]); // Displays 'Luke'
alert(nameList[3]); // Displays 'McGoodlookin'

nameList[0] = 'Luc'; // So chic!


alert(nameList[0]); // Displays 'Luc';

</script>
</head>
<body>
<h1>JavaScript Arrays</h1>
<div>This page just shows some alert() messages.</div>
</body>
</html>

Huzzah – you’ll see three alerts showing the contents of our nameList array.

There’s a much more common way of using arrays – remember the chapter on
JavaScript Loops? That chapter talks a lot about loops, and is practically bending
over backwards not to mention arrays!

But arrays and loops go together like puppies & chuckles.

So let’s see how we’d use our name array with a loop:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>JavaScript Arrays</title>

<script>
var nameList = ["Luke", "Harry", "Betty", "McGoodlookin"];
var loopIdx;

for( loopIdx = 0; loopIdx < nameList.length; loopIdx++ ){


alert(nameList[loopIdx]);
}

</script>
</head>
<body>
<h1>JavaScript Arrays</h1>
<div>This page just shows some alert() messages.</div>
</body>
</html>

If you haven’t already, pop that into a text file and load the file in your browser.

Here’s the interesting bit:

Copyright © 2017 Luke Fabish 212


var nameList = ["Luke", "Harry", "Betty", "McGoodlookin"];
var loopIdx;

for( loopIdx = 0; loopIdx < nameList.length; loopIdx++ ){


alert(nameList[loopIdx]);
}

First, we declare nameList as usual.

Then we declare a new variable called loopIdx.

Then we have our for loop:

for( loopIdx = 0; loopIdx < nameList.length; loopIdx++ ){


alert(nameList[loopIdx]);
}

You can see we start loopIdx at 0 and test it against nameList.length.

Yes, all arrays in JavaScript have a handy attribute called ‘length’ which we can
access as array-name.length. Super handy.

Finally, loopIdx++ is shorthand for loopIdx = loopIdx + 1.

And as I’m sure you saw when you loaded and ran the code, we saw an alert display
for each of the names in our array.

And now, let’s see if we can do something a little more useful with arrays.

Copyright © 2017 Luke Fabish 213


Key Takeaways

• Something stored inside an array is called an element.


• The position of an element inside an array is referred to as an array index.
• Array indexes start at 0 (zero).
• Arrays are often processed with for loops.
• In JavaScript, an array’s length attribute tells us how long an array is.

Copyright © 2017 Luke Fabish 214


Making a simple slideshow with JavaScript
Let’s ditch the alerts() and play with some pictures. This time we’ll be using HTML,
CSS and JavaScript together.

We’ll do things a little differently this time, and not put all of our CSS and JavaScript
into one file with our HTML. This is a more professional approach and makes it
easier to manage our code.

Let’s get started with some CSS. Please save this in a file called slideshow.css:

body {
/* Use a default sans-serif font, like Arial or Helvetica */
font-family: sans-serif;
}

#slideshow {
/* Use flex to centre our buttons vertically */
display: flex;
}

/* Make a div act like a button */


.navbutton {
/* Show a little pointing hand when the mouse cursor is over
this element */
cursor: pointer;

/* Shorthand to set margin-top and margin-bottom to 'auto', and


margin-left and margin-right to 0.*/
margin: auto 0;

/* Shorthand to set padding-top and padding-bottom to 0, and


padding-left and padding-right to 10px */
padding: 0 10px;

/* Super-big font size for our 'arrows' (> and < characters) */
font-size: 6em;

/* Set the arrows to a light-grey colour. */


color: #aaa;
}

.navbutton:hover{
/* When hovering over the arrows, make them black */
color: #000;
}

I’ve added CSS comments to all of the CSS, but let’s have a quick talk about some of the CSS
we haven’t covered yet.

Copyright © 2017 Luke Fabish 215


Flex

First: we set display: flex in the style rule for #slideshow. The ‘flex’ stands for flexbox,
which is a new model for laying out elements in HTML pages.

The main advantage of the flexbox model is that it lets us arrange elements to the
right, left or middle without weird side-effects. It’s still fairly new, but has support in
most modern browsers.

The most important thing to note here, is that we


set #slideshow’s display to ‘flex’ to change the
behaviour of its children; that is, our two navigation
buttons.

Margin and Padding Shorthand

When we use style rules like margin: auto 0; and padding: 0 10px; as we did for
.navbutton, we’re using a kind of shorthand to set margin-top, margin-right,
margin-bottom and margin-left, and similarly for padding. The shorthand goes like
this:

rule: top right bottom left;

So padding: 10px 20px 30px 40px; is equivalent to

padding-top: 10px;
padding-left: 20px;
padding-bottom: 30px;
padding-left: 40px;

The fun part is that leaving a number out means that it’s automatically assigned to
the other side of the box.

For instance, margin: 0; sets top, right, bottom and left to 0.

margin: 5px 10px; means we’ve set the top and the right, but not the bottom and the
left, in this case, the bottom get the top’s value (5px), and the left gets the right’s
value (10px).
Copyright © 2017 Luke Fabish 216
auto means take up all available space. When we tell the browser to assign all
available space to the top and bottom (magin: auto 0;), then the browser assigns
equal space to the top and bottom, putting the element right in the middle.

The :hover pseudo class

Finally, we have the .navbutton:hover rule.

:hover is what’s known as a CSS pseudo class. I don’t really know why they’re called
pseudo, but they define styling actions based on behaviour.

In this case, we want our navbutton to change colour from light-grey to black when
the user hovers their mouse over it.

The Slideshow JavaScript

Here’s what’s going to happen.

We’ll store some references to pictures in an array. We’ll display a new image every
time the user clicks a forward or backward arrow.

This means we need to keep track of what picture we’re up to in the array.

If our user clicks the backward arrow, we move one step back in the array. For the
forward button, we move one step forward in the array.

Let’s see how we do it. Please save this in a file called slideshow.js:

var currentImageIdx = 0;
var imageLocation = "http://lukefabish.com/example-images/";
var imageSet = ['1.jpg', '2.jpg', '3.jpg', '4.jpg'];

function nextPicture(){
currentImageIdx = currentImageIdx + 1;
if( currentImageIdx == imageSet.length ){
currentImageIdx = 0;
}
updatePicture(currentImageIdx);
}

function prevPicture(){
currentImageIdx = currentImageIdx - 1;
if( currentImageIdx < 0 ) {
Copyright © 2017 Luke Fabish 217
currentImageIdx = imageSet.length - 1;
}
updatePicture(currentImageIdx);
}

function updatePicture(idx){
var imgEle = document.getElementById("sl-picture");
imgEle.src = imageLocation + imageSet[idx];
}

So what’s our code doing?

We start by initialising some variables:

var currentImageIdx = 0;
var imageLocation = "http://lukefabish.com/example-images/";
var imageSet = ['1.jpg', '2.jpg', '3.jpg', '4.jpg'];

currentImageIdx keeps track of where we’re up to in the array.

imageLocation is where to find the images. If you want to use your own images, the
easiest thing you can do is put your images in the same directory as slideshow.js and
set imageLocation to “./”

imageSet is an array of image names. These are the images we want in our slideshow.
Again, if you want to use your own images, change the names from 1.jpg, 2.jpg to
whatever file names your images have.

Next, we have a function that moves us to the next picture:

function nextPicture(){
currentImageIdx = currentImageIdx + 1;
if( currentImageIdx == imageSet.length ){
currentImageIdx = 0;
}
updatePicture(currentImageIdx);
}

Let’s take a look at what nextPicture() does.

First, it adds one to currentImageIdx. Having done that, it uses an if statement to see
if currentImgIdx is equal to the length of our image array imageSet. Since we know
the length of imageSet is 4, then there’s no element at position 4, we only have
images at positions 0, 1, 2, and 3. So if currentImgIdx is 4, we need to go back to the
start, and set it to 03.

Copyright © 2017 Luke Fabish 218


After that, we call another function called updatePicture(), passing in the current
value of currentImgIdx. We’ll go over updatePicture() shortly.

The next function is prevPicture:

function prevPicture(){
currentImageIdx = currentImageIdx - 1;
if( currentImageIdx < 0 ) {
currentImageIdx = imageSet.length - 1;
}
updatePicture(currentImageIdx);
}

This is just like the opposite of nextPicture: it subtracts 1 from currentImageIdx.

Then it uses an if statement to see if currentImgIdx is less than 0. If it is, we need to


go to our last image, which will be equal to the array length minus 1 (array length is
4, so currentImageIdx would be set to 3.

Once again, we call updatePicture, so it’s time we took a look at it:

function updatePicture(idx){
var imgEle = document.getElementById("sl-picture");
imgEle.src = imageLocation + imageSet[idx];
}

Previously, we’ve seen how document.getElementById() returns a reference to a


piece of the HTML web page.

In this case we’re asking for a reference to an element with an id of sl-picture.

I know for a fact that our HTML has an <img> tag with id=”sl-picture”, so having got
a reference to our img tag, we set its src attribute (i.e. what image it should display)
to imageLocation +imageSet[idx];

What’s going on there? Well, we know in this case that imageLocation is


“http://lukefabish.com/example-images/”. If we passed currentImgIdx in with a
value of 2, then the idx parameter in updatePicture will be equal to 2. Which value in
imageSet is in position 2? It’s ‘3.jpg’.

What we end up with is “http://lukefabish.com/example-images/” + “3.jpg” which


comes out as one big long string: http://lukefabish.com/example-images/3.jpg.

Copyright © 2017 Luke Fabish 219


Put that in your browser and see what you get. That’s what our HTML <img> tag
would display.

Clearly, it’s time to look at our HTML.

Slideshow HTML

Finally. The HTML. Please put this in a file called slideshow.html, and then open it
in your browser:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>Slideshow with a JavaScript Array</title>

<script src="slideshow.js"></script>
<link rel="stylesheet" type="text/css" href="slideshow.css" />

</head>
<body>
<h1>Slideshow with a JavaScript Array</h1>

<div id="slideshow">
<div class="navbutton" onclick="prevPicture()"><</div>
<img id="sl-picture" src="http://lukefabish.com/example-
images//1.jpg" >
<div class="navbutton" onclick="nextPicture()">></div>
</div>

</body>
</html>

You should see something like this (assuming you’re using the pictures I provided):

Copyright © 2017 Luke Fabish 220


Let’s take a look at our HTML. First, the unfamiliar bits:

<script src="slideshow.js"></script>
<link rel="stylesheet" type="text/css" href="slideshow.css" />

As I said, previously we’ve put all our CSS and JavaScript and HTML into one file.
This is ok for very small projects, but things get out of hand pretty quickly for large
projects. So this is how we reference JavaScript and CSS files we want to use in our
HTML.

Sadly, you can see we’ve got two completely different ways of doing the same thing.
With JavaScript, we need an opening <script> tag with a src attribute that points to
our JavaScript file. Then we need that closing </script> tag, which does…nothing,
except make our HTML valid!

Copyright © 2017 Luke Fabish 221


To use external CSS, we need to use the <link> tag with attributes rel=”stylesheet” to
tell the browser what we’re linking to, type=”text/css” to tell the browser how the
stylesheet is going to arrive, and finally a href attribute set to the location of our CSS.

Finally, you can see that the link tag doesn’t require a closing tag, it self closes with a
forward-slash: <link … />

(The one thing you won’t get programming for the Web – consistency)!

Let’s look at the next juicy bit:

<div id="slideshow">
<div class="navbutton" onclick="prevPicture()">&lt;</div>
<img id="sl-picture" src="http://lukefabish.com/example-
images/1.jpg" >
<div class="navbutton" onclick="nextPicture()">&gt;</div>
</div>

There’s our slideshow div, which is holding two divs and an img.

Notice that the div tags before and after the image have the class navbutton.
Remember this is the class we discussed in the CSS section. Each of these divs has an
onclick event handler, respectively prevPicture() and nextPicture(), which we
discussed in the JavaScript section.

One mystery are the values sitting inside the navbutton divs: &lt; and &gt;
respectively.

If you’ve already loaded this file in your browser, you’ll already know that they’re <
and >. But what’s with the &lt; and &gt;?

This is a special encoding we use to avoid confusing the browser. If we put a bare >
or < in our HTML, the browser will thing it’s about to get a new HTML tag.

But of course it’s not going to in this case, we just want to display a > or <. Using the
encoding form & + code + ; is how we get around it. In this case, the code is ‘lt’ for
less-than, and ‘gt’ for greater-than.

And let’s look at our img tag. It has id=”sl-picture” which we saw referenced in the
updatePicture() function.

Copyright © 2017 Luke Fabish 222


So this is the element that function uses. You can see that its src attribute has been
given a default value. This is so that it displays something when the page first loads.

And that’s all there is to the HTML.

Copyright © 2017 Luke Fabish 223


Key Takeaways

• We have another layout model available to us: flexbox, which lets us put page
elements in the left, right or center of a page, without weird side-effects.
• There’s a shorthand for margin and padding CSS style rules: margin: top right
bottom left;
• CSS has pseudo classes that change an elements style based on user-
behaviour.
• The CSS pseudo class :hover changes the style of an element when the user
positions their mouse cursor over the element.
• We can include CSS in an external file in our HTML using the link tag: <link
rel="stylesheet" type="text/css" href="external-file-name.css" />
• We can include JavaScript from an external file in our HTML using the src
attribute in the script tag: <script src="javascript-file-name.js"></script>

Summary
So, in this chapter we’ve:

• Learnt what an array is,


• Seen how to create arrays.
• Practiced getting elements out of arrays, and putting them into arrays as well.
• Used a for loop to go through all the elements in an arrays.
• Learnt about array lengths and array indexing.
• Made a little slideshow application using arrays.

That’s plenty for an introduction!

Copyright © 2017 Luke Fabish 224


Practice Challenge #1

It's time to have a crack at some problems on your own. I'll present a practice
challenge here for you to try on your own, and put my solutions in the appendices.

Let's start on the first one.

The About Page – HTML and CSS practice


Everyone needs a cool 'About' page, right? Well here's one I whipped up earlier.

The main point here is to get the layout as close to identical to that
presented below.

It's very common to receive a project in the form of a PhotoShop document (or
Sketch these days), or as a mockup put together in MS Word with notes on functional
requirements.

So, this might seem weird, but it's good practice.

Remember, I'll have a couple hints at the bottom of this section.

Here's the first screenshot show how the page would initially load:

Copyright © 2017 Luke Fabish 225


Figure 64: When the about page initially opens. So serious.

And when the user puts their mouse over the photo:

Copyright © 2017 Luke Fabish 226


Figure 65: When the mouse cursor hovers over my picture. Happy times!

Charming, I know.

Anyway, here's what you need to know to get this done:

• The font for <h1> and <h2> is Georgia.


• The font for everything else is Arial or Helvetica (depending on your system).
• That cyan-ish color used for the h1 and h2 tags can be set in CSS with the color
#00ffe4.
• This is implemented is HTML and CSS only.
• The image is displayed as a background image for a <div>, not an <img> tag.

Copyright © 2017 Luke Fabish 227


• I suggest you use your own images!
• A <div> needs height and width to display a background image.
• Everything will be easier if your image and the div displaying it are the same
size (they're 500px high and wide in the example above).

Try implementing it on your own first! You may have to do some Google searches to
get it done. That is 100% normal for any professional developer. Then, check out the
solution at the back of the e-book.

Good luck!

Copyright © 2017 Luke Fabish 228


Practice Challenge #2

Even though you'll need to use some HTML and CSS to get this done, this is mostly
about JavaScript practice. So it's most important that it functions properly. If you
match the way it looks as well, that's great.

This is home-made version of a Captcha form that's designed to stop bots


(automated processes) filling your website comments up with marketing spam for
overseas medical products.

The idea is this: if this section of a form isn't filled out correctly, the rest of the form
is not submitted to the server.

The screenshots follow, and I'll provide some hints afterwards:

Copyright © 2017 Luke Fabish 229


Figure 66: The robot test when it initially loads.

Copyright © 2017 Luke Fabish 230


When the user enters a correct answer:

Figure 67: Apparently the user is not a robot.

And when the user enters an incorrect answer:

Copyright © 2017 Luke Fabish 231


Figure 68: The user is a robot, or they're as good at math as I am.

Hints:

• The answer is checked in JavaScript only. There's no need to submit anything


to a server to check the result.
• The two numbers to be multiplied should be different each time the
form loads. You can generate random numbers between 1 and 10 in
JavaScript like this:

Math.floor((Math.random() * 10) + 1);

• <input> form controls will always return a value as a String, even if their type
is set to 'number'. You can convert a string to a number in JavaScript using
the parseInt() function, like this:

parseInt('10'); // Returns the number 10

• To get a JavaScript function to execute automatically when a page loads use


window.addEventListener() like this:

window.addEventListener('load', yourFunctionGoesHere);

• Now, when the page loads, the function yourFunctionGoesHere will execute.
Note that yourFunctionGoesHere must be specified without parentheses - '('
and ')'.

Good luck! Once again, try on your own first and then use Google if you have to.
My answer is again at the back of the e-book.

Copyright © 2017 Luke Fabish 232


const bookFinished =
True; // The End.

Congratulations! If you've come this far, you're a determined learner and bound for a
successful career as a web developer.

Since this e-book has been written for absolute beginners, I assume you started with
nothing. But look at what you're leaving with! You've learnt:

• How to make web pages using HTML


• To use CSS to make web pages look good.
• How HTML Forms can be used to send data to other web sites, and to get data
from them as well.
• How to write programs in JavaScript that make decisions and execute loops.
• Finally, how to think and solve problems like a programmer.

That last point is a given, because you are a programmer now.

But you've set foot into a very fast-moving space. The web development world is
changing constantly and those who stop learning are quickly left behind.

So while you've made an excellent start, I hope you're committed to learning for life,
just like the rest of the professional development community.

I wish you luck on your web development journey.

PS: Want to stay in touch?


If you'd like short, punchy tutorials to get on top of tech topics quickly, please check
out my YouTube channel and subscribe if you like what you see!

Copyright © 2017 Luke Fabish 233


Copyright © 2017 Luke Fabish 234
Appendix A: HOW TO EDIT
TEXT ON A MAC

Copyright © 2017 Luke Fabish 235


Hello and Welcome to what will probably be the weirdest thing I ever write.

Copyright © 2017 Luke Fabish 236


Sadly, I find it necessary to write up some instructions on how to reliably edit text on a Mac.
Windows users, bless ‘em, don’t have this problem. They can always use the Notepad.exe
application, or the free and awesome Notepad++ editor.

But Mac users don’t have those options for text editing.

And by editing text, I mean just text. No formatting, fonts, different point sizes.

Just. Pure. Text.

No word processors. Text.

Why text? Because that’s what we feed into development tools and web browsers. Pure
information.

We use it to encode instructions to make computers do what we want.

Development tools aren’t even capable of ignoring the formatting that comes out of a word
processor. It just confuses them.

For many years I’ve been using Vim to do all my text editing. It’s my first choice after a full-
featured IDE. And I’ll even install Vim keyboard bindings in the IDE (i.e. make my IDE editor
behave like Vim).

Imagine my horror when I discovered that the default text editor on Mac OS X 10.11,
TextEdit, no longer supports plain text editing by default.

It uses Rich Text Format instead (Hey Apple! Look at the name: TextEdit!)

How we make it use pure text is not at first obvious.

This means that anyone who wants to write a simple script, HTML or CSS doesn’t have an
GUI application that’ll do it out of the box on Mac OS X.

Sigh.

Copyright © 2017 Luke Fabish 237


So this is what I’ll cover as we talk about text on Mac OS X.
• I’ll go over how we can make TextEdit use plain text, either for a single file or always.
• I’ll check out a solid third-party option that’s free, simple and just powerful enough.
• Finally I’ll take a look at my favorite, MacVim, and see if I can convince you to invest
some time in learning it.

And what do you get out of this?


You’ll know what options you have for editing plain text on a Mac (again, crazy you’d have
to read up on this).

You’ll also know all about the third-party options that are free and massively improve on
TextEdit.

Text Editing on Mac – TextEdit


So I think I’ve whined enough about TextEdit now. Nobody likes a sore loser, and I sure feel
like I lost something.

Anyway. TextEdit.

Let’s take a look at an example, a tiny web page:

<!DOCTYPE html>
<html lang="en">
<head><title>Example with TextEdit</title></head>
<body>
<span class="Apple-converted-space">&nbsp; </span><p>A tiny web
page.</p>
</body>
</html>

If we open TextEdit, save the above (TextEdit will force you to use an .rtf extension), and
then point a browser at it, what do you suppose we get?

Copyright © 2017 Luke Fabish 238


If we want our HTML to be treated as HTML, this is what we need to do.

Start a new file. The old previous file can’t be saved as an HTML file. Put the above HTML in
it.

Go to the Format menu and select Make Plain Text:

Copyright © 2017 Luke Fabish 239


Save the file as example.html. Open it in a browser, and hey-presto:

But who wants to do that every time we edit a file? Not me, for one.

How to set up Text Edit to always be text-only

So to avoid setting every file you edit in TextEdit to be text-only, here’s what we do.

First, start up TextEdit. Then open TextEdit’s Preferences:

Copyright © 2017 Luke Fabish 240


Then, in the Format section at the top, choose Plain text, as shown below:

Copyright © 2017 Luke Fabish 241


Close the Preferences window, and you’re done!

Text-only editing forever.

The thing is, we can do way better than TextEdit for editing our code. TextEdit will do in an
emergency, but we deserve better for serious coding.

TextWrangler. The Small, Simple, Text Editor for Mac.


This is what TextWrangler looks like with an HTML file:

Copyright © 2017 Luke Fabish 242


Note – we’ve got line numbers, syntax coloring, multiple documents open, and all in a
reasonably clean interface.

While there’s a lot of weird stuff in the menu bar (I’ve never used the #! menu), you can
ignore anything that doesn’t make sense.

Just use it to create, open, edit and save text files!

You can learn the rest as you go.

Here’s how to install TextWrangler:

Go to the download page at the Bare Bones web site.

And click Download (the first one, shown below):

Copyright © 2017 Luke Fabish 243


So that’ll download a file called TextWrangler_n.n.n.dmg, where that n.n.n is a version
number. Currently the version is 5.0.2, and the file looks like this: TextWrangler_5.0.2.dmg

That file will end up in your Downloads folder. Double-click it to open it, and then do like it
says and drag the application to your Applications folder:

Copyright © 2017 Luke Fabish 244


From then on you’ll be able to run TextWrangle from your applications folder.

The first time you run it you’ll see a message asking you if you’re certain you want to
execute it since it was just downloaded from the Internet – that’s totally normal!

TextWrangler is a superb option for editing text files while coding.

But if you’re feeling brave, we can go one better.

Vim on the Mac – Get ready for an adventure!


So first, what’s this Vim business?

Does it help to know Vim stands for Vi-Improved? No? How about that Vi was short for
Visual Editor, and invented in 1976?

Still no? Well, it hardly matters.

Copyright © 2017 Luke Fabish 245


The main point is that this dinosaur of a text editor has made it all the way into the modern
world because it’s so awesome nothing quite beats it. Like a crocodile.

Hmmm. Well, we better follow that up with an example.

Here we’re not using Vim for programming, but for one of those everyday tasks that come
up in work life. The file is a 1000 records of bogus sales data. Let’s imagine it came in from
some store creating manual records and the data’s in a bad way. We need to fix it! Enter
Vim.

Check out this video (http://bit.ly/2nybEoX) demonstrating that task in a few


commands.

So clearly, Vim confers superpowers upon those willing to learn.

How to install MacVim


I heartily recommend MacVim, which is an excellent Vim implementation that makes some
lovely concessions to help Mac users.

Download it here:

https://github.com/macvim-dev/macvim/releases

You don’t need to make sense of everything here. Just know that there are frequent
releases of Vim, they’re called snapshots, and the most recent one is at the top of the
releases page.

So click the first MacVim.dmg link on this page:

Copyright © 2017 Luke Fabish 246


Once that’s finished downloading, find MacVim.dmg in your Downloads folder, and double
click it.

So now we get this:

Copyright © 2017 Luke Fabish 247


Drag the MacVim.app file to the Applications folder. You’ll be able to run it from your
applications folder, just remember you’ll get a warning the first time because you
downloaded it from the Internet.

So run it!

Copyright © 2017 Luke Fabish 248


Now what do you do with it? You better start here.

Learning Vim is a long, long and windy road. But, really worth it in the end, because nobody
will be able to do what you do, except other Vim users.

Conclusion
So there we have it! The appendix that should never have to have been written.

We’ve had a look at three options for editing text on a Mac: reconfiguring TextEdit,
TextWrangler, and MacVim.

I hope you find a choice that suits you, and if you’re not on a Mac, count your blessings.

Copyright © 2017 Luke Fabish 249


Appendix B: BOOKS TO
MAKE YOU A BETTER
DEVELOPER

Copyright © 2017 Luke Fabish 250


Being a developer means that you’re on a life-long learning journey. I think that’s a journey
everyone should be on, but in the software world it’s mandatory.
Copyright © 2017 Luke Fabish 251
Your current knowledge has a half-life of around five years – i.e. half of what you know now
will be of no value to you in five years.

Brutal, I know.

But this isn’t a world for folks who don’t like to learn new things. Personally, I love learning
new stuff.

Today I’ll be talking about specific books you can use to learn new skills that’ll give you
knowledge I believe will survive your whole career – and I hope that’s longer than five
years!

Take control of your learning


But are books the best way to learn? Actually, I don’t think so.

I think the learning experience is way better when content is taught in-person by an expert,
and you’re learning in a group environment.

That’s a course, and these kinds of courses can be pretty pricey.

When your employer pays for them that’s great! But in this case it’s because your employer
wants you to learn something to add value for the employer, not necessarily for you.

But that’s still not the best way to learn.

For me, the best learning happens in a workplace where best practices are the norm, your
team has high expectations for the quality of your work, and processes and mentors are in
place to help you achieve high standards.

Sadly, those kinds of workplaces aren’t common at all. If you’re not in a situation where
your professional development is taken care of by the business, you need to take care of it
yourself.

So, books.

Copyright © 2017 Luke Fabish 252


They’re not cheap, but you can get a lot of value out of them if you’re willing to put the
work in.

How to get the most out of a book


Depends on the book. But regardless of the kind of book you’re learning from, it’s worth
putting in some time and effort to get the most out of it – reading the book is just the start!

Learning from technology books

If it’s a “Learn technology X” type book where you’re learning a new programming language
or tool, the book will undoubtedly have exercises and examples to work through.

Do the exercises.

Working through the exercises in these kinds of books will increase your learning massively.
It’ll also give you hands-on experience installing and working with the tooling that supports
the new technology.

And if the book has a companion website, please don’t download the code for the
examples.

Unless it’s approaching a thousand lines of code (and I’ve never seen that much code in one
example), you’ll be better off typing the code straight out of the book.

Laborious, I know.

But pecking away at the keyboard will force you to notice small details in the code that are
otherwise easy to miss if you’re just reading the code – something I’ve learned from painful
experience :/

Finally, think of a small project you can use the new technology in. Even trivial projects will
shine light into the dark corners of new technologies that some book authors like to gloss
over!

Copyright © 2017 Luke Fabish 253


Learning from theory and concept books

You’ll notice that the three books I’m discussing today are all theory and concept-type
books. These are the kinds of book that survive that five-year half-life we were talking about
earlier.

This is different to the standard technology book. They often won’t have exercises, just
summaries.

So what’s the best way to bed down your new knowledge, and make it your own?

This comes down to your learning style. Personally, writing things down is how I understand
and remember new knowledge.

Some people have to make pictures, like mind-maps. Others like to talk about what they’re
learned to someone else.

I love writing things down in a basic workbook because:

It becomes a record of what I’ve learned.

Even if I don’t remember something very well, I can refer back to my notes to find out
where I learned it so I can go and refresh my memory.

I have a place to write down questions that spur further research.

It’s a place to record epiphanies – those golden a-ha! moments where a whole area of half-
understood concepts swim into focus.

So I recommend to at least start by keeping a written record, and try new stuff from there
to find out what works best for you.

Finally, think hard about how you can use your new knowledge straight away. Maybe there
are situations at work or with your personal projects you can improve?

Doing this will really cement your new skills and will make you a practitioner of the new
topic, instead of someone who just read a book about it!

Copyright © 2017 Luke Fabish 254


Books that’ll make you a better programmer
Let’s get to the books already.

These are books that I’ve personally read, and personally recommend.

Head First Design Patterns

Copyright © 2017 Luke Fabish 255


I’ve written about design patterns previously, and I think they’ve got a lot going for them if
they’re used judiciously.

The thing is, even if you never implement a design pattern in your life, a lot of design
patterns have been baked into programming language frameworks and application
containers.

Recognising and understanding these design patterns will make your life a whole lot easier
when you encounter them.

For that reason alone they’re worth learning. And if you learn to use them right, you’ll be a
better developer.

And why Head First Design Patterns?

Because it’ll get you up to speed on design patterns as fast as humanly possible.

The Head First books can be a shock – the pictures, crossword puzzles and join the dots
exercises can make you feel like you’re back in elementary school again.

As they carefully explain, this is all in aid of making stuff stick in your brain. So swallow your
pride and do the kooky exercises.

The canonical book on the subject is Design Patterns by the ‘Gang of Four’ (Gamma, Helm,
Johnson & Vlissides, aka ‘GoF’).

I’m not recommending this as a book to start with. Even though the GoF book uses an
example application to illustrate the design patterns, I personally found the context
presented by the Head First book made the subject matter easier to learn. Maybe get
Design Patterns later as a reference because it covers way more patterns than the Head
First book (which covers the most important ones!).

Once you’re comfortable with design patterns, another great book to look at is Patterns of
Enterprise Application Architecture by Martin Fowler. You’ll find this book helpful if
you’re working with .NET or JEE in the enterprise world.

Copyright © 2017 Luke Fabish 256


Clean Code

Copyright © 2017 Luke Fabish 257


Clean Code by Robert “Uncle Bob” Martin is a compendium of things we should be doing
when we code, but often don’t.

Uncle Bob is a character, to put it mildly.

He’s well on the road to becoming the patron saint of confused programmers the world
over, and Clean Code is his message to you when you’re tired, stressed, under pressure or
just sick of what you’re working on: do it right.

The subtitle of the book is “A Handbook of Agile Software Craftsmanship”, and while a lot of
the content has nothing to do with “agile” development, everything in the book will help
you write better code.

All the while Uncle Bob will be right alongside you, reminding you that extraordinary results
require extraordinary effort, inches make champions, how you practice is how you play, and
every other cliché grizzled coaches have yelled to make their teams great. Evangelistic and
charismatic, Uncle Bob also makes it fun.

But don’t think this book is just a cheerleading effort by someone who looks like your
granddad. It’s both a deeply tactical and erudite book on everything from how to choose
good variables and function names through to how to start implementing Test Driven
Development and Refactoring.

It’s such a massive and useful book I’ve been dipping in and out of it for years. I always
come across something I really should be doing better. So I concentrate on applying that
to my work for a while, and then going back for the next thing I can improve.

Really, it’s everything a good programmer should be doing anyway, but sometimes, ahem,
forgets about.

This book sits in the same space as Code Complete, by Steve McConnell. Code Complete is
a very similar book in that it goes into the nitty gritty of writing good, maintainable and
correct code. I prefer Clean Code because it’s a bit more current and covers more territory
that’s relevant to the modern developer.

Copyright © 2017 Luke Fabish 258


Domain Driven Design

This is a massive book, and not as immediately actionable as the last two books I’ve just
discussed.

Copyright © 2017 Luke Fabish 259


But learning from it will be a major investment in your development as a software
professional.

So what’s it all about?

Domain Driven Design, by Eric J. Evans, presents a process for understanding and
modelling complex domains.

Evans defines a domain as a sphere of knowledge, influence or activity (e.g. a invoice


tracking app would be in the ‘accounting’ domain).

The reason this is such a big deal is that while businesses often have very similar domains
(accounting, contracts, sales etc.), they all have complex, arcane and unique processes and
rules for managing those domains.

Large software projects tend not to fail because of technical reasons, but because of an
inability to represent a business domain with complex rules effectively in code.

This is the problem that Domain Driven Design helps solve.

While I cheerfully and heartily recommend this book, I have to give you a couple of
warnings: it’s long, somewhat dense and defines a lot of terminology that’s destined to be
jargon only other domain modellers will understand.

But like I said, it’ll give the tools for dealing with complex business problems successfully.

Not the best books to make you


a better programmer?
If you don’t think these are the best books for you personally, I hope you’ll still take your
professional development as a programmer into your own control.

No matter what book you use to improve, remember to get the most out of it by taking
notes and finding practical ways to use the information from the book as soon as possible.

Copyright © 2017 Luke Fabish 260


Other than that I hope you’ve enjoyed these recommendations, and I’d love to hear about
your personal book recommendations.

Copyright © 2017 Luke Fabish 261


Appendix C – Practice
Challenge Answers

Practice Challenge #1
Here's my code for Practice Challenge #1 – The about page.

Note that the images aren't included (a relief for everyone). I put them in a folder
called 'images' in the same folder as about.html and about.css.

about.html:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>About Me</title>
<link rel="stylesheet" type="text/css" href="./about.css">
</head>
<body>
<div id="content">
<h1>About Me</h1>
<div id="about-img">&nbsp;</div>
<h2>Boiled Sweet Expert</h2>
<p>
That’s right, blindfold me and give me a boiled
sweet and I’ll tell you when it was made, who
made it and 100% of the ingredients. I’m that
good.
</p>
<h3>Super Gargler</h3>
<p>
With a bottle of mouthwash I can gargle the
national anthem of all OECD countries, without
stopping for breath. I achieve this astounding
feat utilising the ancient gargler’s technique of
circular breathing.
</p>
<h3>Hire Me</h3>
<p>
Copyright © 2017 Luke Fabish 262
If these skills are what you’re looking for,
you should get in touch so we can make
sweet gargly business together.
</p>
</div>
</body>
</html>

about.css:

body {
font-family: Arial, Helvetica, sans-serif;
font-size: 18pt;
}

p {
margin-top: 0;
}

#content {
width: 500px;
margin: 0 auto;
}

#about-img {
width: 500px;
height: 500px;
background-image: url('images/about-pic-1-500.jpg');
}

#about-img:hover {
background-image: url('images/about-pic-2-500.jpg');
}

h1, h2, h3, h4 {


margin: 0;
}

h1 {
color: #00ffe4;
font-size: 120pt;
line-height: 130px;
}

h1, h2 {
font-family: Georgia, 'Times New Roman', Times, serif;
}

h2 {
background-color: #00ffe4;
color: #fff;
padding: 5px;
font-size: 45px;
}

Copyright © 2017 Luke Fabish 263


h3 {
margin-top: 45px;
}

Practice Challenge #2
Here's my code for the robot checker, which I christened 'anti-bot.'

anti-bot.html:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>No Bots!</title>
<link rel="stylesheet" type="text/css" href="./anti-bot.css">
<script src="anti-bot.js"></script>
</head>
<body>
<div id="content">
<h1>Robot Test</h1>
<p>
Tell me - what is the product of:
</p>
<form>
<input id="operand1" type="number" readonly>
x
<input id="operand2" type="number" readonly>?
<div>
<input id="answer" type="number" placeholder="Your
answer">
</div>
<button type="button" onclick="checkAnswer()">Check your
answer</button>
</form>
<p id="outcome">&nbsp;</p>
</div>
</body>
</html>

anti-bot.css:

body {
font-family: Arial, Helvetica, sans-serif;
}

h1 {
margin: 0;
font-size: 58px;
font-weight: 300;
}

form {
font-size: 30px;
Copyright © 2017 Luke Fabish 264
}

input {
width: 2em;
font-size: 30px;
}

button {
width: 100%;
font-size: 30px;
margin-top: 5px;
background-color: #eee;
border: 1px solid #aaa;
}

#answer {
width: 10em;
margin-top: 5px;
}

#outcome {
font-size: 30px;
}

#content {
width: 19em;
margin: 0 auto;
border: 1px solid #aaa;
padding: 20px;
}

anti-bot.js:

function randomNumber() {
return Math.floor((Math.random() * 10) + 1);
}

function checkAnswer(e) {
// Even though we've specified a input with type="number", its
// type is still returned as a string. So convert it to a number
// with parseInt().
let inputAnswer = parseInt(userAnswer().value);

// This is a number.
let actualAnswer = firstOperand().value * secondOperand().value;

if (actualAnswer === inputAnswer) {


testOutcome().innerHTML = "You may pass";
testOutcome().style.color = "#0f0"
} else {
testOutcome().innerHTML = "You failed the bot test";
testOutcome().style.color = "#f00"
}
}

Copyright © 2017 Luke Fabish 265


function populateInputs() {
firstOperand().value = randomNumber();
secondOperand().value = randomNumber();
}

function firstOperand() {
return document.getElementById('operand1');
}

function secondOperand() {
return document.getElementById('operand2');
}

function userAnswer() {
return document.getElementById('answer');
}

function testOutcome() {
return document.getElementById('outcome');
}

window.addEventListener('load', populateInputs);

Copyright © 2017 Luke Fabish 266

You might also like